lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
Case 1Prints 1 . Why ? Case 2Prints 0 . Why ? Honestly , i am at a loss here
String a = `` `` ; String [ ] b = a.split ( `` , '' ) ; System.out.println ( b.length ) ; String a = `` , , , , , , , , , , , , '' ; String [ ] b = a.split ( `` , '' ) ; System.out.println ( b.length ) ;
String , split . need help understanding
Java
I came across the following scenario when studying the book `` Functional Programming in Scala '' by Paul Chiusano and Runar Bjanarson ( Ch . 7 - Purely functional parallelism ) .You can find the original code on Github here . See here for the java.util.concurrent documentation.I am concerned with the implementation of...
package fpinscala.parallelism import java.util.concurrent._ import language.implicitConversions object Par { type Par [ A ] = ExecutorService = > Future [ A ] def run [ A ] ( s : ExecutorService ) ( a : Par [ A ] ) : Future [ A ] = a ( s ) def unit [ A ] ( a : A ) : Par [ A ] = ( es : ExecutorService ) = > UnitFuture (...
Deadlocks with java.util.concurrent._ in Scala in REPL
Java
Many examples on the web about Quicksort ( in Java ) are close to this : The thing I 'm puzzled about is why there are those equals checks:1 ) while ( i < = j ) instead of while ( i < j ) 2 ) if ( i < = j ) instead of if ( i < j ) Are there any edge cases where this equals is crucial ? From my understanding if we would...
private void quicksort ( int low , int high ) { int i = low , j = high ; int pivot = numbers [ low + ( high-low ) /2 ] ; while ( i < = j ) { while ( numbers [ i ] < pivot ) { i++ ; } while ( numbers [ j ] > pivot ) { j -- ; } if ( i < = j ) { exchange ( i , j ) ; i++ ; j -- ; } } if ( low < j ) quicksort ( low , j ) ; ...
Quicksort - reason for equals checks
Java
Why does this codeyield this output [ 0 , 1 , 10 , 1 , 100 , 8 , 1 ] ? Why is there an 8 in the output ? Do underscores add some secret functionality ?
int [ ] a = { 0 , 1 , 1_0 , 0_1 , 1_0_0 , 0_1_0 , 0_0_1 } ; System.out.println ( Arrays.toString ( a ) ) ;
Do underscores alter the behaviour of Integers ?
Java
I have a java.nio.Path which points to an absolute path : I have a second java.nio.Path which points to the root directory of the project , also an absolute path : Is it now possible to create a java.nio.Path which holds the relative path between the two :
/home/user/project/resources/configuration.xml /home/user/project resources/configuration.xml
Java - create relative java.nio.Path from two java.nio.Path 's
Java
I need to implement an enum to enum converter in java : Enum_2 > Enum_1 and I 'd like to do it in generic way.So I defined an interface : and Enum_1 : and Enum_2 which implements LabelAware and needs to be converted to Enum_1 : Finally , here 's a generic converter ( List.ofAll ( ) comes from javaslang ) : And a main m...
interface LabelAware < T extends Enum > { String getLabel ( ) ; T getObject ( ) ; } enum Enum_1 { A , B ; String getValue ( ) { return `` whatever '' ; } } enum Enum_2 implements LabelAware < Enum_1 > { C ( `` c '' , Enum_1.A ) , D ( `` d '' , Enum_1.B ) ; private final String label ; private final Enum_1 object ; Enum...
Why this converter needs casting ?
Java
This is kind of strange , but code speaks more then words , so look at the test to see what I 'm doing . In my current setup ( Java 7 update 21 on Windows 64 bit ) this test fails with ArrayIndexOutOfBoundsException , but replacing the test method code with the commented code , it the works . And I wonder if there is a...
public class TestAIOOB { private String [ ] array = new String [ 0 ] ; private int grow ( final String txt ) { final int index = array.length ; array = Arrays.copyOf ( array , index + 1 ) ; array [ index ] = txt ; return index ; } @ Test public void testGrow ( ) { //final int index = grow ( `` test '' ) ; //System.out....
JVM bug ? Cached Object field value cause ArrayIndexOutOfBoundsException
Java
Coming from a Java background , I understand that this does not compile.The last line produces a compiler error ( EDIT : at least on jdk1.6.0_65 ) it does : Bound mismatch : The generic method returnSub ( T , U ) of type Test is not applicable for the arguments ( Test.SubClass , Test.SuperClass ) . The inferred type Te...
public static class SuperClass { } public static class SubClass extends SuperClass { } public static < T , U extends T > U returnSub ( T sup , U sub ) { return sub ; } public static void main ( String [ ] args ) { SuperClass parent = new SuperClass ( ) ; SubClass child = new SubClass ( ) ; returnSub ( parent , child ) ...
Java/Scala Bounded Generics and type inference mismatch
Java
Can someone tell my why this gives a compile error ? I do n't see why the cast to A in the second for-loop causes strings ( ) to return a general List of Objects.Is this a Generics quirk ? Thanks , Kristian
import java.util.ArrayList ; import java.util.List ; public class E { public static void main ( String [ ] args ) { for ( String s : new D ( ) .strings ( ) ) { System.out.println ( `` s = `` + s ) ; } for ( String s : ( ( A ) new D ( ) ) .strings ( ) ) { System.out.println ( `` s = `` + s ) ; } } static class D extends...
Strange behaviour with parameterized method on abstract class
Java
In python I have the following : this is a structure to represent a graph and that I find nice because its structure is the same as the one of one of it 's nodes so I can use it directly to initiate a search ( as in depth-first ) . The printed version of it is : And it can be used like : Now , I 'm curious to know how ...
graph = { } graph [ 1 ] = { } graph [ 2 ] = { } graph [ 3 ] = { } graph [ 1 ] [ 3 ] = graph [ 3 ] graph [ 2 ] [ 1 ] = graph [ 1 ] graph [ 2 ] [ 3 ] = graph [ 3 ] graph [ 3 ] [ 2 ] = graph [ 2 ] { 1 : { 3 : { 2 : { 1 : { ... } , 3 : { ... } } } } , 2 : { 1 : { 3 : { 2 : { ... } } } , 3 : { 2 : { ... } } } , 3 : { 2 : { ...
Creating in c # , c++ and java a strong typed version of a python weak typed structure
Java
I got to deal here with a problem , caused by a dirty design . I get a list of string and want to parse attributes out of it . Unfortunately , I ca n't change the source , where these String were created.Example : Now I want to extract the attributes type , languageCode , url , ref , info and deactivated.The problem he...
String s = `` type=INFO , languageCode=EN-GB , url=http : //www.stackoverflow.com , ref=1 , info=Text , that may contain all kind of chars. , deactivated=false ''
Extract attributes of an string
Java
I read several posts about concurrency problems but I 'm still unsure about something . Can I say that when using synchronized , I get volatile functionality for free , because when the lock on an object will be released , the next thread always reads the modified object . With volatile , the value of an object is imme...
package main ; public class Counter { public static long count = 0 ; } public class UseCounter implements Runnable { public void increment ( ) { synchronized ( this ) { Counter.count++ ; System.out.print ( Counter.count + `` `` ) ; } } @ Override public void run ( ) { increment ( ) ; increment ( ) ; increment ( ) ; } }...
Java When using synchronized do I get volatile functionality for free ?
Java
I have some code that splits a String of letters , make a List with that and later , populate a LinkedHashMap of Character and Integer with the letter and its frequency . The code is as following , How can I write it concisely with Java 8 ? Thanks .
List < String > values = Arrays.asList ( ( subjects.split ( `` , '' ) ) ) ; for ( String value : values ) { char v = value.charAt ( 0 ) ; map.put ( v , map.containsKey ( v ) ? map.get ( v ) + 1 : 1 ) ; } map.put ( ' X ' , 0 ) ;
Is there a better way to write using the Java 8 to populate the LinkedHashMap ?
Java
i am currently having a problem with the codestylesettings i.e . the `` Reformat Code '' function in IntelliJ.NECESARRY INFORMATION : I am writing groovy scripts , which use some Java functionality ( for example generics ) It appears that my version of groovy ( which can not be changed for various reasons ) runs into c...
final List < Map < String , Object > > listOfMaps = a [ `` b '' ] as List < Map < String , Object > > final List < Map < String , Object > > listOfMaps = a [ `` b '' ] as List < Map < String , Object > > < JavaCodeStyleSettings > < option name= '' SPACES_WITHIN_ANGLE_BRACKETS '' value= '' true '' / > < codeStyleSetting...
groovy intelliJ `` angle brackets ( < > ) '' modify codestylesettings
Java
I have a class with a method which I want to be accessible only for its child objects , and not for other classes in this package . Is there a workaround to have this kind of modifier ? Maybe there is a way to make a package final , so other programmers can not add any classes into my package ? Or is there a way to get...
Modifier | Class | Package | Subclass | World————————————+———————+—————————+——————————+———————public | ✔ | ✔ | ✔ | ✔————————————+———————+—————————+——————————+———————protected | ✔ | ✔ | ✔ | ✘————————————+———————+—————————+——————————+———————no modifier | ✔ | ✔ | ✘ | ✘————————————+———————+—————————+——————————+———————priva...
Java between private and protected
Java
I have this class , which is a simplification of some code I found in a project that is being ported from Java 6 to Java 8 : It 's a very small example to merely showcase the problem , the actual code makes a bit more sense . The issue seems to be quite general though , hence the abstract example . The core issue is th...
public class Unification { final class Box < A > { } final class MyMap < A , B extends Box < ? extends A > > { } MyMap < ? , ? > getMap ( ) { return new MyMap < Object , Box < Object > > ( ) ; } < A , B extends Box < ? extends A > > void setMap ( final MyMap < A , B > m ) { } void compileError ( ) { setMap ( getMap ( )...
Java type error when compiling code with javac 8 which worked fine with javac 6
Java
I have following code : Why does it print me Java Stream ?
Stream.of ( `` Java '' , `` Stream '' , `` Test '' ) .peek ( s - > System.out.print ( s + `` `` ) ) .allMatch ( s - > s.startsWith ( `` J '' ) ) ;
Java stream unexpected result
Java
*disclaimer , when I say `` I have verified this is the correct result '' , please interpret this as I have checked my solution against the answer according to WolframAlpha , which I consider to be pretty darn accurate . *goal , to find the sum of all the prime numbers less than or equal to 2,000,000 ( two million ) *i...
long n = 3 ; long i = 2 ; long prime = 0 ; long sum = 0 ; while ( n < = 1999999 ) { while ( i < = Math.sqrt ( n ) ) { // since a number can only be divisible by all // numbers // less than or equal to its square roots , we only // check from i up through n 's square root ! if ( n % i ! = 0 ) { // saves computation time...
project euler # 10 , java , correct for small numbers
Java
( Disclaimer : I am new to Java and also , I have read the related SO question . ) I have the following code : But the PDFont class is not recognized in Eclipse.When I add the following : The PDFont class is picked up.Given that the PDFont class is located under the hierarchy specified in the first import statement end...
import org.apache.pdfbox.pdmodel . * ; ... PDFont font = PDType1Font.HELVETICA_BOLD ; import org.apache.pdfbox.pdmodel.font.PDFont ;
Java import statement with * not picking up class
Java
I 'd been trying to figure out all about Java optimizations and found something interesting.First case : primitive type compile-time optimizationAfter compilation ( I 'm using jd-gui-0.3.5.windows to decompile binary files ) it is looks like : As expected , is n't it ? i was replaced with it 's value ( inlining optimiz...
public class Clazz { public static void main ( String args [ ] ) { final int i = 300 ; new Clazz ( ) { void foo ( ) { System.out.println ( i ) ; } } .foo ( ) ; } } public class Clazz { public static void main ( String [ ] args ) { int i = 300 ; new Clazz ( ) { void foo ( ) { System.out.println ( 300 ) ; } } .foo ( ) ; ...
How does optimization of final references work in java ?
Java
I 'm trying to use a do while loop to find out whether the user wants to check a dog or a cat into a kennel system in Java . The idea is that they enter either `` dog '' or `` cat '' when prompted , and any of entry will result in an error and they will be prompted again to enter the file name.If `` cat '' or `` dog ''...
private String filename ; // holds the name of the fileprivate Kennel kennel ; // holds the kennelprivate Scanner scan ; // so we can read from keyboardprivate String tempFileName ; private String dogsFile = `` dogs.txt '' ; private String catsFile = `` cats.txt '' ; private KennelDemo ( ) { scan = new Scanner ( System...
Do while loop meeting one of 2 conditions
Java
Let M ( n , k ) be the sum of all possible multiplications of k distinct factors with largest possible factor n , where order is irrelevant.For example , M ( 5,3 ) = 225 , because:1*2*3 = 61*2*4 = 81*2*5 = 101*3*4 = 121*3*5 = 151*4*5 = 202*3*4 = 242*3*5 = 302*4*5 = 403*4*5 = 606+8+10+12+15+20+24+30+40+60 = 225.One can ...
public static long M ( long n , long j , long k ) { if ( k==1 ) return usefulFunctions.sum ( j , n ) ; for ( long i=j ; i < =n-k+1+1 ; i++ ) return i*M ( n , i+1 , k-1 ) ; } public static long sum ( long i , long n ) { final long s1 = n * ( n + 1 ) / 2 ; final long s2 = i * ( i - 1 ) / 2 ; return s1 - s2 ; } -- -- -- -...
Possible multiplications of k distinct factors with largest possible factor n
Java
I 'm trying to perform some retrieval queries on a `` correct '' pom.xml used by maven . For that I use basic XPath queries from JDOM.Unfortunately the queries do not return any results ( and neither do simple descendant filters ) . I 'm reasonably sure that the problem lies within the root declaration of the pom.xml :...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/maven-v4_0_0.xsd '' > < ! -- content -- > < /project > XPa...
Document declares separate empty namespace rendering NamespaceAware results useless
Java
It seems , that JShell object created inside another JShell does not have access to parent 's JShell scope . For instance : Is it somehow possible to make parent scope visible to the child one ?
jshell > int x = 1 ; x == > 1jshell > xx == > 1jshell > jdk.jshell.JShell js = jdk.jshell.JShell.create ( ) ; js == > jdk.jshell.JShell @ 1a052a00jshell > js.eval ( `` x '' ) ; $ 4 == > [ SnippetEvent ( snippet=Snippet : ErroneousKey # 1-x , previousStatus=NONEXISTENT , status=REJECTED , isSignatureChange=false , cause...
Access to `` parent scope '' in JShell
Java
What I want as an end result is thisto appear ( when run ) as not to appear as Is there any way to do this ? I tried using windows character map , copied the symbol here , and in my code , but after changing encoding to UTF-8 and inserting it , it comes up as ? when run ... What can be done ? Thanks in advance for answ...
System.out.println ( `` This is the not equal to sign\n≠ '' ) ; This is the not equal to sign≠ This is the not equal to sign ?
how to insert the ≠ sign into a string
Java
Suppose we have a program like this : We know that the weak reference to the BigThing object can not prevent the object from being garbage collected when it becomes no longer strongly reachable.My question is about the local variable bt which is a strong reference to the BigThing object . Does the object become not-str...
void main ( ) { // Point 0 BigThing bt = new BigThing ( ) ; // Point 1 WeakReference < BigThing > weak = new WeakReference < > ( bt ) ; // Point 2 doSomething ( weak ) ; // Point 3 } void doSomething ( ... ) { ... }
Can Java garbage collect variables before end of scope ?
Java
I am trying to find out if a GIT branch can have a subset of the project data like the example below.I am working on a java , spring , maven project and my source is atand my JSP pages are at : we are thinking of outsource the JSP pages to a diff group but we do n't want them changing the java code so we are trying to ...
src/main/java src/main/webapp src/main/webapp
Can a GIT branch have a subset of data ?
Java
I 'm trying to play with reflection to see if I can get to a point where I 'm able to type in a class name and my application will load that class and create an instance of it . After a few attempts I found I could n't just stick a class name in Class.forName ( ) without its package name , so I wound up trying to get a...
BufferedReader console = new BufferedReader ( new InputStreamReader ( System.in ) ) ; String s = `` '' ; do { ClassLoader clsldr = ClassLoader.getSystemClassLoader ( ) ; Package [ ] pkgs = Package.getPackages ( ) ; s = console.readLine ( ) ; if ( s.equals ( `` : exit '' ) ) { System.exit ( 0 ) ; } boolean classFound = ...
Why is my reflection loading weird classes ?
Java
I have an object called employee which has a long list of attributes , I am retriving the values from database and need to put them into the employee object , I am doing the following but as the code is so long I am wondering if there is any shortcut to it .
Employee emp = new Employee ( ) ; try { ps = con.prepareStatement ( `` select * from Employee WHERE username = ? `` ) ; ps.setString ( 1 , username ) ; ResultSet r = ps.executeQuery ( ) ; if ( r.next ( ) ) { // 12 lines to put values into employee object need to be shorter emp.setID ( r.getInt ( 1 ) ) ; emp.setTitle ( ...
How to add results to an object with long list of fields ?
Java
Let 's say I have an unsorted list of four objects : [ B , C , A , D ] .All four objects are of the same type , and : By ! = I mean that they are neither less-than , equal-to , or greater-than the other objects.I need to `` sort '' the list such that A will always come before B , and C will always come before D. Beyond...
( A > B ) , ( C > D ) , ( A ! = C or D ) ( B ! = C or D ) ( C ! = A or B ) ( D ! = A or B ) .
Algorithm for sorting loosely comparable data ?
Java
I have the following code : How can I set restrictions ? I.e . the T to be String or int or double for example . Is this possible ? P.S.I do n't want to use Because I do n't want to have only Strings..
protected < T > T getValueForKey ( String key ) { T value = null ; // currentStats is just a Bundle if ( currentStats.containsKey ( key ) ) { return value ; } return value ; } protected < T extends String > T getValueForKey ( String key ) { }
How can I restrict Java Generics
Java
We already know about this suggestion/practice to use char [ ] instead of String for sensitive data . There is multiple reasons for it . One is to clean up the sensitive data right after they are not needed anymore : Now the question : does it ( i.e . using char [ ] ) make sense ( specifically the point mentioned above...
char [ ] passwd = passwordProvider.getKeyStorePassword ( ) ; KeyStore keystore = KeyStore.getInstance ( `` JKS '' ) ; // TODO : Create the input stream ; keystore.load ( inputstream , passwd ) ; System.arraycopy ( new char [ passwd.length ] , 0 , passwd , 0 , passwd.length ) ; // Please continue ... char [ ] passwd = p...
Java sensitive data : char [ ] vs String ? What is the point ?
Java
I had a look at the source code of the String.hashcode ( ) method . This was the implementation in 6-b14 , which has been changed already.My question is about this line : int len = count ; Where count is a global variable representing the amount of characters of the String.Why is a local variable len used here for the ...
public int hashCode ( ) { int h = hash ; if ( h == 0 ) { int off = offset ; char val [ ] = value ; int len = count ; for ( int i = 0 ; i < len ; i++ ) { h = 31*h + val [ off++ ] ; } hash = h ; } return h ; }
What is the purpose of using a local variable to hold a global one ?
Java
I have an adapter class with a checkbox and when the checkbox is selected it pushes a JSONObject key and value to Parse . Inside my app it only saves one key and value to Parse as a JSONObject and I want my app to save several key and values into Parse when selecting other Checkboxes.When I select a different Checkbox ...
{ `` 2c1 '' : true , `` 2c2 '' : true , `` 2c3 '' : true , `` 2c4 '' : true , `` 2c5 '' : true , `` 2c6 '' : true } { `` 2c1 '' : true } final JSONObject myObject = new JSONObject ( ) ; try { myObject.put ( dataRecord.getID ( ) , true ) ; } catch ( JSONException e ) { e.printStackTrace ( ) ; } checkBox.setOnClickListen...
Several JSONObject keys and values wo n't save to Parse
Java
If I evaluate the following expression in Scala REPL : the returned type is : java.lang.String.If I evaluate this similar expression : the returned type is : String.Why the difference ?
scala > `` 1 '' + 1res0 : java.lang.String = 11 scala > 1 + `` 1 '' res1 : String = 11
Scala returns different types for very similar expressions
Java
In my current Java/Spring project , I am in the phase of integration with PayPal . After configure a Java class to handle the payment process , following the instructions from here , I run my application and try to checkout an order with paypal.I am redirected correctly to the PayPal login page , and after the login , ...
Paypal prop = this.paypalDao.get ( ) ; String clientId = prop.getClientID ( ) ; String clientSecret = prop.getClientSecret ( ) ; APIContext apiContext = new APIContext ( clientId , clientSecret , `` sandbox '' ) ; if ( payerId ! = null ) { if ( guid ! = null ) { Payment payment = new Payment ( ) ; payment.setId ( map.g...
PayPal SDK going from payment review page to profilepage
Java
I have a problem where I want to convert a list of POJOs into DTOs and pass them into a wrapper object which is then returned . Consider this working piece of code : I am looking for a way to rewrite this into smaller , maybe more elegant , piece of code using Java lambda expressions . This is what I have done so far ....
List < Device > devices = dbService.getDevices ( ... ) ; List < DeviceDTO > devicesDTO = new ArrayList < DeviceDTO > ( ) ; for ( Device d : devices ) { devicesDTO.add ( convertToDTO ( d ) ) ; } WrapperDTO wrapper = new WrapperDTO ( devicesDTO ) ; List < Device > devices = dbService.getDevices ( ... ) ; List < DeviceDTO...
How to pass a List to a constructor of a new object using java lambda expression ?
Java
I have this working hierarchy already and the program runs as expected . Basically I have abstracted everything in a Base class and all other subclass adding their own methods.everything looks good until later ( errr ... new requirements ) I realize I need to have a new class ( lets call this class C ) that extends bot...
abstract Class Base { } class A extends Base { //new methods } class B extends Base { //new methods } class C extends A , B { //new methods }
Applicable Design pattern
Java
This is what I tried : I compiled the program at first and ran it two consecutive times , I got two different outputs : output 1 : output 2 : I want to know why did the JVM swap the second object 's location to first object 's location When it ran for the second time.. , it is quite bewildering.. ,
public final class firstObj { public static void main ( String args [ ] ) { Object obj = new Object ( ) ; Object obj1 = new Object ( ) ; System.out.println ( obj ) ; System.out.println ( obj1 ) ; } } java.lang.Object @ 6f548414java.lang.Object @ 65ab7626 java.lang.Object @ 659c2931java.lang.Object @ 6f548414
why is object location swapped in JVM ?
Java
I developed some code in Eclipse , tested it successfully , pushed it to our Jenkins CI server , and got an email that Maven was choking with a Java compile error . I subsequently isolated the problem and created the following minimal example showing the issue : In Eclipse , this code compiles without error and appears...
import java.util.List ; import java.util.function.Function ; class MinimalTypeFailureExample { public static void main ( String [ ] args ) { List < String > originalList = null ; // irrelevant List < IntToByteFunction > resultList = transform ( originalList , outer - > inner - > doStuff ( inner , outer ) ) ; System.out...
Code compiles in Eclipse but not javac : curried lambdas with functional subinterface . Which is correct ?
Java
This is just out of curiosity . If I store two recursive numbers or irrational numbers in two doubles and then perform some operations , how does it produce actual result ? For example , Another one : How these accurate results are generated ?
double d1=7d/3 ; double d2=5d/3 ; double sum=d1+d2 ; System.out.println ( new BigDecimal ( sum ) ) ; //prints exactly 4 double d1=log10 ( 3 ) ; double value=Math.pow ( 10 , d1 ) ; System.out.println ( new BigDecimal ( value ) ) ; //prints exactly 3
How two recursive numbers stored as doubles sum up to an integer
Java
I 'm trying to parse the following string to a Date object : Using this SimpleDateFormat : But I 'm getting a : What am I doing wrong , How I should handle the T and the Z letters in the date ?
2013-12-26T01:00:56.664Z SimpleDateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-dd'T'HH : mm : ss ' Z ' '' ) ; java.text.ParseException : Unparseable date : `` 2013-12-26T01:00:56.664Z '' ( at offset 19 )
Issue with parsing Date string
Java
Let 's say we have a class and an overloaded function : and I want to call g with a method reference to a function of type A - > int : This works with javac , but not with eclipse ecj . I submitted a bug report to ecj , but I am not sure if this is an ecj or javac bug and tried to follow the overload resolution algorit...
public class Main { static final class A { } public static String g ( ToIntFunction < ? extends A > f ) { return null ; } public static String g ( ToDoubleFunction < ? extends A > f ) { return null ; } } public class Main { static final class A { } public static String g ( ToIntFunction < ? extends A > f ) { return nul...
Overload resolution with method references and function interface specializations for primitive types
Java
Is the following lambda possible somehow in Java ? I 'd like to count elements from my filtered stream but collaterally store the first 10EDIT : It was too implicit from my side , but the idea is meant of course as a potential solution which would be the fastest ( faster than calling twice the stream generator and do b...
stream ( ) .filter ( myFilter ) //Reduces input to forthcoming operations .limit ( 10 ) //Limits to ten the amount of elements to finish stream .peek ( myList : :add ) //Stores the ten elements into a list .count ( ) ; //Here is the difficult one . Id like to count everything the total of elements that pass the filter ...
Count elements from Stream but consider only N for collecting
Java
I have the below codeThe double Value which I set is not returned as output . Double Value using Big Decimal 78871234510124576 Double Value using String format 78871234510124576Is there a standard way to convert a Double to a String without explicit type casting with the range of value being long data type ( max value ...
double cellValue = 78871234510124568.0 ; String cell = new BigDecimal ( cellValue ) .toPlainString ( ) ; String b = String.format ( `` % .0f '' , cellValue ) ; System.out.println ( `` Double Value using Big Decimal `` + cell ) ; System.out.println ( `` Double Value using String format `` + b ) ;
Double to String using Java standards
Java
I 'm trying to solve this exercise and here 's my solution . It basically holds a tree map to map the nodes at the same veritical offset to a key . And uses a priority queue to split ties when there are multiple keys at the same ( horizontal level ) using the value at the node . } And to be clear here 's where I think ...
public List < List < Integer > > verticalTraversal ( TreeNode root ) { Map < Integer , PriorityQueue < Node > > map = new TreeMap < > ( ) ; List < List < Integer > > out = new ArrayList < > ( ) ; if ( root == null ) return out ; Queue < Node > q = new LinkedList < > ( ) ; Node r = new Node ( root , 0 , 0 ) ; q.add ( r ...
What am I doing wrong with the Java 8 PriorityQueue comparator ?
Java
So my professor mentioned that a break in an if/if-else statement is `` bad '' code.What exactly does she mean by that ? Also how am I able to fix my code that I currently have written , because it does work the way I want it to , it 's just now I need to get ride of the break statement.Essentially I want the user to e...
int sumOne = 1 ; int sumTwo = 1 ; int sumOneTotal = 0 ; int sumTwoTotal = 0 ; while ( sumOne > 0 || sumTwo > 0 ) { System.out.print ( `` Enter a number to add to first sum : `` ) ; //The user enters in a value for the first sum . sumOne = input.nextInt ( ) ; /** * We use an if-else statment to ensure sumOne is never le...
If-else should not have break ?
Java
I would like to convert an iterator of Strings to Inputstream of bytes . Usually , I can do this by appending all the strings in a StringBuilder and doing : InputStream is = new ByteArrayInputStream ( sb.toString ( ) .getBytes ( ) ) ; But I want to do it lazily because my iterable is provided by Spark and could be very...
def rowsToInputStream ( rows : Iterator [ String ] , delimiter : String ) : InputStream = { val bytes : Iterator [ Byte ] = rows.map { row = > ( row + `` \n '' ) .getBytes } .flatten new InputStream { override def read ( ) : Int = if ( bytes.hasNext ) { bytes.next & 0xff // bitwise AND - make the signed byte an unsigne...
Iterator of Strings to Inputstream of bytes
Java
In CXF 2 I could set the level like this : However , in CXF 3 cacheLevel property is missing in org.apache.cxf.transport.jms.JMSConfiguration.How can I set the cache level in CXF 3 ? Thanks in advance .
< jaxws : client name= '' client '' > < jaxws : features > < bean class= '' org.apache.cxf.transport.jms.JMSConfigFeature '' > < property name= '' jmsConfig '' ref= '' jmsConfig '' / > < /bean > < /jaxws : features > < /jaxws : client > < bean id= '' jmsConfig '' class= '' org.apache.cxf.transport.jms.JMSConfiguration ...
CXF 3 Cache Level
Java
I am trying to implement a new architectural approach for inter-layer communication by using abstract models and decorators.Conventionally , when we design the layers of a monolithic application , we would have a application ( controller ) layer , a domain ( business ) layer and an infrastructure ( persistence ) layer ...
// Abstract Foopublic abstract class AbstractFoo { protected Long id ; protected String color ; protected LocalDateTime lastModified ; protected Long getId ( ) ; protected String getColor ( ) ; protected void setId ( ) ; protected void setColor ( ) ; } // Abstract Decorator ( wraps foo ) public abstract class FooDecora...
Decorators For Inter-Layer Communication
Java
Can someone explain to me why .net is calculating these differently to JavaThe equationJava calculates it as.Net calculates as My issue is that I need .Net to calculate the same as Java as i 'm porting across a decryption function and if it calculates differently then the decryption is n't going to be right . Any help ...
( -1646490243 < < 4 ) + 3333 ^ -1646490243 + -957401312 ^ ( -1646490243 > > 5 ) + 4 1173210151 -574040108 ( -1646490243 < < 4 ) + 3333 Xor -1646490243 + -957401312 Xor ( -1646490243 > > 5 ) + 4 -3121757145 + 2 ^ 32 = 1173210151
VB .NET calculating differently to Java
Java
The following code prints true for 100 times : Granted , 100 times is not a guarantee . But does n't it seem though that even if the identity used here does not meet the requirement `` ... for all u , combiner.apply ( identity , u ) is equal to u '' per the doc , we can still say that a parallel stream derived from a l...
for ( int i=0 ; i < 100 ; i++ ) { String s2 = Arrays.asList ( `` A '' , `` E '' , `` I '' , `` O '' , `` U '' ) .parallelStream ( ) .reduce ( `` x '' , String : :concat , String : :concat ) ; System.out.println ( `` xAxExIxOxU '' .equals ( s2 ) ) ; }
Is n't it guaranteed that a parallel stream derived from a list will always behave like its sequential counterpart giving the same , predictable output ?
Java
I have difficulties in naming the two kinds of scopes that I see in Java : The case is mostly with f = 3 and g = 2 ; A while statement does n't introduce a new scope , so I ca n't create a while-local variable named f. But if I create a local variable named g then I can `` re-create '' it after the loop . Why ? I know ...
class Fun { int f = 1 ; void fun ( ) { int f = 2 ; while ( true ) { int f = 3 ; int g = 1 ; } int g = 2 ; } } # include < iostream > using namespace std ; int main ( ) { int f = 0 ; for ( int i=0 ; i < 1 ; i++ ) { int f = 1 ; cout < < f < < endl ; { int f = 2 ; cout < < f < < endl ; } } cout < < f < < endl ; }
Naming two kinds of scope in Java
Java
I am struggling a bit with class casting . Let me set the scene . I have java server code that uses a service and orchestrator layer . A request comes into the service layer in a bean format ( java class aligned with the front end view ) , and then i have a bunch of domainBeanMapper classes which take a bean format obj...
< util : map id= '' domainBeanMappers '' > < entry key= '' UserBean '' value-ref= '' userMapper '' / > < entry key= '' User '' value-ref= '' userMapper '' / > ... .. < bean id= '' userMapper '' class= '' com.me.mapping.UserMapper '' parent= '' baseDomainBeanMapper '' / > UserBean userBean = ( UserBean ) getDomainBeanMa...
Java - cast to an interface , then find out what the casted type is
Java
why does it work with streams and does not work for the simple set ?
public class Test { static List < Object > listA = new ArrayList < > ( ) ; public static void main ( final String [ ] args ) { final List < TestClass > listB = new ArrayList < > ( ) ; listB.add ( new TestClass ( ) ) ; // not working setListA ( listB ) ; // working setListA ( listB.stream ( ) .collect ( Collectors.toLis...
Java add list of specific class to list of java.lang.Object works with java 8 streams - why ?
Java
I used it works fine if in the following caseproduces : but in case of following string it only removes the square brackets within square brackets in the first runproduces :
value.replaceAll ( `` [ ^\\w ] ( ? = [ ^\\ [ ] *\\ ] ) '' , `` '' ) ; [ a+b+c1 & $ & $ / ] + ( 1+b & +c & ) [ abc1 ] + ( 1+b & +c & ) [ a+b+c1 & $ & $ / [ ] ] + ( 1+b & +c & ) [ a+b+c1 & $ & $ / ] + ( 1+b & +c & )
Regular Expression to remove everything but characters and numbers between Square brackets
Java
At vJUG24 , one of the topics was JVM performance.Slides can be found here.He had an example : which was called via ( ca n't quite read the slide properly , but it 's similar ) : He said because it was a static method , it could be optimised by inlining it like this : Why is it important that the log method is static f...
static void log ( Object ... args ) { for ( Object arg : args ) { System.out.println ( arg ) ; } } void doSomething ( ) { log ( `` foo '' , 4 , new Object ( ) ) ; } void doSomething ( ) { System.out.println ( `` foo '' ) ; System.out.println ( new Integer ( 4 ) .toString ( ) ) ; System.out.println ( new Object ( ) .toS...
Why can a method that takes varargs be optimised into a series of monomorphic calls only if it is static ?
Java
In one of my Java classes I have these 2 very similar functions . Is there a way in Java to combine them into one function so I do n't have to maintain 2 functions ?
public static boolean areValuesValid ( double [ ] values , int numElements ) { if ( values == null || values.length ! = numElements ) { return false ; } for ( int i = 0 ; i < numElements ; ++i ) { if ( Double.isNaN ( values [ i ] ) ) { return false ; } } return true ; } public static boolean areValuesValid ( float [ ] ...
How to combine similar Java functions into one ( In C++ I 'd use templates )
Java
I am wondering whether you would consider it a good practice to remove references ( setting them to null ) to objects in order to help the Java Garbage Collector.For instance , let 's say you have a class with two fields , one of them being very memory-consuming . If you know you only need it for a particular processin...
public class TestClass { public static Object heavyObject1 ; public static Object object2 ; private static void action ( ) { object2 = doSomething ( heavyObject1 ) ; heavyObject1 = null ; //is this good ? } }
Is it a good practice to remove references to help the GC ?
Java
Why java += get wrong result , and how can I prevent this problem ? ( for example any way show warning in IDE ? ) I tried eclipse & IntelliJ but both not show any warning.Sample code :
{ long a = 20000000000000000L ; double b = 90.0 ; a += b ; System.out.println ( a ) ; // 20000000000000088 NG } { long a = 10000000000000000L ; double b = 90.0 ; a += b ; System.out.println ( a ) ; // 10000000000000090 OK } { long a = 20000000000000000L ; double b = 90.0 ; a += ( long ) b ; System.out.println ( a ) ; /...
Why java += get wrong result , and how can I prevent this ?
Java
I 'm facing an issue with generic types : What 's the best solution between the 1. and the 4 . ( or any other one by the way ) ?
public static class Field < T > { private Class < ? extends T > clazz ; public Field ( Class < ? extends T > clazz ) { this.clazz = clazz ; } } public static void main ( String [ ] args ) { // 1 . ( warning ) Iterable is a raw type . References to generic type Iterable < T > should be parameterized . new Field < Iterab...
JAVA and generic types issue
Java
Do Java ( 9+ ) streams support a HAVING clause similar to SQL ? Use case : grouping and then dropping all groups with certain count . Is it possible to write the following SQL clause as Java stream ? The closest I could come up with was : but extracting the entrySet of the grouped result to collect twice feels strange ...
GROUP BY idHAVING COUNT ( * ) > 5 input.stream ( ) .collect ( groupingBy ( x - > x.id ( ) ) ) .entrySet ( ) .stream ( ) .filter ( entry - > entry.getValue ( ) .size ( ) > 5 ) .collect ( toMap ( Map.Entry : :getKey , Map.Entry : :getValue ) ) ;
Java Streams GroupingBy and filtering by count ( similar to SQL 's HAVING )
Java
Some informationI am working on a program that works with basic sets and antichains.Antichains are subsets of the powerset of a set so that no two elements ( sets ) in this subset are subset of another element ( set ) in this subset . For instance { { 1 } , { 1,2 } } is not an antichain because { 1 } ⊆ { 1,2 } .Some of...
public AntiChain join ( AntiChain ac ) { AntiChain res = new AntiChain ( this ) ; for ( int i = ac.bitset.nextSetBit ( 0 ) ; i > = 0 ; i = ac.bitset.nextSetBit ( i+1 ) ) { res.addAndMakeAntiChain ( new BasicSet ( i ) ) ; } return res ; } public AntiChain meet ( AntiChain ac ) { AntiChain res = AntiChain.emptyAntiChain ...
Represent antichains with efficient join and meet operations
Java
I am moving to use Java11 . Learning a new method Predicate.not , I found my current code to find only cat family as : output is : leopard , cat , lionNow I am trying to use the new method and the output is coming incorrect . How do I correct it ? What did I do wrong ? My later code : But this outputs all my list now ....
List < String > animals = List.of ( `` cat '' , `` leopard '' , `` dog '' , `` lion '' , `` horse '' ) ; Predicate < String > cats = a - > ! a.equals ( `` dog '' ) & & ! a.equals ( `` horse '' ) ; Set < String > filterCat = animals.stream ( ) .filter ( cats ) .collect ( Collectors.toSet ( ) ) ; System.out.println ( fil...
Predicate in Java11 filters all elements
Java
My web app seems to be running out of memory which I think is due to a thread leak . It seems that threads are being stuck at waiting and this grows larger and larger until the memory reaches the top of the heap size . The thread size increases on my local Tomcat Server of the web app while idling and not using the web...
`` Thread-124 '' - Thread t @ 378java.lang.Thread.State : TIMED_WAITINGat java.lang.Object.wait ( Native Method ) - waiting on < 44c53e01 > ( a com.mashape.unirest.http.utils.SyncIdleConnectionMonitorThread ) at com.mashape.unirest.http.utils.SyncIdleConnectionMonitorThread.run ( SyncIdleConnectionMonitorThread.java:22...
Unirest Thread Leak
Java
I have simple code : I want to know why is possible , butimpossible ! Who can explain ? Who can specify common rule for similar issues ?
class A { public static void main ( String [ ] args ) { char c = 65 ; // ok new A ( ) .m ( 65 ) ; // compile error } void m ( char c ) { } } char c = 65 ; new A ( ) .m ( 65 ) ; // compile error
Different char casting behaviour for method passing and inside method
Java
As we know , String ( ) .intern ( ) method add String value in string pool if it 's not already exist . If exists , it returns the reference of that value/object . I need to know , when i call test.intern ( ) what this intern method will do ? add `` dog '' with different reference in string pool or add test object refe...
String str = `` Cat '' ; // creates new object in string pool with same character sequence . String st1 = `` Cat '' ; // has same reference of object in pool , just created in case of 'str ' str == str1 //that 's returns trueString test = new String ( `` dog '' ) ; test.intern ( ) ; // what this line of code do behind ...
How does String.intern ( ) work and how does it affect the String pool ?
Java
I have the following saved json data in Elasticsearch : i want to delete all list of ids which its expirationDate are smaller than today using QueryBuilder in springdata Elasticsearch
{ `` id '' : '' 1234 '' , `` expirationDate '' : '' 17343234234 '' , `` paths '' : '' http : localhost:9090 '' , `` work '' : '' software dev '' , `` family '' : { `` baba '' : '' jams '' , `` mother '' : '' ela '' } } , { `` id '' : '' 00021 '' , `` expirationDate '' : '' 0123234 '' , `` paths '' : '' http : localhost...
delete all elements which is less than a value in Elasticsearch
Java
I have two generic methods , which are designed to force the caller to provide parameters that match type wise : However , when calling them , the compiler reasons differently on what is allowed to pass as parameters : How come ? Is the compiler just too clumsy to properly reason about types here , or is this a feature...
private < T > void compareValues ( Supplier < T > supplier , T value ) { System.out.println ( supplier.get ( ) == value ) ; } private < T > void setValue ( Consumer < T > consumer , T value ) { consumer.accept ( value ) ; } compareValues ( this : :getString , `` Foo '' ) ; // Valid , as expectedcompareValues ( this : :...
Type checking with generic Suppliers and lambdas
Java
Creating the apache Abdera client is failingPart of my code isThis is throwing me ... Any help ! !
Abdera abdera = new Abdera ( ) ; AbderaClient abderaClient = new AbderaClient ( abdera ) ; java.lang.RuntimeException : java.lang.NoSuchMethodException : org.apache.abdera.protocol.client.cache.LRUCacheFactory. < init > ( org.apache.abdera.Abdera ) at org.apache.abdera.util.Discover.locate ( Discover.java:37 ) at org.a...
Creation of Abdera Client fails
Java
I have an ArrayList which contains some values with duplicates and elements that occur thrice , I want to collect those values that occur thrice specifically into another ArrayList likeHere , I want to get only the Strings that occur thrice in another array list.Currently , I have a solution for dealing with duplicates...
Arraylist < String > strings ; //contains all strings that are duplicates and that occur thrice Arraylist < String > thrice ; //contains only elements that occur three times .
Get the Strings that occur exactly three times from Arraylist < String >
Java
I have below working groovy code from Spring framework project : Unmarshaller.unmarshall is actually interface method : https : //docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/oxm/Unmarshaller.htmlUnmarshaller interface is implemented by several classes.Who decides which implementing clas...
import org.springframework.oxm.Unmarshallerpublic class ItemSearchService { Unmarshaller unmarshaller ; public ItemSearchResponse getObject ( InputStream xml ) { ItemSearchResponse its = null ; try { its = ( ItemSearchResponse ) unmarshaller.unmarshal ( new StreamSource ( xml ) ) ; } finally { } return its ; } }
How does class gets injected which implements interface method being called in Java or Groovy code ?
Java
I 'm implementing the visitor pattern for a project and realized I may be able to save some typing by having the default implementation of accept be the following.However if the static type of this resolves to Visitable this implementation will not work so what is the static type of this in this situation ?
public interface Visitable { default public void accept ( Visitor v ) { v.visit ( this ) ; } }
What is the static type of ` this ` in Java 8 default interfaces ?
Java
The following code : prints : How is the lambda invocation implemented ? Why are there 2 stack frames ?
public static void main ( String [ ] args ) { Collections.singleton ( 1 ) .stream ( ) .forEach ( i - > new Exception ( ) .printStackTrace ( ) ) ; } java.lang.Exception at PrintLambdaStackTrace.lambda $ main $ 0 ( PrintLambdaStackTrace.java:6 ) at PrintLambdaStackTrace $ $ Lambda $ 1/1831932724.accept ( Unknown Source )...
Why are there 2 stack frames for a lambda invocation ?
Java
So , how to get outcome of this code using functional programming : Which throws out `` Total of reduced numbers : 47.7 '' How to get the same outcome using functional programming tools like map ( ) , reduce ( ) etc ?
public static final List < BigDecimal > numbers = Arrays.asList ( new BigDecimal ( `` 15 '' ) , new BigDecimal ( `` 10 '' ) , new BigDecimal ( `` 17 '' ) , new BigDecimal ( `` 30 '' ) , new BigDecimal ( `` 18 '' ) , new BigDecimal ( `` 23 '' ) , new BigDecimal ( `` 5 '' ) , new BigDecimal ( `` 12 '' ) ) ; BigDecimal to...
Java : How to properly manipulate BigDecimal array using functional programming ?
Java
This might seem to be a no-brainer at first glance . It probably is , but a few things have me feeling I might be missing something . First the Java documentation for Character.isWhitespace seems to exclude it . The definition for what is and what is not allowed as whitespace seems very definitive ( 'if and only if ' )...
import static java.lang.Character.isWhitespace ; public class WhitespaceCheck { public static void main ( String [ ] args ) { Character test = ' ' ; if ( Character.isWhitespace ( test ) ) { System.out.println ( `` Is whitespace ! '' ) ; } else { System.out.println ( `` Is not whitespace ! '' ) ; } } }
Does Java regard a 'normal ' space as whitespace for the purposes of Character.isWhitespace ?
Java
I have a recent interview question , reordering of elements in an array with minimum memory usage . Not to use any additional variable or collections etc.input : output :
value 65 7 1 68 90index 0 1 2 3 4 value 90 68 1 7 65index 0 1 2 3 4
With less memory usage need to reorder the array elements
Java
This is my first question . These 2 create method questions , were on a quiz I took . Create a method , to find a radius , double r. Return the array and its indices , from the 2d circles array . If you ca n't find double r , return { -1 , -1 } . **Create a method to swap the circles , using the findCircleWithRadius me...
public int [ ] void findCircleWithRadius ( Circle [ ] [ ] circles , double r ) { for ( int i = 0 ; i < circles.length-1 ; i++ ) { //search the row for ( int j = 0 ; j < circles [ 0 ] .length ; j++ ) { //search each column Circle temp = circles [ i ] [ j ] ; if ( temp == r ) r = temp ; else return `` { -1 , -1 } '' ; } ...
Find and search for a double in an array and return its indices ? Is this an array element swap method ? )
Java
I have a question regarding the JLS 3rd edition , and the inference mechanism . It is stated in the section 15.12.2.7 that : If F = U [ ] , where the type U involves Tj , then if A is an array type V [ ] , or a type variable with an upper bound that is an array type V [ ] I tried to create a type variable with an array...
public class MyClass < T extends String [ ] > { }
Java inference : type variable with an upper bound that is an array type
Java
I used to declare a final String inside a constructor . Now I want to insert an if-statement in order to declare it differently if needed.I used to do : Now I 'm tryingUnfortunately path can not be found now ( can not find symbol error ) and I 'm really lost with my research understanding this.The following works thoug...
public Config ( ) { final String path = `` < path > '' ; doSomething ( path ) ; } public Config ( String mode ) { if ( mode = `` 1 '' ) { final String path = `` < path1 > '' ; } else { final String path = `` < path2 > '' ; } doSomething ( path ) ; } public Config ( String mode ) { final String path ; if ( mode = `` 1 '...
How to declare a final String inside a constructor with an if-statement ?
Java
I have to design an interface for hierarchical entity : It 's quite easy to implement default getAncestors ( ) method in terms of getParent ( ) in such a way that the former would return Stream of all the ancestors . Implementation example : But I need to also include this into the stream , and here a problem appears ....
interface HierarchicalEntity < T extends HierarchicalEntity < T > > { T getParent ( ) ; Stream < T > getAncestors ( ) ; } default Stream < T > getAncestors ( ) { Stream.Builder < T > parentsBuilder = Stream.builder ( ) ; T parent = getParent ( ) ; while ( parent ! = null ) { parentsBuilder.add ( parent ) ; parent = par...
Designing interface for hierarchical entity
Java
I want to create a sentence from words from two different lists . Like the example above : `` list1w1 list2w1 list1w2 list2w2 list1w3 list2w3 ... '' I know how to do it with for loop , but I want to use streams . Is it even possible ? My current solution :
StringBuilder result = new StringBuilder ( ) ; for ( int i=0 ; i < doses.size ( ) ; i++ ) result.append ( String.format ( `` % s % s < br > '' , list1.get ( i ) , list2.get ( i ) ) ) ;
How to connect words from two lists in Java
Java
I would like to initialize List of my Dto the shortest way possible . Right now I 'm using : Is there any way of making it a one-liner ?
public List < SomeItemDto > itemsToDto ( List < SomeItem > items ) { List < SomeItemDto > itemsDto = new ArrayList < SomeItemDto > ( ) ; for ( SomeItem item : items ) { itemsDto.add ( itemToDto ( item ) ) ; } return itemsDto ; }
One-liner to initialize list from another list
Java
I am trying to read and understand some Java code . Here it is : What does the < ? super PopulationLoadContext > mean ?
protected LoadTarget < ? super PopulationLoadContext > createTarget ( PopulationLoadContext context ) { return createTransactionalTargetGroup ( RiskScoresTables.All_Tables ) ; }
Use of `` super '' with `` ? '' in Java
Java
I have a list of LocalDates lets say 14-06-2020 , 15-06-2020 , 17-06-2020 , 19-06-2020 , 20-06-2020 , 21-06-2020 and I want to have all consecutive intervals from above dates . So the output would be likeWhat would be the most efficient way to do in JavaSo I have create an Interval class that would hold start and endda...
Interval 1 = [ 14-06-2020 , 15-06-2020 ] Interval 2 = [ 17-06-2020 , 17-06-2020 ] Interval 3 = [ 19-06-2020 , 21-06-2020 ] public class Interval { private LocalDate startDate ; private LocalDate endDate ; } public static void main ( String args [ ] ) { List < LocalDate > dates = new ArrayList < > ( ) ; dates.add ( Loca...
Getting list of all consecutive intervals from series of dates in Java
Java
I built a quite fat JavaFX application ( the JAR is about 128 MB ) and I got no problem in running in through IntelliJ . But when I run it from the terminal my 3D model loaders ( Fxyz3d library ) launch this exception.This is thrown only for the 3D-object Loader from the Fxyz3d library , not for my other normal FXML lo...
Exception in thread `` JavaFX Application Thread '' java.nio.file.FileSystemNotFoundException at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getFileSystem ( ZipFileSystemProvider.java:172 ) at jdk.zipfs/jdk.nio.zipfs.ZipFileSystemProvider.getPath ( ZipFileSystemProvider.java:158 ) at java.base/java.nio.file.Path.of (...
FileSystemNotFoundException while running JAR ( Fxyz3d library )
Java
java.lang.Class has methods to test if a given type is : isAnnotationisArrayisEnumisInterfaceisPrimitivebut how does one test that an object of type Class ( instanceof Class is true ) represents a declared , non-abstract class rather than in interface , enum , primitive , array , etc . For example : I was looking for a...
package org.acme ; public class ACME { public ACME ( ) { } public static void main ( String [ ] args ) { Class clazz = Class.forName ( `` org.acme.ACME '' ) ; // Expected I could use a clazz.isClass ( ) . } }
How to test that a type declared as `` public class '' is a class using java.lang.Class ?
Java
I have Map < Integer , Doctor > docLib=new HashMap < > ( ) ; to save class of Doctor.Class Doctor has methods : getSpecialization ( ) return a String , getPatients ( ) to return a collection of class Person.In the main method , I type : As you can see , I have problem with groupingBy , I try to send the same value d to...
public Map < String , Set < Person > > getPatientsPerSpecialization ( ) { Map < String , Set < Person > > res=this.docLib.entrySet ( ) .stream ( ) . map ( d- > d.getValue ( ) ) . collect ( groupingBy ( d- > d.getSpecialization ( ) , d.getPatients ( ) ) //error ) ; return res ; }
Stuck with java8 lambda expression
Java
I face the below problem in java 8 the real question is why there is an extra character appended to the currency symbol .. ? why the above program behaves in this way ... ? .what is the problem in it & how to rectify it .. ? Thanks
import java.util . * ; import java.text . * ; import java.lang . * ; class NumberTest5 { public static void main ( String [ ] args ) { Locale loc = new Locale ( `` sr '' , '' ME '' ) ; DecimalFormat df = ( DecimalFormat ) NumberFormat.getCurrencyInstance ( loc ) ; System.out.println ( `` \n '' + '' currencySymbol : '' ...
Currency Symbol given by DecimalFormat looks invalid
Java
I tried to set up a onClickListener inside my fragment.Here is my layout : Does anyone know why the onClick method never gets called when I hit my button ? Did I miss anything ?
public class HomeFragment extends Fragment implements View.OnClickListener { Button btn_eventList ; public HomeFragment ( ) { // Required empty public constructor } @ Overridepublic View onCreateView ( LayoutInflater inflater , ViewGroup container , Bundle savedInstanceState ) { View view = inflater.inflate ( R.layout....
onClick method in fragment never gets called
Java
Note : I am well aware that initializing it fixes the problem ; I just assumed the compiler would follow the execution path and see that foo would actually be initialized at the point where it suggests it 'may ' not be.My initial assumption would be that if the length was never over 3 , I would never need to allocate m...
List < String > foo ; int length = 5 ; if ( length > 3 ) { foo = new ArrayList < String > ( ) ; } if ( length > 4 ) { foo.add ( `` bar '' ) ; } List < String > foo = null ;
Unexpected behaviour with Java initialization
Java
I am trying to demonstrate an `` anytime algorithm '' - an algorithm that can be stopped at any time and returns its current result . The demo algorithm just returns some mathematical function of i , where i is increasing . It chcecks whether it is interrupted , and if so , returns the current value : In the main progr...
static int algorithm ( int n ) { int bestSoFar = 0 ; for ( int i=0 ; i < n ; ++i ) { if ( Thread.interrupted ( ) ) break ; bestSoFar = ( int ) Math.pow ( i , 0.3 ) ; } return bestSoFar ; } Runnable task = ( ) - > { Instant start = Instant.now ( ) ; int bestSoFar = algorithm ( 1000000000 ) ; double durationInMillis = Du...
Why is n't the last thread interrupted ?
Java
In the program I 'm currently working on , there 's one part that 's taking a bit long . Basically , I have a list of Strings and one target phrase . As an example , let 's say the target phrase is `` inventory of finished goods '' . Now , after filtering out the stop word ( of ) , I want to extract all Strings from th...
String [ ] targetWords ; // contains `` inventory '' , `` finished '' , and `` goods '' ArrayList < String > extractedStrings = new ArrayList < String > ( ) ; for ( int i = 0 ; i < listOfWords.size ( ) ; i++ ) { String [ ] words = listOfWords.get ( i ) .split ( `` `` ) ; outerloop : for ( int j = 0 ; j < words.length ;...
Faster String Matching/Iteration Method ?
Java
Here is my code [ Kotlin ] [ Java ] - it inherits kotlin class Parent.the Parent class has the Generics called T ( out ) , V ( in ) , so I think..the constructor of class Child should be..i.e . the second argument vList should bebecause the V of parent 's Generic is 'in ' but it's..is there anyone can explain this ? he...
internal abstract class Parent < out T , in V > constructor ( tList : List < T > , vList : List < V > ) { abstract fun get ( ) : List < T > abstract fun set ( v : List < V > ) } final class Child extends Parent < Number , String > { public Child ( @ NotNull List < ? extends Number > tList , @ NotNull List < ? extends S...
generics between java and kotlin ! ! help me ?
Java
Let 's say I have the following method I want to refactorThis method 's purpose is to act as a proxy attaching error handling on the stream rethrowing in a wrapping exception CustomRuntimeException . So when we consume it later in the flow , I do n't have to handle those exceptions everywhere but only CustomRuntimeExce...
protected Stream < T > parseFile ( File file , Consumer < File > cleanup ) { try { return parser.parse ( file ) ; // returns a Stream < T > } catch ( XmlParseException e ) { // child of RuntimeException throw new CustomRuntimeException ( e ) ; } finally { if ( file ! = null ) { cleanup.accept ( file ) ; } } throw new I...
Java 8 stream attaching error handling for later consumption
Java
I have two numbers . I want the lower number to be the subtracted from both values.The following is kinda ugly to me , so is there a better approach I could do this ?
x : 1000y : 200= > result : x = 800 and y = 0. if ( x < = y ) { y = y - x ; x = 0 } else { x = x - y ; y = 0 ; }
Subtracting lowest number from several numbers
Java
This question lead me to do some testing : Tangential to the other post , it 's interesting to note how much faster the comparison is when the Object that we 're comparing is initialized . The first two numbers in each output are when the Object was null and the latter two numbers are when the Object was initialized . ...
public class Stack { public static void main ( String [ ] args ) { Object obj0 = null ; Object obj1 = new Object ( ) ; long start ; long end ; double difference ; double differenceAvg = 0 ; for ( int j = 0 ; j < 100 ; j++ ) { start = System.nanoTime ( ) ; for ( int i = 0 ; i < 1000000000 ; i++ ) if ( obj0 == null ) ; e...
Null/Object and Null/Null comparison efficiency
Java
Why does a distinct count of an int array return a different result than a count of an Integer array ? I would expect a result of 3 in both cases.Results
int [ ] numbers1 = { 1 , 2 , 3 } ; System.out.println ( `` numbers1 : `` + Arrays.toString ( numbers1 ) ) ; System.out.println ( `` distinct numbers1 count : `` + Stream.of ( numbers1 ) .distinct ( ) .count ( ) ) ; Integer [ ] numbers2 = { 1 , 2 , 3 } ; System.out.println ( `` numbers2 : `` + Arrays.toString ( numbers2...
Java streams : count distinct values in array of primitives
Java
I 'm rebuilding my app from java to flutter . I 'm using firebase to store colors as integer values . In java I can use the following to convert rgb values to integer values : And I can use the following to convert from an integer value to rgb : How can I convert a Java integercolor to a flutter color and back ? An exa...
colorInt = ( 255 < < 24 ) | ( color.red < < 16 ) | ( color.green < < 8 ) | color.blue ; int r = ( colorInt > > 16 ) & 0xFF ; int g = ( colorInt > > 8 ) & 0xFF ; int b = colorInt & 0xFF ; ( 255 < < 24 ) | ( 154 < < 16 ) | ( 255 < < 8 ) | 147 ; ( 4278190080 ) | ( 10092544 ) | ( 65280 ) | 147 ; ( 4278190080 ) | ( 10092544...
java integer color to flutter color and back
Java
I came across this bug in our code today and it took a while to figure . I found it interesting so I decided to share it . Here is a simplified version of the problem : Guess what Test.getTest ( ) ; returns & why ?
public class Test { static { text = `` Hello '' ; } public static String getTest ( ) { return text + `` World '' ; } private static String text = null ; }
Java Question about Static