lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
Inspired by this question , I wrote the test : This program are printed in common case : First : I explain this behaviour is presence of the JIT-compiler . JIT-compiler cache value non volatile field for each thread after `` warmup '' . It right ? Second : If first right or not right , how can I verify this ? P.S . - I...
public class Main { private static final long TEST_NUMBERS = 5L ; private static final long ITERATION_NUMBER = 100000L ; private static long value ; public static void main ( final String [ ] args ) throws Throwable { for ( int i=0 ; i < TEST_NUMBERS ; i++ ) { value = 0 ; final Thread incrementor = new Thread ( new Inc...
Is JIT reason of this behaviour ?
Java
Suppose I have an interface : Now , suppose I have created an instance of this interface somewhere in my main class , How can I go about printing this function , in plain text ? So , something a bit like this : Running a .toString on this Function prints something like Main $ 1 @ 6d06d69c . How can I go about getting t...
public interface Function { double function ( double input ) ; } Function f = ( x ) - > x ; int f ( double x ) { return x }
Is there a way to print a functional interface ?
Java
I 'm a beginner in Java programming . Currently I 'm reading about Inheritance and the equals method at this page.I understand the explanations until this point : Compare the classes of this and otherObject . If the semantics of equals can change in subclasses , use the getClass test : If the same semantics holds for a...
if ( getClass ( ) ! = otherObject.getClass ( ) ) return false ; if ( ! ( otherObject instanceof ClassName ) ) return false ;
Java equals ( ) method - how does 'semantics of equals in subclasses ' determine the use of getClass and instanceof
Java
So I got a classMenuBarController is an interface whose implementation is set via setController after the MenuBar ist created . The code throws a NullpointerException at menu.add ( createMenuItem ( `` Report '' , controller : :writeReport ) ) which can only be caused by controller : :writeReport . If I replace this wit...
public class MenuBar extends JMenuBar { MenuBarController controller ; public MenuBar ( ) { JMenu menu = new JMenu ( `` File '' ) ; menu.add ( createMenuItem ( `` Report '' , controller : :writeReport ) ) ; menu.add ( createMenuItem ( `` Save '' , controller : :save ) ) ; menu.add ( createMenuItem ( `` Import '' , cont...
Java method reference throws NPE
Java
I 've been experimenting with Python as a begninner for the past few hours . I wrote a recursive function , that returns recurse ( x ) as x ! in Python and in Java , to compare the two . The two pieces of code are identical , but for some reason , the Python one works , whereas the Java one does not . In Python , I wro...
x = int ( raw_input ( `` Enter : `` ) ) def recurse ( num ) : if num ! = 0 : num = num * recurse ( num-1 ) else : return 1 return num print recurse ( x ) public class Default { static Scanner input = new Scanner ( System.in ) ; public static void main ( String [ ] args ) { System.out.print ( `` Enter : `` ) ; int x = i...
Why do these two similar pieces of code produce different results ?
Java
Why the order of declaration important for Java enums , I mean why does this give ( compile time ) errorsbut this one is fine :
public enum ErrorCodes { public int id ; Undefined ; } public enum ErrorCodes { Undefined ; public int id ; } .
Order of member fields in Enum
Java
below is my code where Im trying to check id id =101 and getting the name= Pushkar assosiated with the id=101.But the code is not working as expected .
import org.json.simple.JSONArray ; import org.json.JSONException ; import org.json.simple.JSONObject ; import org.json.simple.parser.JSONParser ; import org.json.simple.parser.ParseException ; public class A6 { public static void main ( String [ ] args ) throws ParseException , JSONException { String out1= '' { \ '' Em...
Conditionally getting json data using java
Java
I was trying to check that a String is a palindrome using StringBuilder and reverse ( ) . For a word with no symmetry like `` chan '' it correctly returns false , but it also returns false for genuine palindromes like `` madam '' .Code : Output : I am running Eclipse Neon with Java 8 .
StringBuilder str = new StringBuilder ( `` madam '' ) ; StringBuilder str2 = new StringBuilder ( str ) ; boolean res = str2.equals ( str.reverse ( ) .toString ( ) .trim ( ) ) ; System.out.println ( str + `` `` + str2 ) ; System.out.println ( res ) ; madam madamfalse
Why is this reversed StringBuilder not equal to the original String , when it is a palindrome ?
Java
I have this code : I know , it looks like it should be an enum , and it would be , but it needs to inherit from Person , an abstract class.My problem is : If I try to access the list of Guys , I 'm okay . But it I try to access any one Guy in particular , I have a problem : Guy gets loaded before Person . However , sin...
public abstract class Person { public static final class Guy extends Person { public static final Guy TOM = new Guy ( ) ; public static final Guy DICK = new Guy ( ) ; public static final Guy HARRY = new Guy ( ) ; } public static final List < Guy > GUYS = ImmutableList.of ( Guy.TOM , Guy.DICK , Guy.HARRY ) ; }
How do I avoid problems arising from accessing static fields before the class is initialized ?
Java
Given a code sample from Oracle docs https : //docs.oracle.com/javase/8/docs/api/java/util/concurrent/locks/StampedLock.htmlAnd provided that all methods of class Point might be called from different threads : Why exactly do we not need fields x and y to be declared as volatile ? Is it guaranteed that the code executin...
class Point { private double x , y ; private final StampedLock sl = new StampedLock ( ) ; void move ( double deltaX , double deltaY ) { // an exclusively locked method long stamp = sl.writeLock ( ) ; try { x += deltaX ; y += deltaY ; } finally { sl.unlockWrite ( stamp ) ; } } double distanceFromOrigin ( ) { // A read-o...
Why do n't we need volatile with StampedLock ?
Java
I have this method : With these two variables : But I 'm getting found for addAll ( Stream ) filteredListIn.addAll ( Stream.of ( listRef ) ^ method Collection.addAll ( Collection ) is not applicable ( argument mismatch ; Stream can not be converted to Collection ) method List.addAll ( Collection ) is not applicableWhat...
filteredListIn.addAll ( Stream.of ( listRef ) .filter ( results - > results.getTitle ( ) .contains ( query.toString ( ) .toLowerCase ( ) ) ) ) ; private List < Results > listRef = new ArrayList < > ( ) ; List < Results > filteredListIn = new ArrayList < > ( ) ;
How to solve `` add all in list can not be applied to ''
Java
I was wondering why is it not possible to call List < Number > not with List < Integer > even Integer is an extended class of the abstract class Number ? There is a logical error as I could call a Method with the parameter Number also with Integer . To solve it I could work with List < ? > or List < ? extends Number > ...
public class Que { public void enterNumbers ( List < Number > nummern ) { for ( Number number : nummern ) { System.out.println ( number + `` \n '' ) ; } } public void enterNum ( Number num ) { System.out.println ( `` This is a number `` + num ) ; } public static void main ( String [ ] args ) { Que que = new Que ( ) ; I...
Why is it not possible to call List < Number > not with List < Integer > even if Integer extends Number ?
Java
So , follwoing some job interviews I wanted to write a small program to check that i++ really is non-atomic in java , and that one should , in practice , add some locking to protect it . Turns out you should , but this is not the question here.So I wrote this program here just to check it . The thing is , it hangs . It...
public class Test { static /* volatile */ long t = 0 ; static long [ ] counters = new long [ 2 ] ; static /* volatile */ boolean stop = false ; static Object o = new Object ( ) ; public static void main ( String [ ] args ) { Thread t1 = createThread ( 0 ) ; Thread t2 = createThread ( 1 ) ; t1.start ( ) ; t2.start ( ) ;...
Java multithreading - joining a CPU heavy thread and volatile keyword
Java
Java.Is there a difference in a way I initialize a variable : or Can the results be different ? Here I tried to do it with a very big floats , but looks like the loss of precision is the same.- > 2.0E9 2.0E9 true 2.0E9 2.0E9 trueAny difference with the doubles ?
float f = 100 ; //implies a cast from integer to float float f = 100f ; //simply a float initialization float f1 = ( float ) 2000000000 ; float f2 = ( float ) 2000000050 ; float f3 = 2000000000f ; float f4 = 2000000050f ; System.out.println ( f1 + `` `` + f2 + `` `` + ( f1==f2 ) + `` `` + f3 + `` `` + f4 + `` `` + ( f3...
Is there a difference in how I initialize a variable : float f = 100 ; or float f = 100f ?
Java
Is using a String ( ) constructor as against string literal beneficial in any scenario ? Using string literals enable reuse of existing objects , so why do we need the public constructor ? Is there any real world use ? For eg. , both the literals point to the same object .
String name1 = `` name '' ; //new String ( `` name '' ) creates a new object.String name2 = `` name '' ;
Why is n't String ( ) constructor private ?
Java
I was using AtomicReference to implement AtomicInteger . However while in testing I notice even in single threaded environment the CAS operation got stuck once its value hit 128.. Am I doing something wrong or there is a caveat in AtomicReference ( may be related to CPU ) ? Here is my code :
public class MyAtomInt { private final AtomicReference < Integer > ref ; public MyAtomInt ( int init ) { ref = new AtomicReference < Integer > ( init ) ; } public MyAtomInt ( ) { this ( 0 ) ; } public void inc ( ) { while ( true ) { int oldVal = ref.get ( ) ; int nextVal = oldVal + 1 ; boolean success = ref.compareAndS...
Why AtomicReference CAS return false with value 128 ?
Java
Purpose is to reduce the number of variables so instead of making many variables I want to do something like this : Instead of
Scanner scnr = new Scanner ( System.in ) ; int number = 0 ; scnr.nextInt ( ) ; if ( ( ( scnr.nextInt ( ) > = 4 ) & & ( scnr.nextInt ( ) < =10 ) ) ) { number = scnr.nextInt ( ) ; } Scanner scnr = new Scanner ( System.in ) ; int number = 0 ; int validNum = 0 ; number = scnr.nextInt ( ) ; if ( ( ( number > = 4 ) & & ( num...
Validate scanner user input in if statement WITHOUT variables
Java
OverviewUsing FlyingSaucer within a JavaFX application , to avoid WebView for various reasons : does n't provide direct API access to its scrollbars for synchronous behaviour ; bundles JavaScript , which is a huge bloat for my use case ; andfailed to run on Windows.FlyingSaucer uses Swing , which requires wrapping its ...
private static class Flawless { private final XHTMLPanel panel = new XHTMLPanel ( ) ; private final JFrame frame = new JFrame ( `` Single Page Demo '' ) ; private Flawless ( ) { frame.getContentPane ( ) .add ( new JScrollPane ( panel ) ) ; frame.pack ( ) ; frame.setSize ( 1024 , 768 ) ; } private void update ( final or...
Blurry render of SwingNode in JavaFX on Windows
Java
I have an XML file I want to generate an XSD schema from , using xmlbeans , specifically inst2xsd . I 'd like to package the script so it can be run via Maven.I could not find any documentation how to run inst2xsd when installing xmlbeans using Maven.This is my pom.xml so far : Installing this via mvn install works . J...
< project > < modelVersion > 4.0.0 < /modelVersion > < groupId > de.wolkenarchitekt < /groupId > < artifactId > xml-to-xsd < /artifactId > < version > 1 < /version > < dependencies > < dependency > < groupId > org.apache.xmlbeans < /groupId > < artifactId > xmlbeans < /artifactId > < version > 3.1.0 < /version > < /dep...
Generate XSD from XML using xmlbeans , inst2xsd and Maven
Java
I need some kind of service that will run a few tasks simultaneously and in an interval of 1 second for 1 minute.If one of the tasks fails , I want to stop the service and every task that ran with it with some kind of indicator that something went wrong , otherwise if after one minute everything went well the service w...
Runnable task1 = ( ) - > { int num = Math.rand ( 1,100 ) ; if ( num < 5 ) { throw new Exception ( `` something went wrong with this task , terminate '' ) ; } } Runnable task2 = ( ) - > { int num = Math.rand ( 1,100 ) return num < 50 ; } ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPoo...
Java stop executor service once one of his assigned tasks fails for any reason
Java
May be simple question but i am confused which code is optimized ? and should i use ? what is the difference in internal process ?
String str = editText.getText ( ) .toString ( ) ; str =str.trim ( ) .toLowerCase ( ) ; textView.setText ( str ) ; textView.setText ( editText.getText ( ) .toString ( ) .trim ( ) .toLowerCase ( ) ) ;
Which is optimized way ?
Java
I have sort of a hard time understanding an implementation detail from java-9 ImmutableCollections.SetN ; specifically why is there a need to increase the inner array twice.Suppose you do this : More exactly I perfectly understand why this is done ( a double expansion ) in case of a HashMap - where you never ( almost )...
Set.of ( 1,2,3,4 ) // 4 elements , but internal array is 8 int idx = Math.floorMod ( pe.hashCode ( ) ^ SALT , elements.length ) ; while ( true ) { E ee = elements [ idx ] ; if ( ee == null ) { return -idx - 1 ; } else if ( pe.equals ( ee ) ) { return idx ; } else if ( ++idx == elements.length ) { idx = 0 ; } } if ( ee ...
ImmutableCollections SetN implementation detail
Java
This piece of code compiles in Eclipse but not in javac : javac output : Which compiler is wrong and why ? ( Eclipse bug report and parts of discussion here )
import java.util.function.Consumer ; public class Test { public static final void m1 ( Consumer < ? > c ) { m2 ( c ) ; } private static final < T > void m2 ( Consumer < ? super T > c ) { } } C : \Users\lukas\workspace > javac -versionjavac 1.8.0_92C : \Users\lukas\workspace > javac Test.javaTest.java:5 : error : method...
Lower-bounded wild card causes trouble in javac , but not Eclipse
Java
I 'm currently taking an intro to Java class and I 'd really like to improve but I 'm struggling to complete this assignment . The requirements for the assignment was toImplement a loop that allows the user to continue to play the game by typing yes.Keep track of the users : Wins , Losses and Games Played using increme...
public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System.in ) ; String input , inputUpper ; char userGuess ; char coinFlip ; int randNum ; int wins = 0 ; int losses = 0 ; int total = 0 ; String choice = `` yes '' ; do { System.out.print ( `` I will flip a coin guess ' H ' for heads or 'T ' for ...
How to write Do/While validation ?
Java
I created java binding library via visual studio extension called Xamarin.GradleBinding . I added ru.rambler.android : swipe-layout:1.0.14 package and while using its SwipeLayout , it all works well . But unfortunately it did not created corresponding C # classes or anything like that . I tried adding package manually ...
public void reset ( ) IntPtr type = JNIEnv.FindClass ( `` ru/rambler/libs/swipe_layout/SwipeLayout '' ) ; IntPtr method = JNIEnv.GetMethodID ( type , `` reset '' , `` ( ) V '' ) ; try { JNIEnv.CallObjectMethod ( _swiper.Handle , method ) ; } catch ( Exception ex ) { var s = ex.Message ; } JNIEnv.CallObjectMethod ( _swi...
Xamarin.Android binding Call java Object method
Java
I do not need to change the implementation of the final method , I just want to change the Javadoc for it .
public class BaseClass { /** * Gets the value . */ public final String getValue ( ) { // returns something . } } public class SubClass extends BaseClass { /** * Gets the value . * < p/ > * The value is meaningless for SubClass . */ @ Override // Can not override final method public final String getValue ( ) { super.get...
How to override the javadoc for a final method in a sub class ?
Java
I 'm working on an encryption algorithm and I need to generate some information in Java ( a binary file ) to read in C++.I 'm not sure if the problem is how I create the binary file or how I read it , though I can perfectly read the information in Java.So I made a simple test . In Java I save the number 9 to a binary f...
int x = 9 ; try { ObjectOutputStream salida=new ObjectOutputStream ( new FileOutputStream ( `` test.bin '' ) ) ; salida.writeInt ( x ) ; salida.close ( ) ; System.out.println ( `` saved '' ) ; } catch ( Exception e ) { System.out.println ( e ) ; } streampos size ; char * memblock ; ifstream file ( `` test.bin '' , ios ...
How do I read a binary file in C++ if I generate it in Java ?
Java
When i was reviewing Builder pattern in Josh 's Bloch book , i came up with simpler implementation , but i 'm not sure whether it 's proper . For example : Is it can still be considered as a Builder pattern or i missed something ? EDITWhat about this ?
public class Test { public static void main ( String [ ] args ) { Numbers first = new Numbers.Builder ( ) .setD ( 3.14 ) .build ( ) ; System.out.println ( first ) ; Numbers second = new Numbers.Builder ( ) .setI ( 17 ) .setF ( 1.24F ) .build ( ) ; System.out.println ( second ) ; System.out.println ( first ) ; } } final...
Less verbose Builder pattern ?
Java
Why does the following code : produces this result : should n't first part ( -- -- -- -- -- -- -- -- -- ) be excluded from the output ? Also , I understood that combiner in collect can potentially be called out of order so it is possible to have instead :76:77:78-:79:80:81 e.g . :63:64:65-:79:80:81 ? UPDATE ( after @ H...
StringBuilder sb22 = IntStream .range ( 1 , 101 ) .filter ( x - > x > 50 ) .boxed ( ) .parallel ( ) .collect ( // object that is used in accumulator to do accumulating on StringBuilder : :new , // use object from above and call append on it with each stream element as argument ( sb , a ) - > sb.append ( `` : '' + a ) ,...
Java stream - collect combiner
Java
I came across something like This line is from the source of GWT . By digging into Java 's grammar I found it to be ( `` .new '' ) inner creator.But I did n't find any proper documentation about why exactly we need the inner creator.How does this differ from a normal object/instance creator ?
ArgProcessor argProcessor = runWebApp.new ArgProcessor ( options ) ;
What is inner creator ( objectinstance.new ) in Java ?
Java
The compareToIgnoreCase method of String Class is implemented using the method in the snippet below ( jdk1.8.0_45 ) . i . Why are both Character.toUpperCase ( char ) and Character.toLowerCase ( char ) used for comparison ? Would n't either of them suffice the purpose of comparison ? ii . Why was s1.toLowerCase ( ) .com...
public int compare ( String s1 , String s2 ) { int n1 = s1.length ( ) ; int n2 = s2.length ( ) ; int min = Math.min ( n1 , n2 ) ; for ( int i = 0 ; i < min ; i++ ) { char c1 = s1.charAt ( i ) ; char c2 = s2.charAt ( i ) ; if ( c1 ! = c2 ) { c1 = Character.toUpperCase ( c1 ) ; c2 = Character.toUpperCase ( c2 ) ; if ( c1...
Java : Why String.compareIgnoreCase ( ) uses both Character.toUpperCase ( ) and Character.toLowerCase ( ) ?
Java
I am receiving a MultipartFile Spring object from rest controller . I am trying to convert any inage file to JPG image but I just need the byte array to save it on mongoDbI found this code to do thatBut result as a false with not error , so ImageIO.write is not workingAlso I found this to do the same but using File obj...
public boolean convertImageToJPG ( InputStream attachedFile ) { try { BufferedImage inputImage = ImageIO.read ( attachedFile ) ; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ( ) ; boolean result = ImageIO.write ( inputImage , `` jpg '' , byteArrayOutputStream ) ; return result ; } catch ( IOE...
How to convert any image to JPG ?
Java
I am fetching data from server and saving in room database and then from room showing it in recycler view.Data is perfectly saving in room database and showing in recycler view.Problem : When I am deleting some data from server database then its old copy that saved earlier still persists in room.What I want : I do n't ...
@ Daopublic interface UserDao { @ Insert ( onConflict = OnConflictStrategy.REPLACE ) void Insert ( User ... users ) ; @ Query ( `` SELECT * FROM Users '' ) LiveData < List < User > > getRoomUsers ( ) ; } @ Entity ( tableName = `` Users '' ) public class User { @ NonNull @ PrimaryKeyprivate String id ; @ ColumnInfo ( na...
Data is showing in room database even after deleted from server
Java
Consider the following example : In the main method , I am calling test with a String and an ArrayList < Integer > object . Both are different things and assigning an ArrayList to String ( generally ) gives a compile error.But I am doing exactly that in the 3rd line of test and the program compiles and runs fine . Firs...
public class Learn { public static < T > T test ( T a , T b ) { System.out.println ( a.getClass ( ) .getSimpleName ( ) ) ; System.out.println ( b.getClass ( ) .getSimpleName ( ) ) ; b = a ; return a ; } public static void main ( String [ ] args ) { test ( `` '' , new ArrayList < Integer > ( ) ) ; } } String aString = n...
How type inference work for method calls ?
Java
I was solving some exercises to understand better how inner classes in java work . I found one quite interesting exercise . The condition of the exercise is to make printName ( ) print `` sout '' instead of `` main '' with minimum changes . There is its code : We 've got an amusing situation - the two classes have is-A...
public class Solution { private String name ; Solution ( String name ) { this.name = name ; } private String getName ( ) { return name ; } private void sout ( ) { new Solution ( `` sout '' ) { void printName ( ) { System.out.println ( getName ( ) ) ; // the line above is an equivalent to : // System.out.println ( Solut...
Why do method ( ) and super.method ( ) refer to different things in an anonymous subclass ?
Java
Try this piece of code - The output is - Why does System.out.println ( ) terminate at ASCII code zero ? I tried this in JCreator LE under Windows 7 .
public class WhitespaceTest { public static void main ( String [ ] args ) { int x = 0 ; char c = ( char ) x ; System.out.println ( `` c -- > '' +c+ '' < -- -this does n't print ? `` ) ; } } c -- >
Why does System.out.println ( ) terminate at ASCII Code zero
Java
I 'm trying to improve startup performance of a Java web app in development environment . It uses jetty-maven-plugin and mvn jetty : run is used to start the app.I followed instructions at http : //www.eclipse.org/jetty/documentation/9.3.x/jetty-classloading.html to register this new CachingWebAppClassLoader.However , ...
< Configure id= '' mywebapp '' class= '' org.eclipse.jetty.webapp.WebAppContext '' > ... < Set name= '' classLoader '' > < New class= '' org.eclipse.jetty.webapp.CachingWebAppClassLoader '' > < Arg > < Ref refid= '' mywebapp '' / > < /Arg > < /New > < /Set > ... < /Configure >
How to enable CachingWebAppClassLoader in Jetty Maven Plugin ?
Java
I am creating a web application similar to quora/stackoverflow that allows users to perform CRUD operations on question bank ( question bank is very small , ~500 questions with maximum 5 answers per question ) along with search . How can I build a free flow search or auto suggestion functionality on question bank ? Tec...
questionId : Stringtags : [ String ] title : Stringdescription : Stringanswernotes : [ String ] applicableJobRole : [ Intern , Full Time ] state : [ Approved , UnderReview , Obsolete ] difficultyLevel : [ Easy , Medium , Hard ] noOfTimesUsed : intcreatedBy : user
How to build a free flow search on sql-server database tables ?
Java
I have this class where I cache instances and clone them ( Data is mutable ) when I use them.I wonder if I can face a reordering issue with this.I 've had a look at this answer and JLS but I am still not confident.My thinking : The runtime can reorder the statement in constructor and publish the current DataWrapper ins...
public class DataWrapper { private static final ConcurrentMap < String , DataWrapper > map = new ConcurrentHashMap < > ( ) ; private Data data ; private String name ; public static DataWrapper getInstance ( String name ) { DataWrapper instance = map.get ( name ) ; if ( instance == null ) { instance = new DataWrapper ( ...
Do I have reordering issue and is it due to reference escape ?
Java
In documentation code I see some things like this : what does characters like @ ( # ) meaning ?
/* * @ ( # ) File.java 1.142 09/04/01
meaning of @ ( # ) characters
Java
I have an exception handler which handles exception from an Activity class , the exception handler looks like this.it is initialized from the activity classwhen the control comes to the exception handler , the activity is not created , instead of a blank page that hangs my app.The only message I get isEDIT : Ok , after...
public class ExceptionHandler implements Thread.UncaughtExceptionHandler { public static final String TAG = `` Exception handler '' ; private final Context activity ; public ExceptionHandler ( Context activity ) { this.activity = activity ; } @ Override public void uncaughtException ( @ NonNull Thread thread , @ NonNul...
Why context.startActivity ( intent ) not starting the activity and how to handle exception in android ?
Java
The my question is addressed to the post : https : //shipilev.net/blog/2014/safe-public-construction/And , it is written : Notice that we do several reads of instance in this code , and at least `` read 1 '' and `` read 3 '' are the reads without any synchronization — that is , those reads are racy . One of the intents...
public class UnsafeDCLFactory { private Singleton instance ; public Singleton get ( ) { if ( instance == null ) { // read 1 , check 1 synchronized ( this ) { if ( instance == null ) { // read 2 , check 2 instance = new Singleton ( ) ; // store } } } return instance ; // read 3 } }
Java Memory Model and reordering operation
Java
I have a Java class and I need to write a similar one in F # . How can I define a private class inside public in f # ?
public class KnownRuleGoals { void record ( ) { knownParsingSet.add ( new KnownParsing ( ) ) ; } private class KnownParsing { Rule [ ] knownParsing ; KnownParsing ( ) { ... } void doWork ( ) { ... } } }
f # private class inside public one
Java
I want to run certain tests in Lists . The Lists can contain entirely different classes.I have one method to check the consistency of the list - not null , not empty , no more than x elements . This is common to all the lists . Then I want to test each of the objects , using overloading.The idea would be something like...
public static < T > void check ( List < T > list ) { //do general checks for ( T element : list ) { check ( element ) ; } } public static void check ( SomeType element ) { ... } public static void check ( SomeOtherType element ) { ... } public static void check ( T element ) { ... } public static void check ( List < So...
Overloading / generics in Java
Java
I run a very simple , single-threaded java program . When I check the threads using command under Ubuntuit shows there are 14 threads at OS level . I expect there is only one thread when the program has one thread , and x threads if the program has x threads . Is my expectation wrong ?
ps -eLf
When I run a single-threaded Java program why are there are multiple threads at the OS level ?
Java
In my java program I have a for-loop looking roughly like this : Since the size of the list is n't changing , I tried to accelerate the loop by replacing the termination expression of the loop with a variable . My idea was : Since the size of an ArrayList can possibly change while iterating it , the termination express...
ArrayList < MyObject > myList = new ArrayList < MyObject > ( ) ; putThingsInList ( myList ) ; for ( int i = 0 ; i < myList.size ( ) ; i++ ) { doWhatsoever ( ) ; } ArrayList < MyObject > myList = new ArrayList < MyObject > ( ) ; putThingsInList ( myList ) ; int myListSize = myList.size ( ) ; for ( int i = 0 ; i < myList...
Java For-Loop - Termination Expression speed
Java
I ca n't seem to figure out how to chain constructors when the constructor I 'm trying to call is supposed to use values passed to the constructor I 'm calling it from.I tried this : but I 'm told that the call to this must be on the first line of the constructor.I 'm trying to call this constructorIdeally , I could ch...
public BoundingBox ( Point a , Point b ) { Point [ ] points = { a , b } this ( points ) ; } public BoundingBox ( Point [ ] input ) { //do some work }
Constructor chaining with array in Java
Java
Is there a way to add additional information to a java stacktrace ? I am developing an interpreter for a script language and would like to see the corresponding lines of script code in the java stacktrace.The output could look something like this : or this : This would make debugging a lot easier , unfortunately google...
java.lang.NullPointerException at package.IPF_Try.execute ( IPF_Try.java:76 ) called in script.scr:155at package.IPF_Block.execute ( IPF_Block.java:304 ) at package.IPF_If.execute ( IPF_If.java:105 ) called in script.scr:130at package.IPF_Block.execute ( IPF_Block.java:304 ) at package.IPF_Main.execute ( IPF_Main.java:...
Add user-specified information to java stack traces
Java
I am using a lambda to implement a functional interface in the Java program below . When the lambda is passed as an argument to a generic method , the compiler flags an `` incompatible types '' error because it infers that the lambda implements the Func < Shape > interface , which has the compiler interpreting the lamb...
public class Main { public static void main ( String ... args ) { methodB ( thing - > Main.testRound ( thing ) ) ; // incompatible types methodB ( Main : :testRound ) ; // no problem here } static < T extends Shape > void methodB ( Func < T > function ) { } static boolean testRound ( Round thing ) { return true ; } } i...
Why does type inference fail for lambda , but succeed for equivalent method reference ?
Java
In my Java 11 application , I want to get Product Updates from a repository . One Product Update has a updateId and a list of productIds to update . If there are no product numbers that should be updated for update with updateId = X , I still want to write to another table that I 've processed the update X ; updateStat...
List < ProductUpdate > productUpdateList = updateStatusRepository.getProductUpdates ( ) ; Map < String , Set < String > > productUpdateMap = productUpdateList .stream ( ) .collect ( Collectors.groupingBy ( ProductUpdate : :getUpdateId , Collectors.mapping ( ProductUpdate : :getProductNo , Collectors.toSet ( ) ) ) ) ; p...
Java collect with grouping and mapping for ` set ` , but need an empty set if all values are ` null `
Java
This is more of a theoretical question to understand Java 's evaluation of arithmetic operations . Since + and - have the same precedence , I do n't quite understand how Java evaluates the following expressions ( where there are more than one + and - operators between the two operands ) .From the Java 8 Language Specif...
public static void main ( String [ ] args ) { int a = 1 ; int b = 2 ; System.out.println ( a+-b ) ; // results in -1 System.out.println ( a-+b ) ; // results in -1 System.out.println ( a+-+b ) ; // results in -1 System.out.println ( a-+-b ) ; // results in 3 System.out.println ( a-+-+b ) ; // results in 3 System.out.pr...
Java precedence for multiple + and - operators
Java
I am facing a weird issue . My REST API server started successfully initially but within a second it shows an error : rest_web_1 exited with code 1Heroku Logs : Updated : Can anyone please help me to figure out what 's going wrong here ?
2017-08-02T17:10:17.046289+00:00 heroku [ web.1 ] : State changed from starting to crashed2017-08-02T17:32:02.558126+00:00 heroku [ web.1 ] : State changed from crashed to starting2017-08-02T17:32:08.592558+00:00 heroku [ web.1 ] : Starting process with command ` java $ JAVA_OPTS -jar target/rest-api-0.0.1-SNAPSHOT.jar...
Dropwizard REST API server exited with code 1
Java
I have an immutable User entity : I need to add a method that will return information if the user 's password must be changed i.d . it has not been changed for more than the passwordValidIntervalInDays system setting . The current approach : The question is how to make the above code more object oriented and avoid the ...
public class User { final LocalDate lastPasswordChangeDate ; // final id , name , email , etc . } public class UserPasswordService { private SettingsRepository settingsRepository ; @ Inject public UserPasswordService ( SettingsRepository settingsRepository ) { this.settingsRepository = settingsRepository ; } public boo...
How to avoid anemic data model ? Can repositories be injected into entities ?
Java
I find myself again and again faced with a similar problem : there 's some piece of code that processes data as it arrives from the user/network/produces of some sort . For efficiency reasons , I do n't want to call flush ( ) or commit ( ) on every piece of data that I receive , but only occasionally.I usually come up ...
class Processor { private final static MAX_SAVE_PERIOD = 60000 ; private final static MIN_SAVE_PERIOD = 20000 ; private final static int MAX_BUFFER = 10000 ; Arraylist < Data > dataBuffer = new Arraylist < Data > ( ) ; private long lastSave = 0 ; public Saver ( ) { new Timer ( ) .schedule ( new TimerTask ( ) { periodic...
periodic save/flush/commit - is there a name to this pattern ?
Java
My Sunday challenge is to get and persist working days in a particular year to a CSV , etc file.I have following code and the problem I am facing is : how to print dates in a specific format i.e . YYYYMMDD as the code currently prints something like Sat Jan 19 00:00:00 CET 2019 . Also , if I can exclude week-ends and g...
import java.io . * ; import java.util . * ; import java.text.SimpleDateFormat ; public class DatesInYear { public static SimpleDateFormat dateFormat = new SimpleDateFormat ( `` yyyyMMdd '' ) ; public static void main ( String [ ] args ) throws java.lang.Exception { Date dt = new Date ( ) ; System.out.println ( dt ) ; L...
Java Get All Working Days in a year in YYYYMMDD format
Java
I encountered a weird problem using Optionals and anonymous classes : The first two methods do not compile with the errorI 'd expected that , since both implement the interface Bar all three approaches work . I also can not figure out why the third option fixes the problem . Can anyone explain this please ?
public class Foo { interface Bar { } void doesNotCompile ( ) { Optional.of ( new Bar ( ) { } ) .orElse ( new Bar ( ) { } ) ; } void doesNotCompile2 ( ) { final Bar bar = new Bar ( ) { } ; Optional.of ( new Bar ( ) { } ) .orElse ( bar ) ; } void compiles1 ( ) { final Bar bar = new Bar ( ) { } ; Optional.of ( bar ) .orEl...
Optional.orElse does not compile with anonymous types
Java
I have a little Java application that implements a RESTful API using Micronaut 2.0.0 . Under the hood , it uses Redisson 3.13.1 to go to Redis . Redisson , in turn , uses Netty ( 4.1.49 ) .The application works fine in a 'classic ' java ( on HotSpot , both Java 8 and 11 ) .I 'm trying to build a native image out of thi...
native-image -- no-server -- no-fallback -H : +TraceClassInitialization -H : +PrintClassInitialization -- report-unsupported-elements-at-runtime -- initialize-at-build-time=reactor.core.publisher.Flux , reactor.core.publisher.Mono -H : ConfigurationFileDirectories=target/config -cp target/app-1.0.0-SNAPSHOT.jar com.app...
How do you debug a 'No instances of ... are allowed in the image heap ' when building a native image ?
Java
Normally , the Java compiler confirms that all checked exceptions that are thrown are in the throw specification . Does anything special happen when a native function throws a java checked exception that was not in the functions throw specification list , or does is the throw specification list simply ignored at runtim...
void function ( JNIEnv * env , jclass jc ) { jclass newExcCls = env- > FindClass ( `` java/lang/NullPointerException '' ) ; env- > ThrowNew ( newExcCls , `` ERROR '' ) ; } public class Tester { static { System.loadLibrary ( `` MyLibrary '' ) ; } private static native void function ( ) ; public static void main ( String...
Java checked exception not in the function 's throw specification ?
Java
There is a table : key consists from 3 suffixes : region+s1+s2region , like US is always specified , but other ones can be not specified so * will be used for `` all '' .for example : for key = `` US_A_U '' value = 2 , because : trying to find full match : find in the table key ( `` US_A_U '' ) - notfound1 step less st...
package test ; import java.util.HashMap ; public class MainCLass { public static void main ( String [ ] args ) { // init map ( assuming this code will be run only once ) HashMap < String , String > map = new HashMap < > ( ) ; map.put ( `` US_A_B '' , `` 1 '' ) ; map.put ( `` US_A_* '' , `` 2 '' ) ; map.put ( `` US_*_* ...
finding vals from table with variable keys
Java
I 'm executing the following query using NamedParameterJdbcTemplate with a single parameter.DDL For TableSQLWhen I execute the query using I 'm getting the following error.If I remove the /100 for the SQL everything is working . Also if I hardcode the parameter it 's workingEnvironment : MSSql Server 2017 in Ubuntu.App...
create table TEST_TRANS ( DESCRIPTION_2 float , AMOUNT_STR varchar ( 255 ) , DESCRIPTION varchar ( 255 ) ) UPDATE TEST_TRANS SET DESCRIPTION_2 = CAST ( AMOUNT_STR as float ) / 100WHERE DESCRIPTION ! = : DESCRIPTION Objects.requireNonNull ( getNamedParameterJdbcTemplate ( ) ) .update ( testQuery , Collections.singletonM...
Spring NamedParameterJdbcTemplate issue with division and parameter in MSSqlServer
Java
So it seems that it 's a bad idea to pass this from a constructor in Java.My simple question is : Why ? There are some related questions on Stackoverflow , but none of them give a comprehensive list of issues that may arise.For instance , in this question , which is asking for a workaround to this problem , one of the ...
class Foo { Foo ( ) { Never.Do ( this ) ; } }
What exactly are the dangers of passing 'this ' from a Java constructor ?
Java
This is a problem I 'm trying to solve on my own to be a bit better at recursion ( not homework ) . I believe I found a solution , but I 'm not sure about the time complexity ( I 'm aware that DP would give me better results ) . Find all the ways you can go up an n step staircase if you can take k steps at a time such ...
static List < List < Integer > > problem1Ans = new ArrayList < List < Integer > > ( ) ; public static void problem1 ( int numSteps ) { int [ ] steps = { 1,2,3 } ; problem1_rec ( new ArrayList < Integer > ( ) , numSteps , steps ) ; } public static void problem1_rec ( List < Integer > sequence , int numSteps , int [ ] st...
Find all the ways you can go up an n step staircase if you can take k steps at a time such that k < = n
Java
I like services . I also like the module system . Unfortunately for me , before I used Java 9 I got in the habit of getting service providers from jars loaded at runtime via URLClassLoader , something like this ( I 'll use Java 10 's var for brevity ) : This works fine , even in Java 9 and beyond , but it loads the jar...
var url = new File ( `` myjar.jar '' ) .toURI ( ) .toURL ( ) ; var cl = new URLClassLoader ( new URL [ ] { url } , getClass ( ) .getClassLoader ( ) ) ; var services = ServiceLoader.load ( MyService.class , cl ) ; for ( var service : services ) { ... }
How to expand the module path at runtime
Java
This a question from a coding competitionThe original question can be found here http : //www.olympiad.org.za/olympiad/wp-content/uploads/2014/03/2013-PO-Question-Paper.pdfQuestion 5SHORTEST PATH THROUGH THE HALL [ by Alan Smithee of Hulsbos High ] The hall is packed wall to wall with rows of chairs , but in each row t...
4 7 2 9 2 9 8 11 8 11 8 11 8 11
Shortest path in a custom binary search tree
Java
In my project there is an existing old.jpdl.xml definition . It is working fine.Now I want to run another new.jpdl.xml definition.After deployment of ear file I tried to read new.jpdl.xml using new ProcessDefinitionId with help of below code.I believe that I am missing deployment steps . Can someone guide me , how to d...
public String getProcessInstanceID ( ProcessEngine processEngine , FlowControl flowcontrol , String processDefinitionID ) { String processInstanceID = null ; log.debug ( `` Entering method - getProcessInstanceID '' ) ; ProcessDefinitionQuery pdq = processEngine.getRepositoryService ( ) .createProcessDefinitionQuery ( )...
How to get ProcessDefinition using jpdl for JBPM 4.4 ?
Java
I am building an application that allows the user to connect to their local wifi network without leaving . However , whenever I select an item on the list the wrong network id comes up , and it connects to the wrong network . I 've noticed that : If I have three available networks , and I select the top one , the botto...
//from ` onCreate ` methodButton buttonScan = ( Button ) findViewById ( R.id.buttonScan ) ; WifiManager wifi = ( WifiManager ) getSystemService ( Context.WIFI_SERVICE ) ; ListView lv = ( ListView ) findViewById ( R.id.list ) ; lv.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) { @ Override public void ...
Android Array Adapter Selecting the wrong ID
Java
I 'm studying some exams of java and I came across with this question : The explanation describes that for an integer literal , the JVM matches in the order : int , long , Integer . Since there is no method with int type parameter , then looks for long type ; and so on.In this explanation they only provide the order fo...
//Write the output of this program : public static void method ( Integer i ) { System.out.println ( `` Integer '' ) ; } public static void method ( short i ) { System.out.println ( `` short '' ) ; } public static void method ( long i ) { System.out.println ( `` long '' ) ; } // ... public static void main ( String [ ] ...
invocation order of overloaded methods in JAVA
Java
In JEP193 , one of the specific goals of VarHandles is to provide an alternative to of using FieldUpdaters and AtomicIntegers ( and avoid some of the overhead associated with them ) . AtomicIntegers can be particularly wasteful in terms of memory since they 're a separate object ( they use around 36 bytes each , depend...
Benchmark Mode Cnt Score Error UnitsVarHandleBenchmark.atomic thrpt 5 448041037.223 ± 36448840.301 ops/sVarHandleBenchmark.atomicArray thrpt 5 453785339.203 ± 64528885.282 ops/sVarHandleBenchmark.fieldUpdater thrpt 5 459802512.169 ± 52293792.737 ops/sVarHandleBenchmark.varhandle thrpt 5 136482396.440 ± 9439041.030 ops/...
Unexpected VarHandle performance ( 4X slower than alternatives )
Java
For a small project ( Problem 10 Project Euler ) i tried to sum up all prime numbers below 2 millions . So I used a brute force method and iterated from 0 to 2'000'000 and checked if the number is a prime . If it is I added it to the sum : The result of this calculation is 1179908154 , but this is incorrect . So i chan...
private int sum = 0 ; private void calculate ( ) { for ( int i = 0 ; i < 2000000 ; i++ ) { if ( i.isPrime ( ) ) { sum = sum + i ; } } sysout ( sum ) }
Why is Java not telling me when I ca n't use Integer ?
Java
I have the following code that does a circular shift of the bits in the array : Then I thought it 's easier and more readable to go backwards like this : But I noticed that the second one ( method2 ) is slower than the first one ( method1 ) ! I noticed the difference because I 'm calling the method thousands of times ....
private static void method1 ( byte [ ] bytes ) { byte previousByte = bytes [ 0 ] ; bytes [ 0 ] = ( byte ) ( ( ( bytes [ 0 ] & 0xff ) > > 1 ) | ( ( bytes [ bytes.length - 1 ] & 0xff ) < < 7 ) ) ; for ( int i = 1 ; i < bytes.length ; i++ ) { byte tmp = bytes [ i ] ; bytes [ i ] = ( byte ) ( ( ( bytes [ i ] & 0xff ) > > 1...
Why does reversing a loop make it slower ?
Java
Here is the Java 8 code , using streams : I want to merge the output of map ( this : :getFields ) , i.e . a Stream < Set < Path > > into a Set < Path > and I 'm not sure of the correct usage of forEach.EDIT after Jon Skeet answer to summarize the comments and compile the codeThe two streams may be combined in one but f...
Set < String > getFields ( Path xml ) { final Set < String > fields = new HashSet < > ( ) ; for ( ... ) { ... fields.add ( ... ) ; ... } return fields ; } void scan ( ) { final SortedSet < Path > files = new TreeSet < > ( ) ; final Path root = new File ( `` ... .. '' ) .toPath ( ) ; final BiPredicate < Path , BasicFile...
Stream < Set < Path > > to Set < Path >
Java
I have a basic LWJGL window set up and I am trying to draw a square using the glBegin ( GL_QUADS ) method . Square square = new Square ( 25 , 25 , 25 ) , is the way I am calling my Square class to draw the square ... but it is a rectangle . When I call it I pass in all 25 's as the parameters . the first two are the st...
public Square ( float x , float y , float sl ) { GL11.glColor3f ( 0.5F , 0.0F , 0.7F ) ; glBegin ( GL11.GL_QUADS ) ; glVertex2f ( x , y ) ; glVertex2f ( x , y+sl ) ; glVertex2f ( x+sl , y+sl ) ; glVertex2f ( x+sl , y ) ; glEnd ( ) ; } glMatrixMode ( GL_PROJECTION ) ; glLoadIdentity ( ) ; // Resets any previous projecti...
Why is n't this a square ? LWJGL
Java
I 'm trying to make and android app with some dynamically drawn views . Currently , the only thing the views draw is a circle in the middle of the view.The views are inside a grid view , but it does n't seem to be drawing them right.This is what happens when I load the screen : The orange block is the view in the grid ...
public class ChooseTablePanel extends GamePanel { TableAdapter adapter ; public ChooseTablePanel ( Context context , GamePanel nextPanel , GamePanel failurePanel ) { super ( context , nextPanel , failurePanel ) ; initialize ( ) ; } public ChooseTablePanel ( Context context , AttributeSet attrs , GamePanel nextPanel , G...
Why are n't my views drawing ?
Java
I am writing a program in Java . The picture is self-explanatory -The main method spawns three threads . The SAX processor processes the input XML file , generates JAXB objects and puts them in guava cache . Guava cache is handled by another thread . Whenever any object comes into the cache , this thread notifies the t...
package test ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; public class MainClass { public static void main ( String args [ ] ) { ExecutorService xMLService = Executors.newFixedThreadPool ( 1 ) ; xMLService.execute ( new XMLProcessor ( ) ) ; ExecutorService cacheService = Execu...
How should I design this program ?
Java
To my understanding following program should print 0,0 as an output.However , when I run this program I am getting 1,0 as an output.Please help me understand what is going on here ?
public class Test1 { public static void main ( String [ ] args ) { System.out.println ( `` '' .split ( `` ; '' ) .length ) ; //1 System.out.println ( `` ; '' .split ( `` ; '' ) .length ) ; //0 } }
Peculiar behavior of split ( ) of string class
Java
Why works for and not I see them as the same since Integer is-a Number
Predicate < ? super Integer > isGreaterThanZero = num - > num.intValue ( ) > 0 ; isGreaterThanZero.test ( new Integer ( 2 ) ) ; Predicate < ? extends Number > isGreaterThanZero = num - > num.intValue ( ) > 0 ;
Why < ? extends Number > not working for Integer ?
Java
I 'm working on a project where many classes need proper typical implementations of equals and hashCode : each class has a set of final fields initialized at construction with `` deeply '' immutable objects ( nulls are intended to be accepted in some cases ) to be used for hashing and comparison.To reduce the amount of...
public abstract class AbstractHashable { /** List of fields used for comparison . */ private final Object [ ] fields ; /** Precomputed hash . */ private final int hash ; /** * Constructor to be invoked by subclasses . * @ param fields list of fields used for comparison between objects of this * class , they must be in ...
Reusable implementation of equals and hashCode
Java
Is there a java library that implements something that behaves like a ReadWriteLock but uses listeners or CompletableFuture/CompletionStage instead of blocking ? Ideally I 'd like to write : And also important : I 'm looking to know if something like this exists and if it does how is it called.I 'm not looking to imple...
lock = ... CompletionStage stage = lock.lockRead ( ) ; stage.thenAccept ( r - > { doSomething ( ) ; r.release ( ) ; } ) ; CompletionStage stage = lock.tryLockWrite ( 10 , TimeUnit.SECONDS ) ; stage.handle ( callback ) ;
Is there a read write lock with listeners for java ?
Java
I was teaching students the old-school Generics and came across an unseen ! behavior while I was presenting ! : ( I have a simple class This gives output as 10 , without any error ! ! ! I was expecting this to give me a ClassCastException , with some error like Integer can not be cast to HashMap.Curious and Furious , I...
public class ObjectUtility { public static void main ( String [ ] args ) { System.out.println ( castToType ( 10 , new HashMap < Integer , Integer > ( ) ) ) ; } private static < V , T > T castToType ( V value , T type ) { return ( T ) value ; } } System.out.println ( castToType ( 10 , new HashMap < Integer , Integer > (...
Ambiguous behaviour in casting
Java
Is there a pattern , or built in function I am missing or shall I just loop through like soIts because I need to persist the list to a database and retain the ordering .
public List < MyObject > convert ( List < String > myStrings ) { List < MyObject > myObjects = new ArrayList < MyObject > ( myStrings.size ( ) ) ; Integer i = 0 ; for ( String string : myStrings ) { MyObject myObject = new myObject ( i , string ) ; myObjects.add ( object ) ; i++ ; } return myObjects ; }
Convert a List < String > to a List < MyObject > , where MyObject contains an int representing the order
Java
I 'm trying to use the Bitemporal framework of Erwin Vervaet to store with Hibernate a temporal collection instead of a temporal property as in his example . ( there is a presentation of the framework here ) I 'm trying to store a collection of addresses which change over time , i.e . a Person can have multiple address...
java.lang.ClassCastException : com.ervacon.bitemporal.AddressSet can not be cast to java.util.Collection /* * ( c ) Copyright Ervacon 2016 . * All Rights Reserved . */package com.ervacon.bitemporal ; import java.io.Serializable ; import java.util.Collection ; import java.util.LinkedList ; public class Person implements...
Trying to store a temporal collection with Erwin Vervaet 's framework and getting ClassCastException
Java
Supposed I have two constraints ( c1 , c2 ) and I want to check whether they are syntactic identical : Option 1 : We could turn this into a satisfiability problem like this post : Whether two boolexpr are equalOption 2 : We could also turn them into strings and compare the equality : But both of those two options have ...
c1 : f ( x ) > 1 & & g ( y ) =2c2 : f ( x ) > 1 & & g ( y ) =2 if ( c1.toString ( ) .equals ( c2.toString ( ) ) ) ///do somthing
Checking syntactic equivalence of two constraints efficiently in Z3
Java
I 'd like to measure the execution time of a set of unit tests to be able to automatically monitor and compare performance when changes are made . Are there any suitable performance counters that can be reached easily from Java itself ? Ie , something like : with these additional requirements : gives the same answer in...
count1 = < call performance counter func > executeUnitTest ( ) ; count2 = < call performance counter func > testPerformance = count2 - count1 ;
exact way to measure performance on individual methods from inside Java ?
Java
I 'm playing with the RxJava retryWhen operator . Very little is found about it on the internet , the only one worthy of any mention being this . That too falls short of exploring the various use cases that I 'd like to understand . I also threw in asynchronous execution and retry with back-off to make it more realisti...
@ Slf4j @ Builderpublic class ChuckNorrisJokesService { @ Getter private final AtomicReference < Jokes > jokes = new AtomicReference < > ( new Jokes ( ) ) ; private final Scheduler scheduler ; private final ChuckNorrisJokesRepository jokesRepository ; private final CountDownLatch latch ; private final int numRetries ; ...
RxJava retryWhen bizarre behavior
Java
I have just read in Effective Java that the fifth principle of the equals ( ) method is that all objects must be unequal to null . The book goes on to say that some classes written by programmers guard against this using an explicit test for null : According to Effective Java , the above not null test is unnecessary . ...
public boolean equals ( Object o ) { if ( o == null ) return false ; ... }
Not-nullity requirement or principle
Java
To protect the question from `` duplicate hunters '' , I need to mention that I did not think that the solution I am looking for is filtering . I did my search , never encounter an answer mentioning filtering.I have a list of objects with a class like that : I want to collect this List into a map , groupingBy gender , ...
class Person { String gender ; String income ; String petName ; } Map < String , Long > mapping = people .stream ( ) .collect ( Collectors.groupingBy ( Person : :gender , Collectors.counting ( ) ) ;
Java Streams - Collecting to a Map With GroupingBy and Counting , But Count 0 If A Specific Field Is Null
Java
Here 's a tough nut to crack . I have a clash between using varargs and generics together . Following given code : I want the compareTo method to use more than one compare condition . If the strings are the same then use the ints instead . Usual situation I would say.I would love to create a static method to handle thi...
public class MyObject implements Comparable < MyObject > { private String name ; private int index ; @ Override public int compareTo ( MyObject o ) { if ( name.compareTo ( o.name ) ! = 0 ) return name.compareTo ( o.name ) ; return ( ( Integer ) index ) .compareTo ( o.index ) ; } } public int compareTo ( MyObject o ) { ...
Combining varargs and generics for chained comparisons in Java
Java
In my program , I repeatedly1 collect Java 8 streams to reduce a collection of objects to a single one . The size of this collection can vary a lot throughout the execution : from 3 objects to hundreds.In the process of optimizing my code and searching for bottlenecks , I made the stream parallel at some point . This w...
public void findInterestingFoo ( Stream < Foo > foos ) { internalState.update ( foos.collect ( customCollector ( ) ) ) ; } public void findInterestingFoo ( Stream < Foo > foos ) { if ( isSmall ( foos ) ) { internalState.update ( foos.collect ( customCollector ( ) ) ) ; } else { internalState.update ( foos.parallel ( ) ...
Find Stream size before performing other operations
Java
I got Parcelable encountered IOException writing serializable object and it caused by java.io.NotSerializableException : androidx.appcompat.widget.Toolbar error only in Android Version 10 devices.I 've searched many results for getting solutions to this problem but every solution I got , was telling to define implement...
java.lang.RuntimeException : Parcelable encountered IOException writing serializable object ( name = com.android.ui.fragment.CustomViewFragment ) at android.os.Parcel.writeSerializable ( Parcel.java:1850 ) at android.os.Parcel.writeValue ( Parcel.java:1797 ) at android.os.Parcel.writeArrayMapInternal ( Parcel.java:945 ...
AndroidX : Parcelable encountered IOException writing serializable object only in Android version 10 devices
Java
Suppose I have a text represented as a collection of lines of words . I want to join words in a line with a space , and join lines with a newline : This works fine , but I end up creating an intermediate String object for each line . Is there a nice concise way of doing the same without the overhead ?
class Word { String value ; } public static String toString ( List < List < Word > > lines ) { return lines.stream ( ) .map ( l - > l.stream ( ) .map ( w - > w.value ) .collect ( Collectors.joining ( `` `` ) ) ) .collect ( Collectors.joining ( `` \n '' ) ) ; }
Efficiently joining text in nested lists
Java
Given this situation : The method genericMethod ( ) in class Cat is definitely NOT overriding the superclass method ( and the compiler complains if I add @ Override signature ) which is reasonable , as the requirements to the type T are different.But I do not quite understand , how the compiler decides which of the two...
public class Animal { public < T > void genericMethod ( T t ) { System.out.println ( `` Inside generic method on animal with parameter `` + t.toString ( ) ) ; } } public class Cat extends Animal { public < T extends Cat > void genericMethod ( T t ) { System.out.println ( `` Inside generic method on cat with parameter `...
Generic method not overriding similar generic method in superclass - > Which one is used ?
Java
Possible Duplicate : Which constructor is chosen when passing null ? I recently came across this curiosity while coding a few days back and ca n't seem to figure out why the following happens : Given the class belowWhen the call new RandomObject ( null ) ; is made the output is always 2 regardless of the order in which...
public class RandomObject { public RandomObject ( Object o ) { System.out.println ( 1 ) ; } public RandomObject ( String [ ] s ) { System.out.println ( 2 ) ; } }
When sent to a constructor in Java , what does `` null '' value do ?
Java
I have a table in the following format : I want to generate some graph where each letter ( W , X , Y , Z ) is a node and have a link with some width according to the weight to the Item B.The question is what I can use to generate this graph ? Can be a tool , a Java or R library or another language . The way does n't ma...
Item A | Item B | Weight X | Y | 2 X | Z | 5 Y | Z | 3 Y | W | 2 ... | ... | ...
Generate a visual representation from a table with relation weight
Java
We 've got 2 pieces of code : And : What is the time complexity of them ? I think that the first one is : O ( logn ) , because it 's progressing to N with power of 2.So maybe it 's O ( log2n ) ? And the second one I believe is : O ( nlog2n ) , because it 's progressing with jumps of 2 , and also running on the outer lo...
int a = 3 ; while ( a < = n ) { a = a * a ; } public void foo ( int n , int m ) { int i = m ; while ( i > 100 ) i = i / 3 ; for ( int k = i ; k > = 0 ; k -- ) { for ( int j = 1 ; j < n ; j*=2 ) System.out.print ( k + `` \t '' + j ) ; System.out.println ( ) ; } }
Time complexity for two pieces of code
Java
This is just for general knowledge and I am pretty sure it may not be possible , but I am curious to know . Suppose I have a Student class object s1 and I pass it to a function as myFunc ( s1.toString ( ) ) . I have n't overrided toString ( ) function . When the parameter will reach to the function , can I reference ba...
public static void main ( ) { Student s1 ; myFunc ( s1.toString ( ) ) ; } public static myFunc ( String address ) { Student s2 ; s2 = //get s1 object from address string }
Getting an object from its address
Java
The above code works fine . However , if I add a method to Nested : I get a compilation error : This makes sense to me . The type of T gets erased at runtime , so Java ca n't apply an operator that 's only defined for certain classes like Integer . But why does a.val - b.val work ? Edit : Lots of good answers . Thanks ...
public class Test { public static class Nested < T > { public T val ; Nested ( T val ) { this.val = val ; } } public static void main ( String [ ] args ) { Nested < Integer > a = new Nested < Integer > ( 5 ) ; Nested < Integer > b = new Nested < Integer > ( 2 ) ; Integer diff = a.val - b.val ; } } T diff ( Nested < T >...
Why does Java 's type erasure not break this ?
Java
The challenge is to find a number whose individual digits multiplied by consecutively increasing power and added up , equal the initial number.Eg : take 89 , split it into 8 and 9 , then 8^1 + 9^2 = 89With an input of 1 and 100 ( the range ) , the output should be [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 89 ] , but I 'm g...
static List < Integer > sumDigPow ( int a , int b ) { List < Integer > eureka = new ArrayList < Integer > ( 0 ) ; List < String > digits = new ArrayList < String > ( ) ; String num ; int sum = 0 , multi ; for ( int i=a ; i < =b ; i++ ) { num = String.valueOf ( i ) ; digits.add ( num ) ; for ( int j=0 ; j < digits.size ...
Getting a wrong output using arraylists
Java
I 've found this code of pixel perfect collision checking and used it in my code : And it worked perfectly , no problems what so ever . That until I set the images into Config_Alpha_8 using this code ( because of ram problems ) : Why Nothing wont happen , it does go inside isCollisioDetected , I 've checked with logs !...
public boolean isCollisionDetected ( Bitmap bitmap1 , int x1 , int y1 , Bitmap bitmap2 , int x2 , int y2 ) { Rect bounds1 = new Rect ( x1 , y1 , x1 + bitmap1.getWidth ( ) , y1 + bitmap1.getHeight ( ) ) ; Rect bounds2 = new Rect ( x2 , y2 , x2 + bitmap2.getWidth ( ) , y2 + bitmap2.getHeight ( ) ) ; if ( Rect.intersects ...
Pixel perfect collision with Config.ALPHA_8
Java
I am trying to access the EXTRA_ADDRESS_BOOK_INDEX constant using JNI : The GetStaticObjectField method crashes with an error : java_vm_ext.cc:534 ] JNI DETECTED ERROR IN APPLICATION : static jfieldID 0x6fd191b0 not valid for class java.lang.Class < android.provider.ContactsContract $ Data > On the other hand if I try ...
JNIEXPORT jint JNICALL JNI_OnLoad ( JavaVM* vm , void* reserved ) { JNIEnv* env = nullptr ; vm- > GetEnv ( reinterpret_cast < void** > ( & env ) , JNI_VERSION_1_6 ) ; jclass clazz = env- > FindClass ( `` android/provider/ContactsContract $ Data '' ) ; jfieldID fieldID = env- > GetStaticFieldID ( clazz , `` EXTRA_ADDRES...
JNI error when trying to access the EXTRA_ADDRESS_BOOK_INDEX field
Java
The below code is a edited version of Dave Koelle 's AlphanumComparator . The edit contains code which sorts empty strings to the end of the list , or bottom of the JTable in my case . The problem is a java.lang.IllegalArgumentException : Comparison method violates its general contract ! occurs.To fix my problem I look...
import java.util.Comparator ; import javax.swing.JTable ; import javax.swing.SortOrder ; public class AlphanumComparator implements Comparator < String > { JTable table ; public AlphanumComparator ( JTable table ) { this.table = table ; } private final boolean isDigit ( char ch ) { return ch > = 48 & & ch < = 57 ; } pr...
Comparator breaching general contract