lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have a List < LedgerEntry > ledgerEntries and I need to calculate the sum of creditAmount and debitAmount.I have implemented this as , This looks like I 'm iterating over the List twice . Is there a way to get this done in one go without having to steam the list twice ?
class LedgerEntry { private BigDecimal creditAmount ; private BigDecimal debitAmount ; //getters and setters } BigDecimal creditTotal = ledgeredEntries.stream ( ) .map ( p - > p.getCreditAmount ( ) ) .reduce ( BigDecimal.ZERO , BigDecimal : :add ) ; BigDecimal debitTotal = ledgeredEntries.stream ( ) .map ( p - > p.getD...
Streams : Calculate the difference of totals in one go
Java
This code is from Effective Java ( Item 66 ) : ( without sync or volatile this never ends ) As Bloch mentioned in that chapter it will never write `` finished '' to the console . I 've been playing around with this class , and add that line to the runnable run method : With this the while loop does n't only increment i...
public class ThreadPractice { static boolean canrunstatic ; public static void main ( String [ ] args ) throws InterruptedException { Thread backgroundThread = new Thread ( new Runnable ( ) { public void run ( ) { int i = 0 ; while ( ! canrunstatic ) { i++ ; } System.out.println ( `` finished '' ) ; } } ) ; backgroundT...
Why do thread behave different with different run method body ?
Java
I have two classesSuppose I use an object of B [ say b ] in my code and after I end up using it , I set it to null . I know that the object of B is now available for garbage collection . I know that after setting b to null , it will be immediately eligible for garbage collection ? But what about the object of type A ? ...
Class A { //constructor } Class B { private A a ; public B ( ) { a = new A ( ) ; } }
Garbage collection of Composed Objects
Java
I have a list of objects . The object looks like this : I need to find the elements that have the same agendaCode , visitTypeCode and scheduledTime and for the life of me I ca n't get it done . I tried this : But it 's not doing what I thought it would . Ideally I would have a list of lists , where each sublist is a li...
public class Slots { String slotType ; Visits visit ; } public class Visits { private long visitCode ; private String agendaCode ; private String scheduledTime ; private String resourceType ; private String resourceDescription ; private String visitTypeCode ; ... } Set < String > agendas = slotsResponse.getContent ( ) ...
Filter objects from a list that have the same member
Java
I have written a web application using spring mvc 3 . It provides a single endpoint that returns JSON . I did having it running successfully using url paramters but now I need to change this to use path variables instead.I changed my controllerfrom : to : and my web xml to map the url ... from : to : But I get a 404 fo...
@ Controllerpublic class DataController { @ Autowired private IDataService dateService ; @ RequestMapping ( value = `` /some/data '' , method = RequestMethod.GET , produces = `` application/json '' ) public @ ResponseBody Data getDataByCode ( @ RequestParam String code ) { return versionService.getDataByCode ( code ) ;...
Spring MVC test - Injecting a mock repository when ever the integration test requires a specific type
Java
Someone postulated in some forum thread that many people and even experienced Java Developers would n't understand the following peace of Java Code.As a person with some interest in Java I gave it my thoughts and came to the following result.Eclipse tells me otherwise . The first line is true and the second is false.I ...
Integer i1 = 127 ; Integer i2 = 127 ; System.out.println ( i1++ == i2++ ) ; System.out.println ( i1 == i2 ) ; System.out.println ( i1++ == i2++ ) ; // True , since we first check for equality and increment both variables afterwards.System.out.println ( i1 == i2 ) ; // True again , since both variables are already incre...
Puzzling behaviour of == after postincrementation
Java
how to stick JLabel in GlassPane to rellative , floating coordinates from JProgressBar without using ComponentListener or another listener , is there built_in notifiers in Standard LayoutManagers that can notify about its internal state , and can be accesible for override , instead my attempt with ComponentListener and...
import java.awt.Container ; import java.awt.Dimension ; import java.awt.FlowLayout ; import java.awt.GridBagConstraints ; import java.awt.event.ComponentAdapter ; import java.awt.event.ComponentEvent ; import javax.swing.JButton ; import javax.swing.JCheckBox ; import javax.swing.JFrame ; import javax.swing.JLabel ; im...
Layout Manager and Positioning
Java
BackgroundI 've been running a code ( posted at the bottom ) to measure performance of explicit Java downcasting , and I 've run into what I feel like is a bit of an anomaly ... or perhaps two anomalies.I have already looked at this thread on Java casting overhead , but it seemed to only talk about casting in general ,...
iters | Test Round | Loop 1 | Loop 2 | Loop 3 -- -- -- -- -- -| -- -- -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- 50,000,000 | 1 | 3367 | 3166 | 3186 Test A | 2 | 3543 | 3158 | 3156 | 3 | 3365 | 3155 | 3169 -- -- -- -- -- -| -- -- -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- | -- -- -- -- -- 5...
Why does a String-casting loop seem to have a static overhead ?
Java
I am using Apache Ignite 1.8.0 for caching on a cluster . I am using the C++ API and am accessing the same cache from both Java and C++ . This works fine but I would like to also use affinity collocation to execute tasks on the same node that has cached the data . I am creating the cache in Java , putting the data in C...
final IgniteCache < Integer , ByteArray > cache = ignite.createCache ( `` myCacheBinaryCpp '' ) int8_t* byteArr= new int8_t [ 3 ] ; byteArr [ 0 ] = 0 ; byteArr [ 1 ] = 2 ; byteArr [ 2 ] = 2 ; cacheCppJ.Put ( i , ByteArray ( 3 , byteArr ) ) ; final Integer affKey = new Integer ( 9 ) ; ignite.compute ( ) .affinityRun ( `...
Ignite C++ and Cache Affinity
Java
I have a method to view a calendar in Java that calculates the date by year , day of the week and week-number.Now when I calculates the dates from 2017 everything works . But when I calculates the dates from January 2018 it takes the dates of year 2017.My code looks likeWhich results in 2018-01-02 and it should be 2018...
import java.time.temporal.IsoFields ; import java.time.temporal.ChronoField ; import java.time.LocalDate ; // ... ..LocalDate desiredDate = LocalDate.now ( ) .with ( IsoFields.WEEK_OF_WEEK_BASED_YEAR , 1 ) .with ( ChronoField.DAY_OF_WEEK , 1 ) .withYear ( 2018 ) ;
Unexpected date calculation result
Java
I 'm trying to sort an ArrayList of PostingsEntry objects according to the score attribute of the PostingsEntry objects . The list resides in a PostingsList object that has the sort ( ) method.I 'm trying to sort the list here : And I print the results : But I get : Which shows that the list has clearly not been sorted...
public class PostingsEntry implements Comparable < PostingsEntry > { public int docID ; public double score = 0 ; private TreeSet < Integer > positions = new TreeSet < Integer > ( ) ; /** * PostingsEntries are compared by their score ( only relevant * in ranked retrieval ) . * * The comparison is defined so that entrie...
Collections.sort ( ) leaves my list unsorted
Java
Many logging frameworks ( e.g. , log4j ) allow you to pass lambda expressions instead of Strings to the logging API . The argument is that if the string is particularly expressive to construct , the string construction can be lazily executed via the lambda expression . That way , the string is only constructed if the s...
void log ( int level , String message ) { if ( level > = System.logLevel ) System.out.println ( message ) ; } // ... .System.logLevel = Level.CRITICAL ; log ( Level.FINE , `` Very expensive string to construct ... '' + etc ) ; void log ( int level , Supplier < String > message ) { if ( level > = System.logLevel ) Syste...
Why bother using lambda expressions in logging APIs if the compiler can possibly inline the logging call
Java
The following code come from java.lang.System.console ( ) method : In my opinion , these is a bug in this method . We should write it like this : Am I right ? What 's your opinion ?
private static volatile Console cons = null ; /** * Returns the unique { @ link java.io.Console Console } object associated * with the current Java virtual machine , if any . * * @ return The system console , if any , otherwise < tt > null < /tt > . * * @ since 1.6 */ public static Console console ( ) { if ( cons == nu...
Possible JDK bug in System.console ( )
Java
I am confused about sharing arrays safely between threads in Java , specifically memory fences and the keyword synchronized.This Q & A is helpful , but does not answer all of my questions : Java arrays : synchronized + Atomic* , or synchronized suffices ? What follows is sample code to demonstrate the issue . Assume th...
public final class SharedTable { // Column-oriented data entries private final String [ ] data1Arr ; private final int [ ] data2Arr ; private final long [ ] data3Arr ; private final AtomicInteger nextIndex ; public SharedTable ( int size ) { this.data1Arr = new String [ size ] ; this.data2Arr = new int [ size ] ; this....
Does a synchronized block trigger a full memory fence for arrays ?
Java
I am using Java to create an app for Google Assistant that will call an external REST API and return certain responses based on trigger phrases.I currently can use the Default Welcome Intent to return simple text responses through the Actions on Google simulator . However , when I try to call an external REST API and s...
@ ForIntent ( `` process-greeting '' ) public ActionResponse greetingProcessor ( ActionRequest request ) { LOGGER.info ( `` Trying to process greeting intent '' ) ; ResponseBuilder responseBuilder = getResponseBuilder ( request ) ; String givenName = ( String ) request.getParameter ( `` given-name '' ) ; if ( givenName...
How to process a request to an external REST service and return the response to Google Assistant ?
Java
Suppose there is a List < Object > and that Object contains two methods : getUserId and getPoints . Consider that List < Object > contains three objects , and they contain the following data : After collecting this properly , I am expecting to have a Map < String , Integer > that would look like this : I am attempting ...
userId A ; 3 pointsuserId A ; 5 pointsuserId B ; 1 point A : 8 , B : 1 this.service.getListObject ( ) .stream ( ) .collect ( Collectors.toMap ( Object : :getUserId , Object : :getPoints ) ) ; A : 5 , B : 1
Using Java 8 Streams ' Collectors to increment value based of existing key/value pair
Java
While working on a use case where the data needs to be sorted on UUID which are all Type 1 or timebased and generated using Datastax Cassandra Java driver library ( UUIDS.timebased ( ) ) , i found that UUID.compareTo is not sorting some of the UUIDs correctly.The logic in compareTo is I had the below 2 UUIDs generated ...
/** * Compares this UUID with the specified UUID . * * < p > The first of two UUIDs is greater than the second if the most * significant field in which the UUIDs differ is greater for the first * UUID . * * @ param val * { @ code UUID } to which this { @ code UUID } is to be compared * * @ return -1 , 0 or 1 as this { ...
Java UUID compareTo not working correctly for Type1 UUIDs
Java
I have a few Map objects that are keyed by the same type K with differently typed values V1 ... VN , which for the purpose of this question do not share a supertype* : I need to create a resulting map of type Map < K , V > , by filtering each of these maps differently , and then use a 'value mapper ' to map the V1 ... ...
Map < K , V1 > kv1Map < K , V2 > kv2Map < K , V3 > kv3 ... Map < K , VN > kvN public static < K , VN , V > Map < K , V > filterAndMapValue ( final Map < K , VN > map , final Predicate < ? super Entry < K , VN > > predicate , final Function < ? super Entry < K , VN > , ? extends V > mapper ) { return map.entrySet ( ) .s...
How to efficiently filter and collect to a resulting map with differently derived map values from a few maps ?
Java
Came accross this today and spent ages trying to reproduce/figure out what was happening . Can somebody explain why this happens or is this a bug with type erasure/default methods/lambda's/polymorphism ? Uncommenting the default method makes it run fine , but I would have expected this to work as isOutput : Code
Works fine with an objectCalling consumeHelloCalling accept with contextHelloCalling accept via consumer ... Exception in thread `` main '' java.lang.AbstractMethodError : Method test/LambdaTest $ $ Lambda $ 1.accept ( Ljava/lang/Object ; ) V is abstract at test.LambdaTest $ $ Lambda $ 1/834600351.accept ( Unknown Sour...
Lambda/default methods/type erasure quirk/bug using ECJ ?
Java
In the above statement , can I use an int array in place of the String array ? What happens if I do n't put anything in the parenthesis , i.e if I use an empty parenthesis ?
public static void main ( String arg [ ] )
java basic question
Java
Recently I ` ve migrated GCM to FCM and after some struggle , I 've managed to make everything work with the help of this great community.Now when I tested notifications on older version of Android ( Nougat ) it does n't work , app just crash , I 've found out that its something related to versions as older ones does n...
public class MessagingService extends FirebaseMessagingService { private static final String TAG = `` FCM Message '' ; public MessagingService ( ) { super ( ) ; } @ TargetApi ( Build.VERSION_CODES.O ) @ RequiresApi ( api = Build.VERSION_CODES.JELLY_BEAN ) @ Overridepublic void onMessageReceived ( RemoteMessage remoteMe...
Firebase Messaging Service Not Working On Older Android
Java
The code compiles fine with JDK 8 ( 1.8.0_212 ) but fails to compile using JDK 11 ( 11.0.3 ) both Oracle jdk and open jdk ( aws corretto ) Tried compiling using javac and with Maven ( maven version 3.6.1 and maven-compiler-plugin version 3.8.0 ) it compiles for JDK 8 and fails for JDK 11.Error :
import java.net.URL ; import java.util.List ; import java.util.ArrayList ; import java.util.Arrays ; import java.util.function.Function ; import java.util.stream.Stream ; public class AppDemo { public static void main ( String [ ] args ) { // NO error here giveMeStream ( `` http : //foo.com '' ) .map ( wrap ( url - > n...
Compilation fails for JDK 11 and compiles fine for JDK 8
Java
I am leaning to program in Scala and came across this problem where Scala code throws StackOverflowErorr while similar implementation in Java can go a bit more before throwing the same errorThe error i get isThe java code is Why does n't Scala 's tail recursion optimization help ? How come Java can handle ( Java could ...
def recursiveSum ( args : Int* ) : Int = { if ( args.length == 0 ) 0 else args.head + recursiveSum ( args.tail : _* ) } recursiveSum ( 5000 to 15000 : _* ) java.lang.StackOverflowError//| at scala.collection.Parallelizable $ class. $ init $ ( Parallelizable.scala:20 ) //| at scala.collection.AbstractTraversable. < init...
Scala StackOverflowError while Java can handle it
Java
I 'm currently trying to splice a string into a multi-line string.The regex should select white-spaces which has 13 characters before.The problem is that the 13 character count does not reset after the previous selected white-space . So , after the first 13 characters , the regex selects every white-space.I 'm using th...
( ? < = . { 13 } ) import java.util.ArrayList ; public class HelloWorld { public static void main ( String [ ] args ) { String str = `` This is a test . The app should break this string in substring on whitespaces after 13 characters '' ; for ( String string : str.split ( `` ( ? < = . { 13 } ) `` ) ) { System.out.print...
Splitting a string on whitespaces
Java
I 'm benchmarking some of our code on an OPO device that 's normally pretty fast and I 'm seeing a lot of `` weird '' performance oddities . Before digging deeper into the Android native code I thought I 'd ask here.What I 'm seeing is that a call for paint.setColor ( argbInt ) takes roughly 5 times longer to execute t...
paint.setStyle ( Paint.Style.FILL ) ; paint.setAntiAlias ( false ) ; canvas.drawRect ( x , y , x + w , y + h , paint ) ; paint.setAntiAlias ( antialias ) ;
Why is setColor so slow on Android
Java
I am trying to read some Java code from a tutorial , I do n't understand the line : I do n't understand what the ... represents if it was just ( Integer zips ) I would understand that there is a variable of class Integer called zips . But the ... are confusing me .
public Weatherman ( Integer ... zips ) {
What does `` public Weatherman ( Integer ... zips ) { `` mean in java
Java
What to do if classes with same interface having similar but different method signature ? Let 's say I have a project to calculate different costs ( to get a total cost at last ) .In my program , there is several calculator classes , namely ACostCalculator , BCostCalculator and so on . When a calculate ( ) method is in...
//getResource ( ) are costly method while several costs need this . So do it outside calculate ( ) method.ResourceA resourceA = getResourceA ( ) ; ResourceB resourceB = getResourceB ( ) ; CostContainer costContainer = new CostContainer ( ) ; CostCalculator aCostCalculator = new ACostCalculator ( ) ; ... CostCalculator ...
What to do if classes with same interface having similar but different method signature ?
Java
I got a Map , which may contain one of the following KeysI now want to check if one of some Keys are set . My current approach is to chain multiple map.getOrDefault ( ... ) or check for each key if it exists in the map.Is there any way to make this easier/better to read ? Unfortunately the map is given as such .
Map < String , String > map = getMap ( ) ; Address address = new Address ( ) ; address.setStreet ( map.getOrDefault ( `` STORE_STREET '' , map.getOrDefault ( `` OFFICE_STREET '' , ... ) ) ; if ( map.containsKey ( `` STORE_STREET '' ) ) { address.setStreet ( map.get ( `` STORE_STREET '' ) ) ; } else if ( map.containsKey...
Java : one of many keys map
Java
Suppose I have this : Then in my code , I can safely cast without a warning like this : which is fine . But if the derived class has more type parameters , it does n't work any more : Why is that ? Is there something obvious I 'm missing here ?
class Base < T > { } class Derived < T > extends Base < T > { } public < T > void foo ( Base < T > base ) { Derived < T > f = ( Derived < T > ) base ; // fine , no warning } class Base < T > { } class Derived < T , U > extends Base < T > { } public < T > void foo ( Base < T > base ) { Derived < T , ? > f = ( Derived < ...
Casting to generic subtypes of a generic class
Java
Is there any value that could be assigned to the myString variable that would result in an infinite loop in the code below ?
while ( true ) { if ( myString.indexOf ( `` `` ) == -1 ) { break ; } myString = myString.replaceAll ( `` `` , `` `` ) ; }
Could this code potentially result in an infinite loop ?
Java
When trying to inject a class which is in the java.lang namespace via java.lang.instrument.Instrumentation # appendToBootstrapClassLoaderSearch on a OpenJDK 11 , nothing happens and no error is thrown . When placing the class to inject into a different package , it works as expected.The reason I want to do this is to o...
JarFile jar = new JarFile ( new File ( `` file/to/bootstrap.jar ) ) ; instrumentation.appendToBootstrapClassLoaderSearch ( jar ) ; // throws ClassNotFoundException java/lang/DispatcherClass.forName ( `` java.lang.Dispatcher '' , false , null ) ; bootstrap.jar └─ java/lang/Dispatcher.class
How to inject a class into the java.lang package
Java
In order to get the exact sum of a long [ ] I 'm using the following snippet.It works fine by processing the numbers split in two halves and finally combining the partial sums . Surprisingly , this method works too : I do n't believe that the fastestSum should work as is . I believe that it can work , but that somethin...
public static BigInteger sum ( long [ ] a ) { long low = 0 ; long high = 0 ; for ( final long x : a ) { low += ( x & 0xFFFF_FFFFL ) ; high += ( x > > 32 ) ; } return BigInteger.valueOf ( high ) .shiftLeft ( 32 ) .add ( BigInteger.valueOf ( low ) ) ; } public static BigInteger fastestSum ( long [ ] a ) { long low = 0 ; ...
Exact sum of a long array
Java
I need a WHERE clause to check tuples IN a list : ( field1 , field2 ) in ( ( ' 1 ' , 1 ) , ( ' 2 ' , 2 ) , ( ' 3 ' , 3 ) ) . This is valid SQL in Postgres.Dialect : POSTGRESjOOQ Version : 3.9.6What is the correct jOOQ syntax for this case ? jOOQ 3.9 documentation implies this is possible , but their example only gives ...
Collection < Row2 < String , Integer > > referenceOrderIdLineNumbers = ... List < Object [ ] > rows = dsl.select ( ... , field ( `` count ( TABLE3 ) '' , Integer.class ) .from ( Tables.TABLE1 ) .join ( Tables.TABLE2 ) .on ( Tables.TABLE2.PK1.eq ( Tables.TABLE1.PK1 ) ) .join ( Tables.TABLE3 ) .on ( Tables.TABLE3.PK2.eq ...
jOOQ `` IN '' Predicate with Degree N Tuples
Java
sorry if this is extremely obvious or has been answered elsewhere . I have n't been able to find anything . I have the following code : I create two instances of this SimpleThread class , and execute the run methods . I would expect to see something like : Thread 9 incrementing ... Thread 9 sleeping ... ( after 5 secon...
public class SimpleThread extends Thread { public static Integer sharedVal = 0 ; public SimpleThread ( ) { } @ Override public void run ( ) { while ( true ) { iterator ( ) ; } } public void theSleeper ( ) { System.out.println ( `` Thread : `` + this.getId ( ) + `` is going to sleep ! `` ) ; try { this.sleep ( 5000 ) ; ...
Java synchronized confusion
Java
OUTPUT : BWhy does virtual machine call this method f ( null ) { System.out.println ( `` B '' ) ; } ? Why not f ( null ) { System.out.println ( `` A '' ) ; }
public class Test { public static class A { } public static class B extends A { } public void f ( A a ) { System.out.println ( `` A '' ) ; } public void f ( B a ) { System.out.println ( `` B '' ) ; } public static void main ( String [ ] args ) { new Test ( ) .f ( null ) ; } }
Passing null to the overridden method when the difference between methods is the parameter subtype
Java
Discussions of finalizable objects in Java typically discuss the common indirect costs that happen when finalizable objects ( and their associated resources ) can not be quickly garbage collected.I 'm more interested , at the moment , in what the actual direct cost of being finalizable is , both in memory terms , and i...
public void finalize ( ) { Pool.release ( getPropertyId ( ) ) ; }
What is the up-front cost of an object being finalizable ?
Java
I 'd like to pass a String parameter as `` null '' However , this is for the super method in a constructor - so i can not doI can not just doas this will result in an ambiguous method call . I do n't want to have an instance variable that is null for this either , that seems inelegant.Is there a way to create a null St...
String s = null ; super ( s ) ; super ( null ) new String ( null ) //does not compile
java Can i create a string that is defined as null in one line ?
Java
The following simple Java program appears to display the string Hello World through the statement System.out.println ( `` Hello World '' ) ; but it does n't . It simply replaces this with another string which is in this case , Good Day ! ! and displays it on the console . The string Hello World is not displayed at all ...
package goodday ; import java.lang.reflect.Field ; final public class Main { public static void main ( String [ ] args ) { System.out.println ( `` Hello World '' ) ; } static { try { Field value = String.class.getDeclaredField ( `` value '' ) ; value.setAccessible ( true ) ; value.set ( `` Hello World '' , value.get ( ...
A simple Java code that works well but functions in a way that is somewhat difficult to follow
Java
Consider the following toy method : And the following client code : Do now both calls involve autoboxing , or only the latter , even though Float testReturnFloat ( ) has been used as method signature ? Small note : This question is only for theoretical analysis , I encountered it as I almost put this into production co...
public Float testReturnFloat ( ) { return 2f ; } float resultOne = testReturnFloat ( ) ; Float resultTwo = testReturnFloat ( ) ;
When does autoboxing take place exactly ?
Java
A compiler that must translate a generic type or method ( in any language , not just Java ) has in principle two choices : Code specialization . The compiler generates a new representation for every instantiation of a generic type or method . For instance , the compiler would generate code for a list of integers and ad...
public class Test { public static void main ( String [ ] args ) { Test t = new Test ( ) ; String [ ] newArray = t.toArray ( new String [ 4 ] ) ; } @ SuppressWarnings ( `` unchecked '' ) public < T > T [ ] toArray ( T [ ] a ) { //5 as static size for the sample ... return ( T [ ] ) Arrays.copyOf ( a , 5 , a.getClass ( )...
Useless expectation from compiler when dealing with generics ?
Java
As far as I understand , variable evaluation is done at run time . However , type evaluation is done at compile time in Java.Also as I see , making a variable constant ( I am using local variables but it changes nothing about the concept above ) , will make its value known at compile time.I provide you two examples to ...
// Working examplefinal int x = 10 ; short y = x ; // Non-working examplefinal long a = 10L ; int b = a ;
Why ca n't I assign a final long to an int ?
Java
I have a stream < A > , where I would like to get a map < String , list < A > > , where the original stream is partitioned into sublists based on the value of category ( ) . It is pretty trivial to have it implemented using a for loop , but is it possible to get a more elegant solution harnessing java streams ? EXAMPLE...
class A { String category ( ) ; // ... } a - > { [ a , xyz ] , [ a , zyx ] } b - > { [ b , abc ] }
Partition java streams in categories
Java
During my studies to the OCPJP8 I 've encountered one question which does n't have very clear answer to me . Consider following code : According to the book correct answer for a question `` Which exception will the code throw ? '' is `` Runtime exception c with no suppressed exception '' .I have check this code in Ecli...
public class Animals { class Lamb implements Closeable { public void close ( ) { throw new RuntimeException ( `` a '' ) ; } } public static void main ( String [ ] args ) { new Animals ( ) .run ( ) ; } public void run ( ) { try ( Lamb l = new Lamb ( ) ; ) { throw new IOException ( ) ; } catch ( Exception e ) { throw new...
Throw runtime exception in Closable.close ( )
Java
This code acts as expected printing `` Average Number of Runs : 0.99864197 '' This code that should print the same exact number , but instead it prints a random negative number.Is there some optimization that happens in java for loops ? Notes : I 'm using jdk1.6.0_45.In normal usage the new Random would have a better s...
import java.util.Random ; public class A { public static void main ( String [ ] args ) { int min = -30 ; int max = 1 ; test ( min , max ) ; } static void test ( int min , int max ) { int count = 0 ; Random rand = new Random ( 0 ) ; for ( int j = 0 ; j < 2097152 ; j++ ) { int number = min + rand.nextInt ( max-min+1 ) ; ...
Near empty Java For-Loop acts strange
Java
Consider the following example where we are sorting people based on their last name : Now , let 's assume that getLastName returns an optional : Obviously persons.sort ( Comparator.comparing ( Person : :getLastName ) ) ; will not compile since Optional ( the type getLastName returns ) is not a comparable . However , th...
public class ComparatorsExample { public static class Person { private String lastName ; public Person ( String lastName ) { this.lastName = lastName ; } public String getLastName ( ) { return lastName ; } @ Override public String toString ( ) { return `` Person : `` + lastName ; } } public static void main ( String [ ...
Comparator for Optional < T > with key extractor , like java.util.Comparator.comparing
Java
I 'm try to convert a list to a map using the Collectors.toMap call . The list consists of ActivityReconcile objects . I want to pass an instance for every entry in the list into the toMap call.The code is below and where I need the instances is denoted by ? ? .
final List < ActivityReconcile > activePostedList = loader.loadActivePosted ( accessToken ) ; Map < AccountTransactionKey , ActivityReconcile > postedActiveMap = activePostedList.stream ( ) .collect ( Collectors.toMap ( AccountTransactionKey.createNewAccountTransactionKeyFromActivityReconcileRecord ( ? ? ) , ? ? ) ) ;
java 8 change list to map using instance of list
Java
I 'm attempting to consolidate multiple unnecessary web requests into a map , with the key connected to a location 's ID , and the value being a list of products at that location.The idea is to reduce the amount of requests to my flask server by creating a single request for each location , with a list of required prod...
public class Product { public Integer productNumber ( ) ; public Integer locationNumber ( ) ; } List < Product > products = ... ( imagine many products in this list ) Map < Integer , List < Integer > > results = products.stream ( ) .collect ( Collectors.toMap ( p - > p.locationNumber , p - > Arrays.asList ( p.productNu...
Appending to a list within a stream to a map
Java
I was just wondering why we do n't use camelcase notation ( instanceOf ) instead of how it is ( instanceof ) .
Foo bar = new Foo ( ) ; if ( bar instanceof Foo ) { ... // it 's true }
Why does n't the instanceof operator use camelcase notation ?
Java
I made a topic some hours ago that lead me to a public repository : https : //github.com/biezhi/webp-ioHowever , I had to update the library used , cwebp and make changes to the code.Its my first fork.My fork is located here : https : //github.com/KenobySky/webp-ioQuestion : Im trying to declare this 'fork ' git reposi...
maven { url `` https : //jitpack.io '' } ... compile 'com.github.KenobySky : webp-io : master ' Execution failed for task ' : compileJava'. > Could not resolve all files for configuration ' : compileClasspath ' . > Could not find com.github.KenobySky : webp-io : master . Searched in the following locations : - https : ...
'Fork ' git repository as dependency in gradle
Java
I am writing a program to calculate the decimal expansion on the number 103993/33102 and I want to print out all of the trailing decimals depending on what number the user inputs . It runs quickly for all number up to 10^5 but if input 10^6 to program takes around 5 minutes to print out an answer . How can I speed thin...
public static void main ( String [ ] args ) throws NumberFormatException , IOException { // BigDecimal num1 = new BigDecimal ( 103993 ) ; // BigDecimal num2 = new BigDecimal ( 33102 ) ; String repNum = `` 415926530119026040722614947737296840070086399613316 '' ; // pw.println ( num.toString ( ) ) ; String sNum = `` 3.1 ...
Decimal expansion program running very slow for large inputs
Java
I have the following scenario , simplified : Where -- - > means `` depends on '' .ProjectB is really simple . It does n't declare any dependenci . In fact , the only relevant part is this : In pom.xml of projectA I have declared the dependency to projectB : And in pom.xml of projectX I have : The problem is that projec...
projectX -- - > projectA -- - > projectB < packaging > jar < /packaging > < packaging > jar < /packaging > < dependencies > < dependency > < groupId > com.mycompany < /groupId > < artifactId > projectB < /artifactId > < version > 1.0.0 < /version > < scope > provided < /scope > < /dependency > < /dependencies > < packa...
How can I use dependencies of a project that 's been marked as provided ?
Java
I want to determine if a string is the name of a month and I want to do it relatively quickly . The function that is currently stuck in my brain is something like : However , I will be processing lots of text , passed one string at a time to this function , and most of the time I will be getting the worst case of going...
boolean isaMonth ( String str ) { String [ ] months = DateFormatSymbols.getInstance ( ) .getMonths ( ) ; String [ ] shortMonths = DateFormatSymbols.getInstance ( ) .getShortMonths ( ) ; int i ; for ( i = 0 ; i < months.length ( ) ; ++i ; ) { if ( months [ i ] .equals ( str ) ) return true ; if ( shortMonths [ i ] .equa...
Is there a faster method to match an arbitrary String to month name in Java
Java
Our project is developed using Eclipse OSGi , but provides also normal JARs via jardesc files for export . The project uses the ASM library and a javaagent in order to exchange invokevirtual with invokedynamic calls.This worked well in Java 7 and 8 . Now , we upgraded to Java 9 and ported our implementation to use jdk....
java -- version ` java 9.0.4Java ( TM ) SE Runtime Environment ( build 9.0.4+11 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 9.0.4+11 , mixed mode ) JVM_ARGS= '' -d64 -Xms1024m -Xmx4048m -ea '' MODULES= '' -- add-reads jdk.dynalink=ALL-UNNAMED -- add-reads java.base=ALL-UNNAMED '' $ { JAVA_HOME } bin/java $ MODULES \...
jdk.dynalink not visible from bootclasspath in Java 9
Java
How to prevent loading the value that is not present in the cache many times simultanously , in the efficient way ? A typical cache usage is the following pseudocode : The problem : before the value is loaded from service ( Database , WebService , RemoteEJB or anything else ) a second call may be made in the same time ...
Object get ( Object key ) { Object value = cache.get ( key ) ; if ( value == null ) { value = loadFromService ( key ) ; cache.set ( key , value ) ; } return value ; }
How to prevent loading non-cached value simultanously many times ?
Java
I 'm currently learning to program in Java , and I have a question about the unary incrementers listed in the title I have n't been able to find elsewhere . I just started playing around with them , and could n't quite decide which one to use in a for loop because it seems the difference in behaviors between prefix ( i...
public class PlusPlus { public static void main ( String [ ] args ) { long startTime1 , startTime2 , endTime1 , endTime2 ; final double COUNT = 100000000 ; //times x++ incrementing startTime1 = System.currentTimeMillis ( ) ; for ( int x = 0 ; x < COUNT ; x++ ) ; endTime1 = System.currentTimeMillis ( ) ; System.out.prin...
Unary incrementers ++x and x++ in Java
Java
I wonder why this is a valid override : Whereas this is not : According to JLS §8.4.8.1 , B.getSupplier must be a subsignature A.getSupplier : An instance method mC declared in or inherited by class C , overrides from C another method mA declared in class A , iff all of the following are true : ... The signature of mC ...
public abstract class A { public abstract < X > Supplier < X > getSupplier ( ) ; public static class B extends A { @ Override public Supplier < String > getSupplier ( ) { return String : :new ; } } } public abstract class A { public abstract < X > Supplier < X > getSuppliers ( Collection < String > strings ) ; public s...
Overriding a method with a generic return type fails after adding a parameter
Java
Is monadic programming in Java 8 slower ? Below is my test ( a right-biased Either is used that creates new instances for each computation ) . The imperative version is 1000 times faster . How do I program monadicaly in Java8 while getting comparable performance ? Main.javaEither.java
public class Main { public static void main ( String args [ ] ) { Main m = new Main ( ) ; m.work ( ) ; m.work2 ( ) ; } public void work ( ) { final long start = System.nanoTime ( ) ; final Either < Throwable , Integer > result = Try ( this : :getInput ) .flatMap ( ( s ) - > Try ( this : :getInput ) .flatMap ( ( s2 ) - ...
How do I program monadicaly in Java8 while getting comparable performance ?
Java
When running `` gradle build '' I got the following error with one of our projects , couple of the classes get the following compile error : Even though , the method setFirstResult takes a long as parameter . Here is the code : I have tried -- refresh-dependencies and cleared out cache etc . None of those worked for me...
can not be applied to given types ; this._logFilter.setFirstResult ( firstResult ) ; ^ required : int found : long reason : actual argument long can not be converted to int by method invocation conversion public void setFirstResult ( long firstResult ) { this._firstResult = firstResult ; } public class GlobalMessageLog...
Gradle complains it ca n't convert long to int even while the method takes long as parameter
Java
If I have the following two classes : andI then compile them with javac Base.java Derived.java and then use javap -v Derived . If I use Java 7 , I getIf I do the same thing with Java 8 , I instead get The thing to note here is that there is an annotation visible on the void method ( java.lang.Object ) stub in the Java ...
// Base.javapublic abstract class Base < T > { abstract void method ( T t ) ; } // Derived.javapublic class Derived extends Base < Number > { @ Deprecated void method ( Number n ) { } } public class Derived extends Base < java.lang.Number > Signature : # 17 // LBase < Ljava/lang/Number ; > ; SourceFile : `` Derived.jav...
Why does Java 8 apply annotations differently to derived classes ?
Java
I 've met a such kind of code and comments in the java.util.ImmutableCollections class : Why not just throw new IndexOutOfBoundsException ( ... ) ? What 's the reason ?
static final class List0 < E > extends AbstractImmutableList < E > { ... @ Override public E get ( int index ) { Objects.checkIndex ( index , 0 ) ; // always throws IndexOutOfBoundsException return null ; // but the compiler does n't know this } ... }
`` but the compiler does n't know this '' - what 's the sense ?
Java
I 'm trying to allocate a large matrix ( around 10GB ) . I 'm working on 64 bit machine with a 64 bit JVM . My process then should have 2^64 bytes available and I 've set the JVM heap size to be 128G ( I have 16GB of RAM in my machine if that matters ) . My understanding was that I should get the memory from the OS and...
Jama.Matrix A = new Matrix ( num_words , num_documents ) ; -Xms40m-Xmx128g-d64
Why do I get heap outOfMemory exception ?
Java
in most IDEs and editors there 's no consensus as to how to ident the @ Override . and it 's not covered in the coding style for java http : //www.oracle.com/technetwork/java/codeconvtoc-136057.htmli use exclusively vim and it creates a new indentation level . So i 'm inclined to think that the correct isBut every docu...
@ Override public boolean onTouch ( View v , MotionEvent event ) { @ Overridepublic boolean onTouch ( View v , MotionEvent event ) { @ Override public boolean onTouch ( View v , MotionEvent event ) {
Where to type @ Override ?
Java
Strangely , it outputs 25.0 instead of 25Whats going on ?
Object myObject = true ? new Integer ( 25 ) : new Double ( 25.0 ) ; System.out.println ( myObject ) ;
Why is the result of conditional operator opposite of expected ?
Java
suppose i have two functions , boolean fA ( ) and boolean fB ( ) if i write another function function ( boolean b ) and I call function ( fA ( ) ||fB ( ) ) then fB ( ) might not be executed , if fA ( ) returns true.I like this feature , but here I need both functions to execute . Obvious implementation : is ugly , and ...
boolean temp = fA ( ) ; function ( fB ( ) ||temp ) ;
How to preventing short-circuiting ?
Java
I get a StackOverflowException on this Java method : I 'm playing with tail call recursion so I guess this is what happens when the JVM does n't short circuit the stack right ?
private static final Integer [ ] populate ( final Integer [ ] array , final int length , final int current ) { if ( current == length ) { return array ; } else { array [ current ] = TR.random.nextInt ( ) ; System.out.println ( array [ current ] ) ; return populate ( array , length , current + 1 ) ; } }
I get a StackOverFlowException on this code because my JVM does n't support tail call optimizaion , right ?
Java
There is a C++ function , which is called from Java code via JNI.I want to pass the underlying c-string to the Java correctly , so I have done below arrangements : But in this case , the function data ( ) is no longer thread-safe.What is the best way to achieve the thread-safety while passing the string without causing...
// main.cppstring global ; const char* data ( ) // Called externally by JNI { return ( global = func_returning_string ( ) ) .data ( ) ; // ` .data ( ) ` = ` .c_str ( ) ` }
How to pass a C++ string to Java JNI in a well defined thread-safe way ?
Java
I was fiddling around making infinite loops to test some other code/my understanding , and came across this strange behaviour . In the program below , counting from 0 to 2^24 takes < 100ms on my machine , but counting to 2^25 takes orders of magnitude more time ( at time of writing , it 's still executing ) .Why is thi...
public class TestClass { public static void main ( String [ ] args ) { addFloats ( ( float ) Math.pow ( 2.0 , 24.0 ) ) ; addFloats ( ( float ) Math.pow ( 2.0 , 25.0 ) ) ; } private static void addFloats ( float number ) { float f = 0.0f ; long startTime = System.currentTimeMillis ( ) ; while ( true ) { f += 1.0f ; if (...
Why does counting to 2^24 execute quickly , but counting to 2^25 take much longer ?
Java
// Desired output : : newCode = `` helloworld '' ; But this is not replacing i++ with blank .
String preCode = `` helloi++ ; world '' ; String newCode = preCode.replaceAll ( `` i++ ; '' , `` '' ) ;
String replaceAll not replacing i++ ;
Java
I 'm testing the results of a query . The table where the results are stored has a structure like this : And the query receives parameters in order to do the search based on Date and Hour columns like this : For example , if I use the following values : dateFrom : '2015-01-01'hourFrom : 700dateTo : '2015-01-03'hourTo :...
Id SomeValue Date Hour -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -1 foo1 2015-01-01 7002 foo2 2015-01-01 8003 foo3 2015-01-01 900 ... 18 foo18 2015-01-01 240019 bar1 2015-01-02 10020 bar2 2015-01-02 200 ... 41 bar23 2015-01-02 230042 bar24 2015-01-02 240043 baz1 2015-01-03 10044 baz2 2015-01-03 200 ( and on .....
Is it ok to sort a List in the body of the test case to check for boundary data ?
Java
I want to have smooth text in my game . I found that solution is pixel shader , so i do every thing like is described on github documentation . I 've got font.vert and font.frag files and in this documentation is said that i should use const float smoothing = 0.25f / ( spread * scale ) . My font is 48 px size thus i us...
# ifdef GL_ESprecision mediump float ; # endifuniform sampler2D u_texture ; varying vec4 v_color ; varying vec2 v_texCoord ; const float smoothing = 0.25/48.0 ; void main ( ) { float distance = texture2D ( u_texture , v_texCoord ) .a ; float alpha = smoothstep ( 0.5 - smoothing , 0.5 + smoothing , distance ) ; gl_FragC...
How use pixel shader to achive smooth text ?
Java
I 'm trying to understand how Java handles cases of ambiguity that come out when a concrete class inherits ( abstract or concrete ) methods having the same name from different classes/interfaces . I 've not been able to find a general rule , this is why I decided , once for all , to spend some time on this by using a p...
+ -- -- -- -- -- -- -- -- -- -- -- -- -+ | INTERFACE | + -- -- -- -- -- + -- -- -- -- -- -- -- | | abstract | non-abstract | | method | method |+ -- -- -- -- -- -+ -- -- -- -- -- -- -- + -- -- -- -- -- + -- -- -- -- -- -- -- +| | abstract | | || ABSTRACT | method | 1a | 2a || + -- -- -- -- -- -- -- + -- -- -- -- -- + -...
What are the rules to handle homonym inherited methods ?
Java
I was wondering that what is the best/appropriate way to release file resources/handles.Traditional code , } Will the file handle be released by closing BufferredInputStream.close alone or it needs the underlying stream ( i.e . FileInputStream.close ( ) ) also to be called explicitly.P.S . Javadoc for [ FilterOutputStr...
BufferredInputStream stream = nulltry { -- -- stream = new BufferredInputStream ( new FileInputStream ( ) ) ; -- -- } finally { if ( stream ! = null ) { stream.close ( ) } [ FilterOutputStream.close ] : http : //docs.oracle.com/javase/1.4.2/docs/api/java/io/FilterOutputStream.html # close % 28 % 29
Releasing I/O resource properly
Java
When using Matcher 's find ( ) method , a partial match returns false but the matcher 's position moves anyway . A subsequent invocation of find ( ) omits those partially matched characters.Example of a partial match : the pattern `` [ 0-9 ] + : [ 0-9 ] '' against the input `` a3 ; 9 '' . This pattern does n't match ag...
import java.util.regex . * ; public class Test { public static void main ( String [ ] args ) { final String INPUT = `` a3 ; 9 '' ; String [ ] patterns = { `` a '' , `` [ 0-9 ] + : [ 0-9 ] '' , `` [ 0-9 ] '' } ; Matcher matcher = Pattern.compile ( `` . * '' ) .matcher ( INPUT ) ; System.out.printf ( `` Input : % s % n '...
A partial match changes the Matcher 's position
Java
I am having an issue where the JRE crashes whenever I check if the GtkLookAndFeel is supported . Surprisingly , this bug only appears to show up on Oracle JREs.So far I have tested the behavior on three JREs : ( I am using the 64 bit version of all of these ) OpenJDK Runtime Environment ( IcedTea 2.5.1 ) ( 7u65-2.5.1-4...
import javax.swing.LookAndFeel ; public class Test { public static void main ( String [ ] args ) { LookAndFeel currLAF = new com.sun.java.swing.plaf.gtk.GTKLookAndFeel ( ) ; currLAF.isSupportedLookAndFeel ( ) ; System.out.println ( `` I am exiting main '' ) ; } } I am exiting main # # A fatal error has been detected by...
GtkLookAndFeel fatal crash on Oracle Jre
Java
Possible Duplicate : Generics in for each loop problem if instance does not have generic type assigned Could someone clarify why iterate1 ( ) is not accepted by compiler ( Java 1.6 ) ? I do not see why iterate2 ( ) and iterate3 ( ) are much better.Compiler output :
import java.util.Collection ; import java.util.HashSet ; public class Test < T > { public Collection < String > getCollection ( ) { return new HashSet < String > ( ) ; } public void iterate1 ( Test test ) { for ( String s : test.getCollection ( ) ) { // ... } } public void iterate2 ( Test test ) { Collection < String >...
Iterating over member typed collection fails when using untyped reference to generic object
Java
I was experimenting with anonymous classes today . When I do System.out.println ( super.x ) ; , it prints 12 , and when I use System.out.println ( x ) ; it prints 4 . I thought super.x would print 4 and was wondering if someone could please explain to me why this is ?
public class AnonClass { private int x = 1 ; public AnonClass ( int x ) { this.x = x ; } public static void main ( String [ ] args ) { AnonClass test = new AnonClass ( 4 ) ; test.testMethod ( ) ; } public void testMethod ( ) { AnonClass anon = new AnonClass ( 12 ) { { System.out.println ( super.x ) ; //Prints 12 System...
Anonymous class variables
Java
So I have been working fairly extensively with the Neo4j API , and I have noticed that virtually always they will have functions which return whereas I have always understood that it is better to return one of Set , List , or Collection unless one has a compelling reason to do otherwise . Set to indicate to the user th...
Iterable < Class >
When to return Iterable < String > rather than List , Set , Collection ?
Java
When I compile : I get an empty method fooTest ( ) { } . However when I compile : the if statement is included in the compiled class file . Does this mean there are two different `` types '' of static final in java , or is this just a compiler optimization ?
public static final boolean FOO = false ; public static final void fooTest ( ) { if ( FOO ) { System.out.println ( `` gg '' ) ; } } static boolean isBar = false ; public static final boolean BAR = isBar ; public static final void fooTest ( ) { if ( BAR ) { System.out.println ( `` gg '' ) ; } }
javac treating static final differently based on assignment method
Java
I have the following code which compiles successfully : However , if I convert the Supplier to the following lambda expression the code does not compile anymore : The compiler error is : If I change the declaration of the supplier to Supplier < ? extends List < V > > , both variants compile successfully.I compile the c...
import java.lang.String ; import java.util.List ; import java.util.Arrays ; interface Supplier < R > { Foo < R > get ( ) ; } interface Foo < R > { public R getBar ( ) ; public void init ( ) ; } public class Main { static private < V > void doSomething ( final Supplier < ? extends List < ? extends V > > supplier ) { // ...
Using lambda impedes inference of type variable
Java
I have class AbstractsAndInterfaces : Why does it print 5 ? Why BASE variable is uninitialized ?
public static AbstractsAndInterfaces instance = new AbstractsAndInterfaces ( ) ; private static final int DELTA = 5 ; private static int BASE = 7 ; private int x ; public AbstractsAndInterfaces ( ) { //System.out.println ( BASE ) ; //System.out.println ( DELTA ) ; x = BASE + DELTA ; } public static int getBASE ( ) { re...
Strange behaviour of static variables
Java
I have the following method in a class : Will this pattern get re-compiled every time the method is called ? Or does it get cached ? Should I declare it as a static variable in my class ? Thanks
public boolean validTransAmt ( ) { FacesContext facesContext = FacesContext.getCurrentInstance ( ) ; Pattern p = Pattern.compile ( `` ^ ( [ 0-9 ] { 0 , } ) ( ( [ \\. ] ? ) ( [ 0-9 ] { 1,2 } ) ( [ \\. ] ? ) ) $ '' ) ; String transAmt = getDetails ( ) .getAmount ( ) ; Matcher matcher = p.matcher ( transAmt ) ; if ( ! mat...
Should I declare pattern object as static
Java
I want to use the Templating Maven Plugin in my project , but I do n't understand where to put my sources . The plugin docs specify : but Intellij does not recognize this as a sources folder , and therefore wo n't allow me to create classes in it . If I make it a sources folder manually , then I run into the issue that...
$ { basedir } /src/main/java-templates
Intellij and maven templating plugin : how to reference java-templates
Java
I am reading the differrences between ArrayList and LinkedList pointed out in When to use LinkedList over ArrayList ? . I developed a small example applcation to test a major advantage of LinkedList but the results I obtain do not confirm , that LinkedList outweighs ArrayList in the performance of the operation : Here ...
ListIterator.add ( E element ) public static void main ( String [ ] args ) { int number = 100000 ; long startTime1 = System.currentTimeMillis ( ) ; fillLinkedList ( number ) ; long stopTime1 = System.currentTimeMillis ( ) ; long startTime2 = System.currentTimeMillis ( ) ; fillArrayList ( number ) ; long stopTime2 = Sys...
Measuring time does not confirm LinkedList advantage
Java
There is something that I do n't understand in the usual implementation of the clone method.If you look at the first line in the try block in the following code , we are calling super.clone ( ) , which will create an instance of the of the super class , and return an Object reference to that instance . Now , that insta...
public Object clone ( ) { try { Employee copy = ( Employee ) super.clone ( ) ; // copy ID , name , and salary ! copy.hireDay = ( Date ) hireDay.clone ( ) ; return copy ; } catch ( CloneNotSupportedException e ) { System.out.println ( e ) ; return null ; } }
In clone ( ) we use super.clone ( ) then access a variable that is not in super , how comes ?
Java
Base Class : Derived Class : This is what I have in mind regarding what is going on above.When I create an object of the derived class by default super ( ) is called and the constructor of the base class is called and it initializes the variable i . Now , my question is : Does the constructor in this case only initiali...
public class Inheritance { int i ; Inheritance ( ) { System.out.println ( `` I am in base class '' + i ) ; } } public class TestInheritance extends Inheritance { TestInheritance ( ) { System.out.println ( `` I am in derived class '' ) ; } public static void main ( String [ ] args ) { TestInheritance obj = new TestInher...
Inheritance and Object Creation
Java
I am trying to not load my entire tile based map into memory to save RAM client side . The map will be huge and already is requriring 1GB client side ( multi-layered map ) .I have gotten some perspective on Game Dev SO . I am trying to Load zones/chunks of my game map into memory ( i.e . 300x300 ) and then when the pla...
public class MapChunkLoad { public static void main ( String [ ] args ) { short [ ] groundLayer ; int mapWidth = 9 ; int mapHeight = 9 ; int chunkWidth = mapWidth / 3 ; //3 int chunkHeight = mapHeight / 3 ; //3 int characterX = 8 ; int characterY = 8 ; String map = `` 1 , 1 , 1 , 1 , 1 , 1 , 1 , 1 , 7 , `` + `` 1 , 8 ,...
Split 1d array into chunks
Java
Is there any way to do Null Objects with Java Records ? With classes I 'd do it like that : But that does not work , because every constructor needs go through the canonical ( Id ( String id ) one and I ca n't just call super ( ) to go around the invariants.Right now I work around this withbut that feels wrong and open...
public class Id { public static final Id NULL_ID = new Id ( ) ; private String id ; public Id ( String id ) { this.id = Objects.requireNonNull ( id ) ; } private Id ( ) { } } public record Id ( String id ) { public static final Id NULL_ID = null ; // how ? public Id { Objects.requireNonNull ( id ) ; // ... } } public I...
Java Records and Null Object Pattern ?
Java
I was studying on leetcode for an interview . There were a question about finding missing number unpaired in array . I solved it by using HashSet . But i saw the below solution which is more efficient than mine.My question is that what the logic XOR of a ^= nums [ i ] means ?
int a = 0 ; for ( int i = 0 ; i < nums.length ; i++ ) { a ^= nums [ i ] ; } return a ;
What is the purpose of `` ^= `` operator in Java ?
Java
I 'm practicing algorithms and let 's say we have an array with elements 2 , 3 , 9 , 12 , 7 , 18 , then I want to print 18 only because it 's double of 9 . When I print the result it always displays much more lines , however , the printed numbers ( if there are any ) are good . How can I manage displaying the result pr...
The following number is doubled of another number from the array : 0The following number is doubled of another number from the array : 0The following number is doubled of another number from the array : 140The following number is doubled of another number from the array : 0The following number is doubled of another num...
Print only those numbers that are double of another number in the array in Java
Java
I 've coded for several months in Python , and now i have to switch to Java for work 's related reasons . My question is , there is a way to simulate this kind of statementwithout defining an additional isIn ( ) -like boolean function that scans list_name in order to find var_name ?
if var_name in list_name : # do something
Simulate if-in statement in Java
Java
I want to display a formatted date on my JSP page , so I use : It works perfectly . It is displayed on the page as However , a strange thing happens when it is cached by Google - the date on the cached page is displayed like this : Can anyone explain this ? Should n't the formatting happen on the server ? Does n't my a...
< fmt : formatDate pattern= '' MMM d '' value= '' $ { myEvent.date } '' / > Nov 28 2016-11-28 20:00:00.0
JSP - Date formatting and Google cache
Java
Why this happening.Why there is compilation error in first case . If i put braces then no compilation error but for if statement braces are optional if it 's one statement .
if ( someCondition ) int a=10 ; //Compilation Errorelse if ( SomeOtherCondition ) { int b=10 ; //no compilation Error }
Variable declaration in if clause
Java
With jdk12 , came Chess symbols ( source ) : Unicode 11.0.0 introduced the following new features that are now included in JDK 12 [ ... ] 4 blocks for the following existing scripts : Georgian Extended Mayan Numerals ndic Siyaq Numbers Chess Symbols With that in mind , I tried to print those characters with the followi...
Character.UnicodeBlock block = Character.UnicodeBlock.CHESS_SYMBOLS ; for ( int i = 0 ; i < 1114112 ; i++ ) { char unicode = ( char ) i ; if ( Character.UnicodeBlock.of ( unicode ) == block ) { System.out.println ( unicode ) ; } }
Print chess symbols using UnicodeBlock ?
Java
I am trying to run a maven project from a python script . I have installed apache maven . Running the command : mvn exec : java -D '' exec.mainClass '' = '' org.matsim.project.RunMatsim '' from terminal in the project folder where the pom.xml is , creates no errors and the project runs correctly.But when running the fo...
import subprocess as spdef execute ( cmd ) : popen = sp.Popen ( cmd , stdout=sp.PIPE , universal_newlines=True , shell=True ) for stdout_line in iter ( popen.stdout.readline , `` '' ) : yield stdout_line popen.stdout.close ( ) return_code = popen.wait ( ) if return_code : raise sp.CalledProcessError ( return_code , cmd...
Maven command mvn runs without errors from terminal but not from python
Java
I know question is quite simple for you people to answer but , I got stuck at a drop list from where i wanted to select the birth Month.I have been working on other websites but unfortunately could'nt get this to work.I tried : Click using different locators.Using Action class to mover hover and clicking.Using Java Scr...
< span id= '' BirthMonth '' class= '' form-error '' aria-invalid= '' true '' > < div class= '' goog-inline-block goog-flat-menu-button jfk-select '' role= '' listbox '' style= '' -moz-user-select : none ; '' aria-expanded= '' false '' tabindex= '' 0 '' aria-haspopup= '' true '' aria-activedescendant= '' :0 '' title= ''...
Unable to select the value from the drop list
Java
I have some Java code which filters a list based on some input . It currently uses a lambda , for example : What I want to do is to move the filter logic to another method to make it re-usable and easily unit testable . So I wanted to use a method reference in place of the lambda passed to the filter method . Easy to d...
public List < ComplexObject > retrieveObjectsFilteredByTags ( List < String > allowedTags ) { List < ComplexObject > complexObjects = retrieveAllComplexObjects ( ) ; return complexObjects .stream ( ) .filter ( compObject - > allowedTags.contains ( compObject.getTag ( ) ) ) .collect ( Collectors.toList ( ) ) ; } public ...
How to convert lambda filters with dynamic values to method references
Java
I 'm learning Java 's generic , I snag into some problem instantiating the type received from generic parameters ( this is possible in C # though ) I tried this : generics in Java - instantiating TError : That does n't work . The following looks ok , but it entails instantiating some class , can not be used on static m...
class Person { public static < T > T say ( ) { return new T ; // this has error } } public static < T > T say ( Class < ? > t ) { return t.newInstance ( ) ; } incompatible typesfound : capture # 426 of ? required : T public class Abc < T > { public T getInstanceOfT ( Class < T > aClass ) { return aClass.newInstance ( )...
Instantiating generic 's parameter
Java
I would like to understand the following type of syntax.Example : What is the logic of this interface ?
public interface A < T extends A < T > > { }
Generics in Java
Java
I 'm trying to use Java 8 lambdas and have a general question about object serialization.For example the following input prints 5 if the executor.execute has only one method and runs the code block without serializing it.However if I serialize the lambda expression via SerializedLambda and deserialize it back , it prin...
final int finalVar = 5 ; executor.execute ( ( ) - > { System.out.println ( finalVar ) ; } ) ; final int finalVar = 5 ; executor.execute ( new Runnable ( ) { int myVar = finalVar ; public void run ( ) { System.out.println ( myVar ) ; } ) ;
Including outside variables when serializing an object
Java
How can the Array content be converted to a String in Java ? Example : The output has to be : Arrays.toString ( myArray ) is returning : and myArray.toString ( ) , returns : So none of them works . Is there a function for this ? This question might look similar to ( this ) , but is actually different . I am literally a...
int [ ] myArray = { 1,2,3 } ; `` 123 '' `` [ 1 , 2 , 3 ] '' [ I @ 12a3a380
How to print Array content in Java ?