lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I 'm trying to experiment with lambdas for fun . I created a functor which allows the composition of a lambda . But , the means of composition only allow a linear transformation , and does not allow branching.The idea is that I know I will have , in the future , an effectively immutable state data structure . I want to...
import java.util.Objects ; import java.util.function.BiFunction ; @ FunctionalInterfacepublic interface Procedure < S , T > { T procede ( S stateStructure ) ; default < R > Procedure < S , R > andThen ( BiFunction < S , T , R > after ) { Objects.requireNonNull ( after ) ; return ( param ) - > after.apply ( param , proc...
Branching when composing lambdas from other lambdas
Java
I got the following structureNow , I have a list of those points defined.The data does not matter at all , just a list of points ( the above is just an easy and quick example ) .How can I transform this list to a array of doubles ( double [ ] array ) in a Java 8 way ?
public class Point { private final double x ; private final double y ; // imagine required args constructor and getter for both fields } List < Point > points = new ArrayList < > ( ) ; points.add ( new Point ( 0,0 ) ) ; points.add ( new Point ( 0,1 ) ) ; points.add ( new Point ( 0,2 ) ) ; points.add ( new Point ( 0,3 )...
Converting Pair of Double into a double array
Java
I have a List < Map < String , String > > such as : My expect result is to generate a new List map , which is grouped by date , and all the entry set in the same date would be put together , like : I tried with the following method , but always not my expect result.Some Additional Comments for this problem : I worked t...
Map < String , String > m1 = new HashMap < > ( ) ; m1.put ( `` date '' , `` 2020.1.5 '' ) ; m1.put ( `` B '' , `` 10 '' ) ; Map < String , String > m2 = new HashMap < > ( ) ; m2.put ( `` date '' , `` 2020.1.5 '' ) ; m2.put ( `` A '' , `` 20 '' ) ; Map < String , String > m3 = new HashMap < > ( ) ; m3.put ( `` date '' ,...
Java 8 stream grouping a List < Map < > > by the same < Key , Value > to a new List < Map < > >
Java
Possible Duplicates : Can not refer to a non-final variable inside an inner class defined in a different method Why inner classes require “ final ” outer instance variables [ Java ] ? The above code works fine.I want to know why does the compiler give an error if I remove the final keyword from String z . What differen...
class MyOuter { private String x = `` Outer '' ; void doStuff ( ) { final String z = `` local variable '' ; class MyInner { public void seeOuter ( ) { System.out.println ( `` Outer x is '' + x ) ; System.out.println ( `` Local variable z is '' + z ) ; // does // not compile if final keyword from String z is removed } }...
Java Inner Classes
Java
I am having an issue with a hashmap . In my hashmap method i want to have two or more keywords as a key , oppose to having one . For example I want the user to input some sentence containing two or more keywords assuming `` professor name '' is a keyword . For exampleAnd the user enters `` what is the professor name ''...
String [ ] temp3 = { `` instructor '' , '' teacher '' , '' mentor '' } ; responses.put ( `` professor name '' , temp3 ) ; String [ ] temp3 = { `` instructor '' , '' teacher '' , '' mentor '' } ; responses.put ( `` professor '' , temp3 ) ; private static HashMap < String , String [ ] > populateSynonymMap ( ) { String [ ...
Understand two or more keys with Hashmaps
Java
I wanted to learn something more about generics and to do so I decided to write a simple application . It allows to retrieve list of all entities using CriteriaQuery.First of all , I tried to generify code by using type parameter ( T ) . However , my code will not even compile . Why ? I 've come up with another solutio...
private static < T > List < T > retrieveAllT ( Session session , CriteriaBuilder criteriaBuilder , T t ) { CriteriaQuery < t > query = criteriaBuilder.createQuery ( t ) ; Root root = query.from ( t ) ; query.select ( root ) ; return session.createQuery ( query ) .getResultList ( ) ; } private static List < ? > retrieve...
Avoiding unchecked casting using generics
Java
Consider the following set of expressions : An attempt to compile this will fail on line /*1*/ with the error : both when using OpenJDK 1.8.0 ( Ubuntu ) or Oracle JDK 1.8 ( Windows ) .However , Eclipse 4.5.0 ( Mars ) compiles this without any error and it results in : From this you can see that the line /*1*/ of the ja...
class T { { /*1*/ Object o = T.super ; // error : ' . ' expected/*2*/ o.toString ( ) ; } } error : ' . ' expected o = T.super ; ^ class T { T ( ) ; 0 aload_0 [ this ] 1 invokespecial java.lang.Object ( ) [ 8 ] // super ( ) 4 aload_0 [ this ] 5 astore_1 [ o ] // o = T.super 7 invokevirtual java.lang.Object.toString ( ) ...
Is 'T.super ' a legal expression as per JLS ?
Java
I have a table which I need to query , then organize the returned objects into two different lists based on a column value . I can either query the table once , retrieving the column by which I would differentiate the objects and arrange them by looping through the result set , or I can query twice with two different c...
MY_TABLENAME AGE TYPEJohn 25 ASarah 30 BRick 22 ASusan 43 B
Better to query once , then organize objects based on returned column value , or query twice with different conditions ?
Java
I 'm developing a project ( in Java 8 ) that involves the simulation of logic circuits . The circuits are described in an input file that I 'm parsing with ANTLR v4.Using ANTLR 's visitor classes , I build up a Composite structure that stores all of the necessary components to simulate the circuit.Afterwards , I initia...
// module is an ANTLR parse treeBLXCircuit mainCircuit = modelGenerator.visit ( module ) ; Map < BLXSocket , Boolean > valueMap = new HashMap < > ( ) ; List < BLXSocket > inputs = mainCircuit.getInputSockets ( ) ; valueMap.put ( inputs.get ( 0 ) , false ) ; valueMap.put ( inputs.get ( 1 ) , false ) ; valueMap.put ( inp...
Why would calling a dummy function fix a bug ?
Java
I would like to know how ( if it is possible ) could I program a Java class using a data layout Array of Class , for example : but internally the data would be store as a layout of Class of Arrays like this : My objective is that the programmer could programed in a more intuitive style like the first one , but internal...
public class X { double a ; double b ; double c ; } public X array_of_x [ SIZE ] = new X [ SIZE ] ; public class X { double a [ ] = new double [ SIZE ] ; double b [ ] = new double [ SIZE ] ; double c [ ] = new double [ SIZE ] ; } public X class_x = new X ( ) ;
How to automatically convert from Array of Classes to Class of Arrays
Java
I would like to modify the following method so its arguments can be of any type that implements the Comparable interface . The method ’ s return type should be the same as the type of its parameter variables.So in modifying it , I could just use < T extends Comparable < T > > , but how would I go about making the retur...
public static int max ( int a , int b ) { if ( a > b ) return a ; else return b ; }
Modifying a method so the arguments can be any type that implements Comparable
Java
This message pertains strictly to Java . If a method is in a superclass there are two ways the method could be called : Is there any harm in always doing the latter ? As a coding style I prefer the latter because it 's clear at a glance where the method call is coming from . Are there any circumstances where 'super ' i...
foo ( ) ; super.foo ( ) ;
Is there any harm in using super when not needed ?
Java
I 'd like to write some troubleshooting code which i can easily remove from later non debug versions of my program . I came up with : Is Java smart enough to drop the if statement from the final bytecode if debug==false ? Is there a better practice to achieve the goal of keeping debug code out of the final version of a...
final static boolean debug_on=true ; ... if ( debug_on ) { system.out.println ( ) or logger.log ( ... ) }
How smart is Java about if statements with final variables
Java
Edit : this question is malformed to the extent that I can not really fix it , and is a bug somewhere in my project . The root cause of my problem is that myLambda.getClass ( ) should not throw ClassNotFoundException , and the lambda works as expected.Given the class of an interface And a lambda instanceHow can I deter...
Class myIf = MyIf.class ; Object myLambda ; myIf.isInstance ( myLambda )
How to determine if JDK8 lambda can be assigned to type ?
Java
In this book , it says : A limitation of Arrays.asList ( ) is that it takes a best guess about the resulting type of the List , and does n't pay attention to what you are assigning it to.The book is Thinking in Java By Bruce EckelHowever , the following code is working fine , contrary to code shown in this book page 28...
public class Main { public static void main ( String [ ] args ) { List < Snow > snow = Arrays.asList ( new Light ( ) , new Heavy ( ) ) ; } } class Snow { } class Powder extends Snow { } class Light extends Powder { } class Heavy extends Powder { }
The limitation of Arrays.asList ( ) is not true in Thinking in Java 4th Edition
Java
I have a class : When I declare a Generic with wildcard and call getList method , the following assignment is illegal.This seems odd to me because according to the declaration of Generic , it 's natural to create a Generic < T > and get a List < List < T > > when call getList.In fact , it require me to write assignment...
class Generic < T > { List < List < T > > getList ( ) { return null ; } } Generic < ? extends Number > tt = null ; List < List < ? extends Number > > list = tt.getList ( ) ; // this line gives compile error List < ? extends List < ? extends Number > > list = tt.getList ( ) ; // this one is correct
Why is this generic assignment illegal ?
Java
I 'm programming in Java for only a few months so I 'm not that experienced with Java ( some tricks and the basic things I should know though ) .I got a problem which may be obvious but I do n't see it.This is an extract from my code.How can this be true ? These are two separate objects . I do n't get it.The foo method...
public class SomeClass { private final int [ ] numbers = { 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 } ; private LabelText AText = new LabelText ( ' A ' , numbers ) ; private LabelText BText = new LabelText ( ' B ' , numbers ) ; public void foo ( ) { AText.numbers [ 6 ] = -1 ; BText.numbers [ 3 ] = -1 ; if ( BText.numbers ...
Two newly created objects seem to refer to the same address
Java
I am working on a Enterprise application . I am facing some issues while running application in multithreaded environment . I am writing a program in which there is a variable whose value is getting updated ( incremented ) at very fast rate ( for example 10000 updates/persecond ) . A loop runs for certain iterations an...
class test implements Runnable { static ConcurrentHashMap < String , Integer > map = new ConcurrentHashMap < > ( ) ; static AtomicInteger value_to_be_incremented_stored = new AtomicInteger ( 0 ) ; // variable whose value to be updated static AtomicInteger i = new AtomicInteger ( 0 ) ; // this runs the loop @ Override p...
Java Multi-threading : Unexpected result
Java
According to the Java Language Specification , java.lang.Object is the root of Java 's inheritance hierarchy . Unlike C++ or Objective-C , programmers can not specify their own root superclasses . Because of this , I figured it was impossible to actually define java.lang.Object in Java itself . To my surprise , I found...
package java.lang ; public class Object { public static void main ( String [ ] args ) { System.out.println ( `` Hello world from custom java.lang.Object ! `` ) ; } } Error : Main method not found in class java.lang.Object , please define the main method as : public static void main ( String [ ] args )
How is it possible that java.lang.Object is implemented in Java ?
Java
I am given some classes that are unknown to me . Some of them are shown as an example : The task is to redesign method signature types if needed and to add implementation . The bake method should conform to the following : Create objects of class Bakery or any subclass of it according to class argumentFlag compile-time...
class Paper { } class Bakery { } class Cake extends Bakery { } class ReflexiveBaker { /** * Create bakery of the provided class . * * @ param order class of bakery to create * @ return bakery object */ public Object bake ( Class order ) { // Add implementation here } } public Object bake ( Class < ? extends Bakery > or...
Java generics and reflection : class loading
Java
I 'm trying to build a project using JDK 9 , as using the -- release argument to javac means it can build for older versions without needing the corresponding JDK/JRE installed . I need to support Java 6 so my preexisting set up requires Java 6 for the bootstrapClasspath and a further JDK 8 or 9 for gradle and the IDE ...
tasks.withType ( JavaCompile ) { options.compilerArgs.addAll ( [ ' -- release ' , ' 6 ' , `` -Xlint '' ] ) } warning : [ options ] source value 1.6 is obsolete and will be removed in a future releasewarning : [ options ] target value 1.6 is obsolete and will be removed in a future releasewarning : [ options ] To suppre...
Targeting Java 6 with Java 9 JDK gives warnings
Java
I have a base class ShapeManager with a list of shapes which I want toenumerate ( ) . Then there is a specialization ColoredShapeManager which wantsto process specialized ColoredShapes instead of Shapes : I am unsure whether ShapeManager should share shapes : List < Shape > with itschildren This seems flawed since Colo...
+ -- -- -- -- -- -- -- -- + + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+| Shape | | ShapeManager || -- -- -- -- -- -- -- -- | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| + id : int | | # shapes : List < Shape > || | | || | | + ShapeManager ( ) { || | | shapes.add ( new Shape ( ) ) ; || | |...
Sharing a list of base type with children
Java
I am in the midst of creating an online contact management tool for users to manage contacts and clients . I am trying to develop a solution where the user will add a BCC or CC in any email client like this : and my app will grab the recipients to address information email , name , etc and my backend script will grab t...
1234 @ myappdomain.12345.com
create an email drop box with php , javascript etc
Java
I was trying create an array of a collection as follows.but it gives me an error - > generic array creationcan anybody explain me why is it ?
ArrayList < Integer > ar [ ] =new ArrayList < Integer > [ 50 ] ;
Can we have an Array of a collection ?
Java
Bear with me ... I do n't think this is too subjective but maybe I 'm wrong.Recently I wanted to factor out some repetitive code which drew a custom Bitmap background on our BlackBerry app . ( This question is not really about BlackBerry though , so I 'll provide some details here about the BB GUI so that non-BB Java p...
abstract public class BGFullScreen extends FullScreen { Bitmap bg ; public BGFullScreen ( Manager mgr , long style ) { super ( mgr , style ) ; bg = Bitmap.getBitmapResource ( `` bg.jpg '' ) ; } abstract protected void innerPaint ( Graphics g ) ; protected void paint ( Graphics g ) { g.drawBitmap ( new XYRect ( 0 , 0 , ...
Is this idiomatic Java ?
Java
I have a loop that is running until the user clicks a ready button , and then it starts the the loop inside the if-statement , but it only works it there is a print statement before it . Does it have to do with how the Rule Set is static ? The Button works no matter what , but it only enters the loop if the print state...
package gameoflife ; public class GameOfLife { public static final int HEIGHT = 16 ; public static final int LENGTH = 16 ; public static Grid current ; public static void main ( String [ ] args ) { Ui gui = new Ui ( ) ; int time = 0 ; while ( true ) { RuleSet.checkReady ( ) ; //System.out.println ( RuleSet.checkReady (...
If statement only entering if print before
Java
A Local Cluster from a web classloaderI 'm trying to run a local cluster from a web container ( yes , it 's only for dev & testing purposes ) and am having difficulty with classloaders.Direct approachWhen I do it the easy and recommended way , I get rewarded withThis is because the classloader used to load and instanti...
ILocalCluster localCluster = new LocalCluster ( ) ; localCluster.submitTopology ( topologyName , stormConf , topology ) ; Async loop died ! : java.lang.ClassCastException : my.company.storm.bolt.SomeFilteringBolt can not be cast to org.apache.storm.task.IBolt at org.apache.storm.daemon.executor $ fn__7953 $ fn__7966.in...
Run a local cluster under a nondefault classloader
Java
I 've been trying to figure out how to find a O ( n ) time complexity algorithm to solve the following in Java : We are given an input pair with a start point and end point , and we have to construct a path such that the start of one input matches the end of another input ( in this case , alphabetically ) EX : if I hav...
for inputs parse input add parse [ 1 ] to starts , add parse [ 2 ] to endsfor starts find origin ( a start not in ends ) < -- requires hash ? if no origin cycle existsfor inputs find ends [ origin ] < -- requires hash ? origin = ends [ origin ] < -- so we can find the next one
Path reconstruction with Hashing ?
Java
Chrome is not stable on my Jenkins . When I run build 5 times , it runs 1 - 2-time success , and the other 3 times I have the above error.Snapshot of the error : Code for Chrome : Some steps I have already taken : Provided 777 permission to google chrome and chrome driverSet : Start Xvfb before the build , and shut it ...
ChromeOptions options = new ChromeOptions ( ) ; System.setProperty ( `` webdriver.chrome.driver '' , '' /usr/local/bin/chromedriver '' ) ; options.addArguments ( `` -- headless '' ) ; options.addArguments ( `` -- no-sandbox '' ) ; options.addArguments ( `` -- disable-dev-shm-usage '' ) ; driver = new ChromeDriver ( opt...
org.openqa.selenium.WebDriverException : unknown error : Chrome failed to start : crashed using ChromeDriver Selenium in Jenkins on Ubuntu 18.04
Java
I have this Java problem , which I suspect it relates to a higher-level algorithm , but my searches have n't been able to come up with anything practical.You construct an array as follows : Basically , Ai , j = Ai-1 , j-1+Ai-1 , j . It 's supposed to return the element at index ( l , c ) : for ( 4 , 1 ) it should retur...
11 11 2 11 3 3 11 4 6 4 11 5 10 10 5 1 static long get ( int l , int c ) { long [ ] [ ] matrix = new long [ l+1 ] [ l+1 ] ; matrix [ 0 ] [ 0 ] =1 ; matrix [ 1 ] [ 0 ] =1 ; matrix [ 1 ] [ 1 ] =1 ; for ( int i=2 ; i < =l ; i++ ) { matrix [ i ] [ 0 ] =1 ; for ( int j=1 ; j < =i ; j++ ) { matrix [ i ] [ j ] = matrix [ i-1 ...
Calculate element in matrix incrementally , using neighbors
Java
I want to create a big array , and want to try out some lambda , but for some reason that : wont work , even that : dose not work.The compiler error is : Type mismatch : can not convert from boolean to Tand : The method setAll ( T [ ] , IntFunction ) in the type Arrays is not applicable for the arguments ( boolean [ ] ...
cells = new boolean [ this.collums ] [ this.rows ] ; IntStream.range ( 0 , cells.length ) .forEach ( x - > Arrays.setAll ( cells [ x ] , e - > MathX.fastNextInt ( 1 ) == 0 ? true : false ) ) ; cells = new boolean [ this.collums ] [ this.rows ] ; IntStream.range ( 0 , cells.length ) .forEach ( x - > Arrays.setAll ( cell...
Arrays.setAll wont work with boolean
Java
I 've been trying to take a sub list of a list , reverse it , and place the reversed list back into the starting position . For example , say we have the list [ 1 , 2 , 3 , 4 , 5 , 6 ] , then reversing from index 2 to index 4 would give [ 1 , 2 , 5 , 4 , 3 , 6 ] .I 've written some code for this , however it gives a Co...
int startIndex = 2 ; int endIndex = 4 ; List < Integer > list = new ArrayList < > ( ) ; list.add ( 1 ) ; list.add ( 2 ) ; list.add ( 3 ) ; list.add ( 4 ) ; list.add ( 5 ) ; list.add ( 6 ) ; List < Integer > toReverse = list.subList ( startIndex , endIndex+1 ) ; Collections.reverse ( toReverse ) ; list.removeAll ( toRev...
Why does List.addAll of a reversed subList of the list cause a ConcurrentModificationException
Java
This is a continuation of this questionSpring WebMvcTest how to mock Authentication ? I 'm trying to test a controller method in Spring-boot that receives an Authentication object as parameter . The controller is a RestController with @ CrossOrigin annotation . The method looks like this : As you can see i get the prin...
@ GetMapping ( `` /authentication '' ) public String testAuthentication ( Authentication authentication ) { UserDetailsStub userDetailsStub = ( UserDetailsStub ) authentication.getPrincipal ( ) ; return userDetailsStub.getUsername ( ) ; } @ Import ( SecurityConfiguration.class ) @ RunWith ( SpringRunner.class ) @ WebMv...
Spring-Boot WebMvcTest : How to test controller method with Authentication object parameter ?
Java
I am performing some actions on a stream and returning an array list . This is working without a problem but I need to do a final step to add an element if the array list is empty ( nothing to do with options / nulls just part of the requirement ) My way is a bit clunky and I wondered if it can be done in the stream op...
public ArrayList < String > getArrayList ( ) { ArrayList < String > aL = setOfStrings.stream ( ) .filter ( remove some ) .filter ( remove some more ) .map ( i - > createStringAbout ( i ) ) .collect ( Collectors.toCollection ( ArrayList : :new ) ) ; if ( aL.size ( ) < 1 ) { aL.add ( `` No items passed the test '' ) ; } ...
Add a default item to a stream collection
Java
I 'm pretty new to the Java World ( since I 'm writing primary in C/C++ ) . I 'm using maps in my apps.Since java.util.Map is abstract I need to instantiate it 's implementation . Usually I use HashMap like : But in java docs I found many other implementations , like TreeMap , LinkedHashMap , HashTable , etc . I want t...
Map < String , MyClass > x = new HashMap < > ( ) ;
java : maps zoo , what to choose
Java
I want to sort a map using Java 8 streams and return a list of its key.Map signature is : and the data will be like [ 1=6 , 5=13 , 2=11 ] There are two conditions on which I have to sort and return a list of keys.If all the values of the keys are different , then sort and return a list based values in descending order ...
Map < Integer , Integer > ranks = new HashMap < Integer , Integer > ( ) ; input [ 1=6 , 5=13 , 2= 11 , 4 = 14 ] result [ 4,5,2,1 ] input [ 2=6 , 5=13 , 1= 11 , 3=13 ,9 = 22 ] result [ 9,3,5,1,2 ] List < Integer > ranksList = ranks.entrySet ( ) .stream ( ) .sorted ( Map.Entry.comparingByValue ( Comparator.reverseOrder (...
How to define custom sorted comparator in java 8 Stream to compare on the key and the value
Java
In my Java application a small put important feature is to be able to rename audio files based on their metadata ( e.g album/artist -title ) and the mask is specified using Javascript , this makes for a very flexible and powerful renaming feature . I knew Javascript was being deprecated but it now seems it is actually ...
try { mask = includeUserDefinedFunctions ( mask ) ; ScriptEngine engine = manager.getEngineByName ( `` JavaScript '' ) ; for ( SongFieldName next : SongFieldName.values ( ) ) { if ( next.getScriptVar ( ) ! =null & & next.getSongFieldKey ( ) ! =null ) { engine.put ( next.getScriptVar ( ) , cleanValue ( song.getFieldValu...
How can I continue to use Javascript in Java 15 onwards
Java
In the code below , the instance variable called `` x '' inside subclass `` B '' hides the instance variable also called `` x '' inside the parent superclass `` A '' .In the code below , why does println ( z.x ) display the value of zero ? Thanks .
public class A { public int x ; } public class B extends A { public int x ; } A a = new A ( ) ; B b = new B ( ) ; a.x = 1 ; b.x = 2 ; A z = b ; System.out.println ( z.x ) ; // Prints 0 , but why ?
Instance variable hiding with inheritance
Java
I 'm trying to use Java Opencl from within jruby , but am encountering a problem which I ca n't solve , even with much google searching.when I run this code using : jruby test.rbI get the following error , when the last line is uncommented : Just wondering whether anyone has an idea on how to solve this problem ? EDIT ...
require 'java'require 'JOCL-0.1.7.jar'platforms = org.jocl.cl_platform_id.newputs platforms.classorg.jocl.CL.clGetPlatformIDs ( 1 , platforms , nil ) # < Class:0x10191777e > TypeError : can not convert instance of class org.jruby.java.proxies.ConcreteJavaProxy to class [ Lorg.jocl.cl_platform_id ; LukeTest at test.rb:2...
Trouble using java class within jruby
Java
While testing , I upgraded my Junit to 5.0 ( Thus replacing some of my assertTrue ( ) methods with the new versions ) . After doing so , I found one of my tests did n't compile . I reduced the issue down to plain old java with no junit or other dependencies . The result is the following code which will not compile : As...
public static void recreate ( ) { // This does NOT work Recreation.assertTrue ( identity ( ( x ) - > Boolean.TRUE ) ) ; // This DOES work Recreation.assertTrue ( identity ( ( String x ) - > Boolean.TRUE ) ) ; } private static class Recreation { public static void assertTrue ( boolean b ) { System.out.println ( `` boole...
Java can not compile generic lambda argument unless parameter type is specified
Java
Sample code to demonstrate the failure : Here is the Error ( not Exception ) I see : I am using 32-bit Java 8 ( v1.8.0_60 ) with Google Guava v19.0 . My Google-Fu tells me Google Guice is the root cause , but lacks credible explanation . ( This is part of a much larger project that also includes Google Guice v3.0 via A...
package ia.quant.nextgen.entry ; import com.google.common.collect.ArrayListMultimap ; import java.util.function.Consumer ; /** * Created by arpeke on 2015-12-18 . */public final class SampleMain { public static void main ( String [ ] argArr ) { final ArrayListMultimap < Void , Void > arrayListMultimap = ArrayListMultim...
Why does Google Guava 's ArrayListMultimap clear method throw IllegalAccessError when called by method reference ?
Java
I was just trying something with try-catch and this code : I understand Error will not be caught by the catch block above , but the finally block will be executed , and then the JVM will terminate.But when I try to run the program many times , I get different outputs : C printed before the stack trace : or C printed af...
public class MainThread { public static void main ( String [ ] args ) { try { badMethod ( ) ; System.out.print ( `` A '' ) ; } catch ( Exception ex ) { System.out.print ( `` B '' ) ; } finally { System.out.print ( `` C '' ) ; } System.out.print ( `` D '' ) ; } public static void badMethod ( ) { throw new Error ( ) ; /*...
In case of Error , program shows unexpected behavior
Java
Testing some things out I tried o make an enum in which every one element in a enum have a different class inside.Take for example : If i try to put a public modifier before any class , the Modifier not allowed here shows up . I am not quite sure why this would be . I can not instantiate those classes outside the enum ...
public enum MyEnum { first { class First { } } , second { class Second { } } ; } public enum MyEnum { first { class First { } public Object getObject ( ) { return new First ( ) ; } } , second { class Second { } public Object getObject ( ) { return new Second ( ) ; } } ; public abstract Object getObject ( ) ; } public c...
Why cant I make an enum 's inner class public ?
Java
I have a question about using generics with collections . We know that the above line means that ArrayList al is restricted to hold only integers . So the following line gives a compilation error : But I do n't understand what the below line means , Where we do n't give ArrayList < Integer > at the left side while decl...
ArrayList < Integer > al=new ArrayList < Integer > ( ) ; al.add ( `` wwww '' ) ; ArrayList al=new ArrayList < Integer > ( ) ; al.add ( `` wwww '' ) ; ArrayList al=new ArrayList < Integer > ( ) ;
Collection with generics
Java
I have these statements : This compiles perfectly . And outputs But : outputsI did some research on this topic . I read the documentation , and it says : This method can not handle supplementary characters . To support all Unicode characters , including supplementary characters , use the isJavaIdentifierStart ( int ) m...
int \u65549 = 9 ; System.out.println ( \u65549 ) ; 9 System.out.println ( Character.isJavaIdentifierStart ( \u65549 ) ) ; false int x = \u65549 ; System.out.println ( Character.isJavaIdentifierStart ( x ) ) ; false
Is \u65549 a valid Java identifier ?
Java
I 'm reading on Joshua Bloch 's Effective Java , 2nd edition , Item 11 : Override clone judiciously . On page 56 , he is trying to explain that when we override clone ( ) for some classes ( like collection classes ) , we must copy the internals of it . He then gives the example of designing a class Stack : He claims th...
public class Stack { private Object [ ] elements ; private int size = 0 ; private static final int DEFAULT_INITIAL_CAPACITY = 16 ; public Stack ( ) { ... } public void push ( Object e ) { ... } public Object pop ( ) { ... } private void ensureCapacity ( ) { ... } //omitted for simplicity } @ Override public Stack clone...
Effective Java claims that elements.clone ( ) suffices
Java
Consider the following Java function : This does not work , since the type captures of cl and ls are not unified and can , indeed , refer to different types . Had this function compiled , I could have called it as foo ( NullPointerException.class , new List < SecurityException > ( ) ) , which would have been illegal.We...
public void foo ( Class < ? extends Exception > cl , List < ? extends Exception > ls ) throws Exception { ls.add ( cl.newInstance ( ) ) ; } public < T extends Exception > void foo ( Class < T > cl , List < T > ls ) throws Exception { ls.add ( cl.newInstance ( ) ) ; } private Map < Class < ? extends Foo > , ? extends Fo...
Can captures in Java generics be unified in type declarations ?
Java
Here 's the context if it 's necessary for any answers . I 'm building an engine in which I 'm going to make a videogame . It involves a 96 x 54 ( columns x rows ) table of letters , to keep an even spacing between them . Because of this , it would be very helpful if any solutions could be as least resource intensive a...
import javax.swing . * ; import static java.lang.Math . * ; import java.awt . * ; public class transparencyExample { //Declaring constants public static final Color [ ] MAINFRAME = { new Color ( 0x35ce4a ) , new Color ( 0x111111 ) } ; //Creating static variables and methods private static JLabel tempLabel ; private sta...
Allow text in multiple JLabels to overlap
Java
Consider this method : As you can see the set is creating a new TreeSet with a custom comparator . I was wondering if it makes any difference from a performance/memory/garbage collection/whatever point of view , if I were to do this and instead having polluted the outer space : The reason I am asking , is that I feel t...
private void iterate ( List < Worker > workers ) { SortedSet < Worker > set = new TreeSet < > ( new Comparator < Worker > ( ) { @ Override public int compare ( Worker w0 , Worker w1 ) { return Double.compare ( w0.average , w1.average ) ; } } ) ; // ... } static final Comparator < Worker > COMPARATOR = new Comparator < ...
Is extracting to static final necessary for Java optimization ?
Java
By default , Java does Binary Numeric Promotion for primitives , but does not do the same thing for objects . Here 's a quick test to demonstrate : Output : This is obviously correct behavior - an Integer is not a Long . However , does there exist a `` value equals '' for Number subclasses that would return true the sa...
public static void main ( String ... args ) { if ( 100 == 100L ) System.out.println ( `` first trial happened '' ) ; if ( Integer.valueOf ( 100 ) .equals ( Long.valueOf ( 100 ) ) ) { System.out.println ( `` second trial was true '' ) ; } else { System.out.println ( `` second trial was false '' ) ; } if ( 100D == 100L )...
Is there a number `` value equals '' ?
Java
The following code measure the time it takes for 100 invocations of the method handle ( Object o ) from the interface Handler ( Yes it 's bad quality profiling ) : The fact is that if the LinkedList contains only one kind of Handler , for example SuperHandler , the execution time is smaller than if they were 2 , 3 , et...
package test ; import java.util.LinkedList ; public class Test { static int i = 0 ; private interface Handler { public void handle ( Object o ) ; } private static class SuperHandler implements Handler { public void handle ( Object o ) { i += 1 ; } } private static class NoSuperHandler implements Handler { public void h...
Java - LinkedList - Performance decreases with the number of different classes in it
Java
In the JSR-133 , there are two example that state presumably correctly synchronized programs.The first example is given by figure 6 where : Then , thread 1 modifies the state by : and thread 2 modifies the state by : The author states that this program is correctly synchronized,However , there is an execution of this p...
x == y == 0 r1 = x ; if ( r1 ! = 0 ) y = 1 ; r2 = y ; if ( r2 ! = 0 ) x = 1 ; x == y == 0 r1 = x ; y = r1 ; r2 = y ; x = r2 ;
How to understand JSR-133 Happens-Before is too Weak Figure6/7
Java
Java has two ways of checking whether two booleans differ . You can compare them with ! = , or with ^ ( xor ) . Of course , these two operators produce the same result in all cases . Still , it makes sense for both of them to be included , as discussed , for example , in What 's the difference between XOR and NOT-EQUAL...
class Test { public boolean xor ( boolean p , boolean q ) { return p ^ q ; } public boolean inequal ( boolean p , boolean q ) { return p ! = q ; } } $ javap -c TestCompiled from `` Test.java '' class Test { Test ( ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : retur...
Is there a useful difference between ( p ^ q ) and ( p ! = q ) for booleans ?
Java
Benchmarking the following Java code using jmh : Using mvn package & & java -XX : -UseCompressedOops -XX : CompileCommand='print , *.testMethod ' -jar target/benchmarks.jar -wi 10 -i 1 -f 1 , I was able to get the assembly , and if we focus on the one from C2 ( as shown below ) , we can see that both cos and sin are ca...
interface MyInterface { public int test ( int i ) ; } class A implements MyInterface { public int test ( int i ) { return ( int ) Math.sin ( Math.cos ( i ) ) ; } } @ State ( Scope.Thread ) public class MyBenchmark { public MyInterface inter ; @ Setup ( Level.Trial ) public void init ( ) { inter = new A ( ) ; } @ Benchm...
JVM JIT method recalculate for pure methods
Java
I have a string that looks like this : [ `` 1011000 '' , `` 1000010 '' , `` 1001101 '' , `` 1000011 '' ] .My argument is coming from elsewhere so it needs to be this way.I need to typecast this to a real byte array.Here 's my method : It does n't work , however . Complains about inconvertable types String to byte.Can a...
public void send ( String [ ] payloadarr ) throws IOException { byte [ ] payload = { } ; for ( int i = 0 ; i < payloadarr.length ; i++ ) { byte x = ( byte ) payloadarr [ i ] ; payload [ i ] = x ; } //do byte stuff with payload }
Help typecasting a String Array of bytes to actual bytes
Java
I 'm trying to read N items from a RingBuffer using readManyAsync but It 's always returns an empty resultSet . If I use readOne I get data.I 'm using the readManyAsync as the documentation specify . There is another way to do that ? Enviroment : Java 8Hazelcast 3.5.3Example : Output :
Ringbuffer < String > buffer = this.hazelcastInstance.getRingbuffer ( `` testBuffer '' ) ; buffer.add ( `` a '' ) ; buffer.add ( `` b '' ) ; buffer.add ( `` c '' ) ; Long sequence = buffer.headSequence ( ) ; ICompletableFuture < ReadResultSet < String > > resultSetFuture = buffer.readManyAsync ( sequence , 0 , 3 , null...
Hazelcast Ringbuffer readManyAsync returns Empty Results
Java
I 've got one ClassLoader for trusted application code and a seperate ClassLoader for user-submitted ( untrusted ) code.I want the user-submitted code to be restricted by the Security Manager . How do I check the caller origin from within the SecurityManager ? See the psuedocode : What I 've tried already : StackWalker...
System.setSecurityManager ( new SecurityManager ( ) { public void checkPermission ( Permission permission ) { if ( /*caller class is not loaded by the trusted classloader*/ ) { throw new SecurityException ( `` You do not have permissions . `` ) ; } } } ) ;
How to check caller class origin in SecurityManager ?
Java
In the below code , the line System.out.println ( sumInteger ( bigs ) == sumInteger ( bigs ) ) ; displays as false . But when again we compare the another Integer wrapper classes System.out.println ( bc == ab ) ; , it returns true . Why is the comparison of wrapper classes false in the first case and true in the second...
import java.util.Arrays ; import java.util.List ; public class Arrays { public void array1 ( ) { List < Integer > bigs = Arrays.asList ( 100,200,300 ) ; System.out.println ( sumInteger ( bigs ) == sum ( bigs ) ) ; // 1 . Output : true System.out.println ( sumInteger ( bigs ) == sumInteger ( bigs ) ) ; //2 . Output : fa...
Wrapper classes and generic clarifications in Java
Java
I have checked the source code for java.lang.Enum and the method T valueOf ( Class < T > enumType , String name ) beginning on line 232 ( the implementation in both java-8 and java-11 seems equal ; here is the source for Java 8 ) .What is the reason the null check for name happens after finding the enumeration by name ...
public static < T extends Enum < T > > T valueOf ( Class < T > enumType , String name ) { T result = enumType.enumConstantDirectory ( ) .get ( name ) ; if ( result ! = null ) return result ; if ( name == null ) throw new NullPointerException ( `` Name is null '' ) ; throw new IllegalArgumentException ( `` No enum const...
Why does n't java.lang.Enum : :valueOf check for the null name first ?
Java
Some devices ( e.g . webrelays ) return raw XML in response to HTTPGet requests . That is , the reply contains no valid HTTP header . For many years I have retrieved information from such devices using code like this : In openJdk 7 the following lines have been added to sun.net.www.protocol.http.HttpURLConnection , whi...
private InputStream doRawGET ( String url ) throws MalformedURLException , IOException { try { URL url = new URL ( url ) ; HttpURLConnection con = ( HttpURLConnection ) url.openConnection ( ) ; con.setConnectTimeout ( 5000 ) ; con.setReadTimeout ( 5000 ) ; return con.getInputStream ( ) ; } catch ( SocketTimeoutExceptio...
Retrieving XML over HTTP in Java 7
Java
I 'm using Jersey 1.12 and have an endpoint that may or may not receive malformed headers from clients that i do n't control ( for instance `` Content-Type '' : '' application/json ; bla-bla '' ) Obviously bla-bla is malformed as the spec requires parameters to have values as well i.e . bla-bla=value and thus Jersey wi...
`` status '' : 400 , '' message '' : `` Bad Content-Type header value : 'application/json ; bla-bla ' ''
How to have Jersey pass malformed headers
Java
I came up with two expressions to assign value from a bit operation to a variable , and noticed `` x+=y '' and `` x=x+y '' yielded different results in this case : I did some research , and found the only case `` x+=y '' and `` x=x+y '' is not equivalent is when operant types are not the same , however in this case , `...
public void random ( ) { int n = 43261596 ; System.out.println ( Integer.toBinaryString ( n ) ) ; n = n + 0 & 1 ; //binary representation of n is 0 //n += 0 & 1 ; //result is the same as n System.out.println ( Integer.toBinaryString ( n ) ) ; }
Java `` x += y '' and `` x = x+y '' yields different result
Java
I sometimes have a need for classes that should only be instantiated once during the lifecycle of the application . Making them singletons is bad because then unit testing becomes problematic.But still , because there should be one and only instance of such objects during the lifecycle of my application , it would be a...
/** * The key words `` MUST '' , `` MUST NOT '' , `` REQUIRED '' , `` SHALL '' , `` SHALL NOT '' , * `` SHOULD '' , `` SHOULD NOT '' , `` RECOMMENDED '' , `` MAY '' , and `` OPTIONAL '' in this * document are to be interpreted as described in RFC 2119 . * * You MUST NOT instantiate this class more than once during the ...
How to implement a near-singleton ?
Java
I have the following static factory method that creates a list view out of an int array : In `` Effective Java '' , Joshua Bloch mentioned this as an Adapter that allows an int array to be viewed as a list of Integer instances.However , I remember that Adapter uses composition and the instance of the anonymous list imp...
public static List < Integer > newInstance ( final int [ ] numbers ) { return new AbstractList < Integer > ( ) { @ Override public Integer get ( int index ) { return numbers [ index ] ; } @ Override public int size ( ) { return numbers.length ; } } ; } public static void main ( String [ ] args ) { int [ ] sequence = { ...
Where is final parameter stored in anonymous class instance ?
Java
In other words , is the following line guranteed to print num lines ? This question was triggered by a discussion in the comments of https : //stackoverflow.com/a/41346586/2513200I vaguely remember a discussion that optimizations that avoid iteration might be legal , but did n't find anything conclusive during a quick ...
int num = list.stream ( ) .peek ( System.out : :println ) .count ( ) ;
Is Stream.count ( ) guranteed to visit each element ?
Java
i have following structure : Now i want to disregard the First-level-Maps and group ( and sum up ) the 3rd-Level-Maps according to the key of the 2nd-Level-Maps.To Clarify some example-Entries : Desired output : So to do this I first group my Entry-stream according to my 2nd-Level-Keys ( `` A '' , '' B '' ) and , if no...
Map < String , Map < String , Map < String , Integer > > > Entry 1 : [ `` 1 '' [ `` A '' [ [ a,1 ] ; [ b,2 ] ] ; '' B '' [ [ a,3 ] ; [ c,1 ] ] ] ] Entry 2 : [ `` 2 '' [ `` A '' [ [ b,2 ] ; [ c,1 ] ] ; '' B '' [ [ a,5 ] ; [ b,0 ] ] ] ] Entry 1 : [ `` A '' [ [ a,1 ] ; [ b,4 ] ; [ c,1 ] ] ] Entry 4 : [ `` B '' [ [ a,8 ] ;...
Grouping of inner Maps with Java Streams
Java
I have the following types of requests.Few field examples : Mongo DB data format : Mongo DB stores user order details . Each order contains user detail [ 10 fields ] and order details [ 30 fields ] API has to give by default last 30 days of orders if no date is mentioned.My question : How can I efficiently read this da...
server/controllerName/access_id/id/field/field_value/api_nameserver/controllerName/access_id/id/field/field_value/field2/field_value/api_name 1. start date and end date2 . user name3 . user group { `` name '' : '' gibbs '' , `` category '' : '' vip '' } { user : `` gibbs '' , total_Result : 10 , [ { //order details ite...
Accessing data from mongodb
Java
I am trying to write unit tests for my Javalin.io web application . There are a few references to Mockito being used for mocking the Context objects , which is Javalins way to give the user access to the incoming web requests . I am trying to mock the .header ( String ) method of the Context class because the unit unde...
< dependency > < groupId > org.mockito < /groupId > < artifactId > mockito-core < /artifactId > < version > 3.2.0 < /version > < scope > test < /scope > < /dependency > @ Test void stupidTest1 ( ) { Context context = mock ( Context.class ) ; String test1 = `` hello123 '' ; when ( context.header ( `` Authorization '' ) ...
Final Kotlin class can not be mocked because method `` should return Validator ''
Java
I have some code that takes an externally provided class name , and needs to construct an instance that implements some interface , lets call it Foo.As part of this process , I 'd like to have the following function : This obviously results in an unchecked warning , as it is genuinely unsafe - the caller may have reque...
private static Class < ? extends Foo > fooFromClassName ( String name ) throws ClassNotFoundException { return ( Class < ? extends Foo > ) Class.forName ( name ) ; } private static Class < ? extends Foo > fooFromClassName ( String name ) throws ClassNotFoundException { Class < ? > impl = Class.forName ( name ) ; if ( F...
Unchecked cast when bounding the generic parameter to Class < ? >
Java
This code uses Spring 3.1 and junit4 and spring-test 3.1 . I want to turn this code using and loading junit3.8.x . This is due to a legacy build system . How can I do this ? Most of the online documentation for spring is centered around the approach below . I need to be able to 'load the spring classes ' . In this case...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : context= '' http : //www.springframework.org/schema/context '' xmlns : mvc= '' http : //www.springframework.org/schema/mvc '' xsi...
How can I turn this 'spring 3.1 ' oriented junit4 test with SpringJUnit4ClassRunner into a spring oriented junit3.8 based test ?
Java
Thare are two input lists as follows : My preferred output list must be as follows : What I have done so far looks like below : The output I am getting is as followsProblem is with the elements that does n't have their name in the list inputB . There order does n't have the original order in inputA . For the original o...
inputA = [ { name : `` A '' , age : 20 } , { name : `` B '' , age : 30 } , { name : `` C '' , age : 25 } , { name : `` D '' , age : 28 } ] inputB = [ `` D '' , `` B '' ] expectedOutput = [ { name : `` D '' , age : 28 } , { name : `` B '' , age : 30 } , { name : `` A '' , age : 20 } , { name : `` C '' , age : 25 } ] Ato...
Sort object List by another List using Java Comparators
Java
http : //docs.oracle.com/javase/6/docs/api/java/util/Random.html # nextInt % 28int % 29 says : The algorithm is slightly tricky . It rejects values that would result in an uneven distribution ( due to the fact that 2^31 is not divisible by n ) . The probability of a value being rejected depends on n. The worst case is ...
int bits , val ; do { bits = next ( 31 ) ; val = bits % n ; } while ( bits - val + ( n-1 ) < 0 ) ;
Why 2^31 is not divisible by n ?
Java
I have found somewhere a pretty weird number declaration in Java.I am curious why the value of x is 5.0
double x = 0xap-001 ;
Java - curious number declaration
Java
I 'm just starting out with JavaFX , and I wanted to put a WebView into a Window : It looks ever so simple , but for some reason the draw regions are being highlighted with red and green when moving the mouse around . How can I disable the flashing colors ? Update : the problem is with Groovy/Gradle interactionHere 's ...
public static class HelloJavaFXWeb extends Application { @ Override public void start ( Stage stage ) throws Exception { final Group root = new Group ( ) ; Scene scene = new Scene ( root , Color.DODGERBLUE ) ; WebView webView = new WebView ( ) ; webView.getEngine ( ) .load ( `` http : //www.google.com '' ) ; root.getCh...
Why is JavaFX 's WebView is flashing red and green ?
Java
I trying to get my JButton to stop its background change when clicked . I have been reading and testing answers from other questions like such but none have helped me . I am very new to Java so specific details would be helpful , here is my code and a demonstration of what is happening . Also , I am running ubuntu if t...
import javax.swing . * ; import java.awt . * ; public class RaisedButton extends JButton { private String text = `` '' ; private String type = `` default '' ; public RaisedButton ( String text , String type ) { this.text = text ; this.type = type ; __init__ ( ) ; } private void foundations ( ) { NotoFont noto = new Not...
Stop button from being highlighted when clicked in swing
Java
I plan to execute a jar command using a jar that is included in another jar.The command will automatically obfuscate a Java jar file using code similar to : allatori.jar file is included in my main.jar file as a resource . config.xml file is also included.How can I run my command so that it executes the included jar fi...
public void obfuscate ( ) { try { String jre = `` \ '' '' + System.getProperty ( `` java.home '' ) + `` \\bin\\javaw.exe '' + `` \ '' '' ; String jar = `` -jar '' ; Runtime.getRuntime ( ) .exec ( new String [ ] { jre , jar.trim ( ) , `` /lib/allatori.jar /lib/config.xml '' } ) ; } catch ( Exception e ) { e.printStackTr...
How do I execute a jar from inside a jar ?
Java
I have some code that compiles with javac 1.8.0_92 : However , with javac 1.8.0_45 , some extra types are required ( L ) : As you can imagine , this causes issues for packages that a user builds from source . Why is this ? Is this a bug with that particular build of Java ?
public final class Either < L , R > { // ... private final L l ; private final R r ; // ... public < T > T join ( final Function < L , T > f , final Function < R , T > g ) { Preconditions.checkNotNull ( f ) ; Preconditions.checkNotNull ( g ) ; return which == LeftOrRight.LEFT ? f.apply ( l ) : g.apply ( r ) ; } public ...
Java type inference differences between javac 1.8.0_45 and javac 1.8.0_92 ?
Java
I 'm trying to parse a week-based-year and week-of-week-based-year from a string without any separator character . E.g . `` 201812 '' ( week 12 of year 2018 ) . Like this : But this gives me : If I add a space between the fields like so : It works fine , with result : Is this another bug like this one ? Or am I missing...
DateTimeFormatter formatter = new DateTimeFormatterBuilder ( ) .appendPattern ( `` YYYYww '' ) .parseDefaulting ( WeekFields.ISO.dayOfWeek ( ) , 1 ) .toFormatter ( ) ; LocalDate parse = LocalDate.parse ( `` 201803 '' , formatter ) ; java.time.format.DateTimeParseException : Text '201803 ' could not be parsed at index 0...
Parse week-based-year and week-of-week-based-year without separator character fails
Java
I want to use camunda-bpm-assert-scenario in my ScalaTests.There I have this code with receiveTask : :receive : According to answer in Is it possible to use a Java 8 style method references in Scala ? I can translate this quite easily to : But this gives me : This is the receive function : And here is the expected inte...
when ( documentRequest.waitsAtReceiveTask ( `` ReceiveTaskWaitForDocuments '' ) ) .thenReturn ( ( receiveTask ) - > { receiveTask.defer ( `` P1DT1M '' , receiveTask : :receive ) ; } ) ; receiveTask.defer ( `` P1D '' , receiveTask.receive _ ) Error : ( 84 , 45 ) type mismatch ; found : Unit required : org.camunda.bpm.sc...
How to translate the Java double colon operator ( : : ) to Scala ?
Java
I was trying to create a few scenarios to demonstrate visibility issues while sharing variable across threads . And I noticed that in almost all the cases I tested , if inside run ( ) I added a System.out.println ( ) statement in the same block of code where I am using the shared variable , the visibility issue is not ...
public class NoVisibility_Demonstration extends Thread { boolean keepRunning = true ; public static void main ( String [ ] args ) throws InterruptedException { NoVisibility_Demonstration t = new NoVisibility_Demonstration ( ) ; t.start ( ) ; Thread.sleep ( 1000 ) ; t.keepRunning = false ; System.out.println ( `` keepRu...
Relationship between Threads and println ( ) statements
Java
I looking for a way to split my chunk of string every 10 words.I am working with the below code.My input will be a long string.Ex : this is an example file that can be used as a reference for this program , i want this line to be split ( newline ) by every 10 words each.Any help is appreciated .
private void jButton27ActionPerformed ( java.awt.event.ActionEvent evt ) { String [ ] names = jTextArea13.getText ( ) .split ( `` \\n '' ) ; var S = names.Split ( ) .ToList ( ) ; for ( int k = 0 ; k < S.Count ; k++ ) { nam.add ( S [ k ] ) ; if ( ( k % 10 ) ==0 ) { nam.add ( `` \r\n '' ) ; } } jTextArea14.setText ( nam ...
How to split a string after every 10 words ?
Java
I 'm trying to make a call to Java Webstart that uses the `` -open '' run time option to send arguments to the webstart application . I have referenced the question : Passing command line arguments to javaws ( Java WebStart ) executable , but this syntax does n't seem to work for multiple arguments . It seems to work f...
InvalidArgumentException [ Invalid arguments supplied : { hello , jnlp , launch.jnlp , 123 } ] private static void launchApp ( String appName , String appPath , String ... args ) { logger.debug ( `` Launching application : `` + appName ) ; Properties props = System.getProperties ( ) ; ArrayList < String > fullCmdString...
Java Webstart `` javaws -open '' flag does n't work with multiple arguments
Java
When I add an event listener using a lambda that calls an overridable method in the constructor , I get a warning . If I use a method reference , I do n't get any warnings about overridable methods or leaking this . Should I avoid method references in the constructor or is it safe ? Here 's a simple example :
public class SomeClass { public SomeClass ( SomeObj obj ) { obj.addListener ( this : :handleEvent ) ; // no warnings , is it really safe ? obj.addListener ( ( event ) - > handleEvent ( event ) ) ; // warning about overridable method in constructor } private void handleEvent ( Event event ) { event.doSomething ( someMet...
Is using a reference to an overridable method in the constructor safe ?
Java
I 've been reading the OS X Java Developer Tools , in order to help make my application more `` native '' with the operating system . I found something interesting in this particular section . ( emphasis mine ) To load a resolution-independent tiff , icns , or pdf file from the Resources folder of your application bund...
Supported read formats : [ jpg , bmp , gif , png , wbmp , jpeg ] Supported write formats : [ jpg , bmp , gif , png , wbmp , jpeg ] 'JPEG ' reader : com.sun.imageio.plugins.jpeg.JPEGImageReader @ 5e9f23b4'JPEG ' reader : com.sun.imageio.plugins.jpeg.JPEGImageWriter @ 378fd1ac static Image n ; public static void main ( S...
How does Java load native NSImages ?
Java
With Java 8 Streams , is it possible to encapsulate and reuse intermediate stream operations in some way that wo n't break the stream pipeline ? Consider this example from the Java Tutorial on streams : Suppose I need to use the filter and mapToInt operations in different places throughout my code . I might want try an...
double average = roster .stream ( ) .filter ( p - > p.getGender ( ) == Person.Sex.MALE ) .mapToInt ( Person : :getAge ) .average ( ) .getAsDouble ( ) ; IntStream maleAges ( Stream < Person > stream ) { return stream .filter ( p - > p.getGender ( ) == Person.Sex.MALE ) .mapToInt ( Person : :getAge ) } double averageBob ...
Can intermediate stream operations be encapsulated without breaking the pipeline ?
Java
I 'm confused by the DateTimeFormatter 's withZone method 's behavior when it comes to parsing . According to it 's documentation : When parsing , there are two distinct cases to consider . If a zone has been parsed directly from the text , perhaps because DateTimeFormatterBuilder.appendZoneId ( ) was used , then this ...
@ Testpublic void testNoZoneInInput ( ) { final ZonedDateTime expected = ZonedDateTime.of ( 2017 , 2 , 2 , 9 , 0 , 0 , 0 , ZoneId.of ( `` UTC '' ) ) ; final ZonedDateTime actual = ZonedDateTime.parse ( `` 2017-02-02T10:00:00 '' , DateTimeFormatter.ISO_DATE_TIME.withZone ( ZoneId.of ( `` UTC+1 '' ) ) ) ; Assert.assertTr...
How does DateTimeFormatter 's override zone work when parsing ?
Java
I have the code above , but I ca n't work out why it produces rather thanMany thanks
String s = `` hi hello '' ; s = s.replaceAll ( `` \\s* '' , `` `` ) ; System.out.println ( s ) ; h i h e l l o hi hello
String.replaceAll Strange Behaviour
Java
Assume the following existing classes : now , we need to create a variant of each Axx class that overrides `` foo '' method . The basic idea was : But it seems is not posible to extend a class from one of their parametized types.The objective is to skip the need of following new code : and allow statements like : Any h...
class A { public void foo ( ) { ... } ; ... } class A1 extends A { ... } ; class A2 extends A { ... } ; ... class A1000 extends A { ... } ; class B < T extends A > extends T { @ Override public void foo ( ) { ... } ; } class B1 extends A1 { @ Override public void foo ( ) { ... } ; } ; class B2 extends A2 { @ Override p...
Java Generic class extends parametrized type
Java
If I writeAbove code works normally , but if I writeThe compiler/gradle in Android studio does n't let this one through even though it 's the same , and it says that the code after return in example 2 is unreachable.I do n't have any issues regarding this but I am eager to know why ?
private void check ( ) { if ( true ) return ; String a = `` test '' ; } private void check ( ) { return ; String a = `` test '' ; }
Why does compiler build return unreachable code in some cases
Java
I have a question about this method from java.util.Collections : I understand how < ? super T > works , however , I do n't understand why the first parameter is List < ? super T > instead of List < T > . I think it 's useless in this situation.Using List < T > should work as well , should n't it ? Could you give me som...
public class Collections { public static < T > void copy ( List < ? super T > dest , List < ? extends T > src ) { for ( int i=0 ; i < src.size ( ) ; i++ ) dest.set ( i , src.get ( i ) ) ; } }
Generics Collections PECS
Java
I have a question related to the following code snippet : The first call to wide_vararg fails to compile ( saying that the method is ambigous ) while the second compiles just fine . Any explanations about this behaviour ? Thanks !
class VarArgsTricky { static void wide_vararg ( long ... x ) { System.out.println ( `` long ... '' ) ; } static void wide_vararg ( Integer ... x ) { System.out.println ( `` Integer ... '' ) ; } public static void main ( String [ ] args ) { int i = 5 ; wide_vararg ( i , i , i ) ; // needs to widen and use var-args Long ...
Java issue with var-args and boxing
Java
There are a few *.java files in the source tree of Scala in the scala.runtime directory.Those files seem to be very simple , e. g. DoubleRef.java looks like this : Is there any reason why those classes ca n't be defined in Scala ?
package scala.runtime ; public class DoubleRef implements java.io.Serializable { private static final long serialVersionUID = 8304402127373655534L ; public double elem ; public DoubleRef ( double elem ) { this.elem = elem ; } public String toString ( ) { return java.lang.Double.toString ( elem ) ; } }
What 's the purpose of these Java files in scala.runtime ?
Java
When would you ever need to use the non short circuit logical operator or ? In other words ... When would you use Instead ofIf the first conditional is true ... Then the entire statement is already true.Update : and the same question for & and & &
if ( x == 1 | x==2 ) if ( x == 1 || x==2 )
Logical operator OR without short circuit
Java
Using java.util.regex to extract substrings I find myself implementing the same code pattern working around calls to : Is there a functional extension or popular library ( guava / apache commons ) that avoids the ugly unnecessary and error-prone local variable , like : and also a stream of match results like : It seems...
Pattern p = Pattern.compile ( pattern ) ; // can be static finalMatcher m = p.matcher ( input ) ; if ( m.find ( ) ) { // or m.matches ( ) foo ( m.group ( x ) ) ; } else { ... } Pattern p = Pattern.compile ( pattern ) ; // can be static finalp.matchedGroup ( input , x ) // return Optional < String > .map ( group - > foo...
Functional style java.util.regex match/group extraction
Java
At my work we recently finished the system architecture for a control application which has a maximum latency of roughly one to two seconds . It is distributed on small ARM on-chip boxes communicating via an IP LAN . We initially foresee that we would use C or C++ , since it is a classical control system language . Aft...
C+++ RAII - Easy resource management - it will be a complex system+ System language - speed if we cant't find a JIT VM for our ARM+ No GC - no big worst case latencies from the GC+ Easy to integrate with some shared mem libs that we have to interface with- Fewer free as in beer libs - Lacks introspection - Mapping clas...
~1s latency control app : is this suitable for Java ?
Java
I am wondering why the Java compiler would add a bridge method for the foo method here : The foo method is compiled to be public in the SuperClass type . Nevertheless , the SubClass method redefines the method as a bridge to the very same method . I wonder why this bridge is necessary .
public class Outer { class SuperClass { public void foo ( ) { } } public class SubClass extends SuperClass { } }
Why does the Java compiler add visibility bridge methods for public methods defined in package-private super types ?
Java
The code at the bottom of this question is a bit long but basically creates a few objects and determines their size in memory . I execute the code with the following JVM parameters ( TLAB to avoid chunk memory allocation and supposedly get accurate memory usage figures ) : I run the code on a 64 bit Hotspot JVM and get...
-server -Xms2000m -Xmx2000m -verbose : gc -XX : -UseTLAB public class TestMemoryReference { private static final int SIZE = 100_000 ; private static Runnable r ; private static Object o = new Object ( ) ; private static Object o1 = new Object ( ) ; private static Object o2 = new Object ( ) ; private static Object o3 = ...
Accurate measurement of object sizes
Java
While learning java9 StringConcatFactory class I am unable to understand why following code with MethodHandles.publicLookup ( ) throws StringConcatException exception while if MethodHandles.lookup ( ) is used everything is working fine.As per java docs of lookup : `` lookup - Represents a lookup context with the access...
StringConcatFactory.makeConcat ( MethodHandles.publicLookup ( ) , '' abc '' , MethodType.methodType ( String.class ) ) ; //Exception HereStringConcatFactory.makeConcat ( MethodHandles.lookup ( ) , `` abc '' , MethodType.methodType ( String.class ) ) ; //Working fine
Exception in StringConcatFactory - Java 9
Java
The following code is working fine for m2 ( ) but is throwing a ClassCastException when I use m1 ( ) .The only difference between m1 and m2 is the number of arguments . My question is - Does varargs not work with a single argument when we use generics ? PS : This is not related to ClassCastException using Generics and ...
public class Test { public static void m1 ( ) { m3 ( m4 ( `` 1 '' ) ) ; } public static void m2 ( ) { m3 ( m4 ( `` 1 '' ) , m4 ( `` 2 '' ) ) ; } public static void m3 ( Object ... str ) { for ( Object o : str ) { System.out.println ( o ) ; } } public static < T > T m4 ( Object s ) { return ( T ) s ; } public static voi...
ClassCastException in varargs while using Java-8
Java
Let 's say n = 4 . With recursion I want to return : Basically I want to take number n and with by combining numbers 1,2,3 and 4 create all possible variations when the number of sum == n.This was my first idea , but it gives me Exception in thread `` main '' java.lang.StackOverflowError
1 1 1 11 1 21 32 1 12 23 14 public static void test_2 ( String path , int sum , int n ) { if ( sum == n ) { System.out.println ( path ) ; } else { test_2 ( path+ '' 1 `` , sum + 1 , n ) ; test_2 ( path+ '' 2 `` , sum + 2 , n ) ; test_2 ( path+ '' 3 `` , sum + 1 , n ) ; test_2 ( path+ '' 4 `` , sum + 2 , n ) ; } }
Sum of numbers using recursion java