lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
Well , I have an interface which is ; And I 'm implementing it . Here is thing , when I defining function like : I 'm getting warning on function initalize which is 'Type safety : The expression of type ... needs unchecked conversion to conform to ... '.I can get rid of this with using suppresswarning but I do not want...
public interface abc { public < T extends JPanel > T initalize ( ) ; } public class Startup_thePanel extends JPanel implements abc { public Startup_thePanel initalize ( ) { return this ; } }
java wildcard type safety warning
Java
Caller Of the method , MethodProblemIf there are 2 requests that has to be sent , I sometime see only one request being sent . Meaning , even though for loop is executing twice for 2 request ( HTTP ) , I see only one request is being sent to the server.What is that i am doing wrong here ? Rxjava version in use : 2.2.19
for ( String name : controllerToPartitionModels.keySet ( ) ) { List < PartitionModel > partitionsList = controllerToPartitionModels.get ( name ) ; refreshPartition ( partitionsList , false ) ; } private void refreshPartition ( List < PartitionModel > partitionModels , boolean isSyncAll ) { ITModule.getITService ( ) .re...
Android + RxJava + For Loop + Not executing all the requests
Java
I have written a piece of software in Java that checks if proxies are working by sending a HTTP request using the proxy . It takes around 30,000 proxies from a database , then attempts to check if they are operational . The proxies received from the database used to be returned as an ArrayList < String > , but have bee...
//This code is executed recursively ( at the end , main ( args ) is called again ) //Create the threadpool for requests//Threads is an argument that is set to 750.ThreadPoolExecutor executor = ( ThreadPoolExecutor ) Executors.newFixedThreadPool ( threads ) ; Deque < String > proxies = DB.getProxiesToCheck ( ) ; while (...
I have tried to optimize ( memory ) my program , but GC is still making it lag
Java
I have the week number , its curresponding year and dayOfWeek number ( i.e . 1 for Monday , 2 for Tuesday and so on ) . Is there a way to find the date with this information in java ? Following is a method I found online . But then realised that wkstart is storing the current date instead of the start of the week.Is th...
int week = 51 ; LocalDate wkstart = LocalDate.now ( ) .with ( IsoFields.WEEK_OF_WEEK_BASED_YEAR , week ) ; LocalDate mon = wks.plusDays ( 1 ) ; LocalDate tue = wks.plusDays ( 2 ) ; LocalDate wed = wks.plusDays ( 3 ) ; LocalDate thu = wks.plusDays ( 4 ) ; LocalDate fri = wks.plusDays ( 5 ) ; LocalDate sat = wks.plusDays...
How to get Date from Week Number , Year and dayOfWeek in java ?
Java
How do I use list.contains to check if the number was found in the list more than once ? I could make a method with for loop , but I want to know if it 's possible to do using .contains . Thanks for help !
private static boolean moreThanOnce ( ArrayList < Integer > list , int number ) { if ( list.contains ( number ) ) { return true ; } return false ; }
ArrayList , double contains
Java
I think I 've run into an issue with an assumption I made : if a spliterator 's item is n't consumed by a stream , the spliterator will still be able to advance to it . It seems like this is not the case.Here 's some code to demonstrate : This outputs : I understand that spliterators can be split ... but it seems like ...
import java.util.Spliterator ; import java.util.function.Function ; import java.util.stream.Collectors ; import java.util.stream.Stream ; import java.util.stream.StreamSupport ; /** * Created by dsmith on 7/21/15 . */public class SpliteratorTest { public static void main ( String [ ] args ) { System.out.println ( `` Te...
Spliterator state after `` consumed '' in Stream
Java
Consider this class : And consider this reflection snippet which wants to access the handle ( ) method.Instead of findingpublic void Handler.handle ( Bar ) It findsprivate Foo Handler.lambda $ 3 ( Bar ) Which obviously then throws the Exception : Can someone explain what is going on here , please ? It looks like Java c...
public class Handler { private Supplier < Foo > foo ; public void handle ( Bar bar ) { foo = ( ) - > bar.getFoo ( ) ; } } for ( Method method : Handler.class.getDeclaredMethods ( ) ) { if ( method.getParameterCount ( ) == 1 & & Bar.class.isAssignableFrom ( method.getParameterTypes ( ) [ 0 ] ) ) { // This is the method ...
Inner Lambda getting returned in Class.getDeclaredMethods ( ) ?
Java
I am trying to use a pattern to search for a Zip Code within a string . I can not get it to work correctly . A sample of the inputLine is What I am trying to use for a pattern is If I am looking to only get 75002 , what do I need to change ? This only outputs the last digit in the number , 2 . I am terribly confused an...
What is the weather in 75042 ? public String getZipcode ( String inputLine ) { Pattern pattern = Pattern.compile ( `` .*weather.* ( [ 0-9 ] + ) . * '' ) ; Matcher matcher = pattern.matcher ( inputLine ) ; if ( matcher.find ( ) ) { return matcher.group ( 1 ) .toString ( ) ; } return `` Zipcode Not Found . `` ; }
Searching for number after a specific word that does not immediately precede the number
Java
the java source code like : why the result is : white ?
public class Test { public static void main ( String [ ] args ) { System.out.println ( X.Y.Z ) ; } } class X { static class Y { static String Z = `` balck '' ; } static C Y = new C ( ) ; } class C { String Z = `` white '' ; }
what 's the class and field order of loading in java ?
Java
I have a big set of strings and I want to create an autosuggest feature for it.Assume the set is [ `` foo '' , `` fighter '' ] Typing `` f '' should return both values , and typing `` fo '' should only return `` foo '' .Currently I am just iterating through the set and filering out results by calling startsWith , howev...
public Set < String > getSubset ( String s ) { result = new HashSet < String > ( ) ; getSubset ( root , s ) ; return result ; } private void getSubset ( TrieNode node , String s ) { TrieNode n = node ; for ( char ch : s.toCharArray ( ) ) { if ( n.children [ ch ] ! = null ) { n = n.children [ ch ] ; continue ; } return ...
Efficiently get subset of strings `` startingWith '' out of a set
Java
I have some troubles with a method having a typed List parameter , inherited from another ( typed ) class.Let 's keep it simple : The B class has a useless generic T , and test ( ) want an Integer List.Now if I do : I get a `` The method test ( List ) of type A must override or implement a supertype method '' error , t...
public class B < T > { public void test ( List < Integer > i ) { } } public class A extends B { // do n't compile @ Override public void test ( List < Integer > i ) { } } public class A extends B { // compile @ Override public void test ( List i ) { public class A extends B < String > { // compile @ Override public voi...
Method with typed list and inheritance
Java
When we move the right hand side to the left of the equation , we need to flip the operator sign from + to - and vice versa.Using java regex replaceAll , we 're able to replace all + 's with - 's . As a result , all the operator signs become - 's , making it impossible for us to recover all the +'s.As a workaround , I ...
6*x + 7 = 7*x + 2 - 3*x
Is it possible to switch between + and - using regex in Java ?
Java
If a application run by gradle should be debugged , you add the parameterThe debugger will start a jpda-server ( because server=yes ) and suspend until eclipse ( or whatever ) attach to the socket.How to do the inverse way ? How to tell gradle-bootrun to attach to the eclipse-jpda-server ? I tried to set the options li...
-- debug-jvm bootRun { jvmArgs= [ `` -agentlib : jdwp=transport=dt_socket , server=n , suspend=y , address=localhost:5005 '' ] } * What went wrong : Execution failed for task ' : bootRun'. > The value for property 'enabled ' is final and can not be changed any further . * Try : Run with -- info or -- debug option to ge...
debug gradle bootRun having server=n
Java
Learning about Java iterators and general data structures via means of homework.I have built a doubly-linked list ( LinkedList ) which uses Nodes ( LinkedList $ Node ) and has an Iterator ( LinkedList $ LinkedListIterator ) All classes make use of generics.Within LinkedListIterator 's @ Overridden remove ( ) method I a...
./LinkedList.java:170 : deleteNode ( LinkedList < T > .Node < T > , LinkedList < T > .Node < T > , LinkedList < T > .Node < T > ) in LinkedList < T > can not be applied to ( LinkedList < T > .Node < T > , LinkedList < T > .Node < T > , LinkedList < T > .Node < T > ) deleteNode ( nodeToBeRemoved , next , prev ) ; import...
Why does the javac error `` ( x ) can not be applied to ( y ) '' , happen when both parameters and arguments match up ? ( inner-class calling outer-class method )
Java
how I can get current Persian Date with time4Jin java ?
PersianCalendar jalali = new PersianCalendar ( ) ;
How to get current date in time4j library ?
Java
Has anyone had any success using JDK 16 ( https : //jdk.java.net/16/ ) early access build with IntelliJ ? I am able to use JDK 15 early access builds , but when I try JDK 16 I get an error message : All of the research I 've done says JDK stores tools.jar inside of the path/to/jdk-16/lib folder . Thing is , tools.jar i...
Error : Can not determine path to 'tools.jar ' library for 16 ( path/to/jdk-16 )
IntelliJ JDK 16 Early Access - Any Success ? tools.jar
Java
this might be a long message but i would like to give a clear question for all of stackoverflow user.What I did is create a static String of array inside a class that is binded on my gridviewAnd manually binding it on public class ImageAdapter extends BaseAdapterAs you see I am calling ParserArrayList 's 'imageCaptionI...
class ParserArrayList { //some declaration and codes here private String [ ] imageCaptionId = { `` My First Medal '' , `` You ... '' , `` The ... '' , `` Gim me ... '' , `` A ... '' , `` Seven ... '' , `` ... ..City '' , `` ... . Madness '' , `` Loyal ... '' , `` ... .. '' , `` ... '' , `` Champion ... '' } ; } public ...
Static Array of string must be converted from database
Java
Java does not parse the date as expected and outputs :
SimpleDateFormat sdf = new SimpleDateFormat ( `` MMM dd , YYYY , EEE '' , Locale.US ) ; System.out.println ( sdf.format ( new Date ( ) ) ) ; System.out.println ( sdf.format ( sdf.parse ( `` Apr 27 , 2018 , Fri '' ) ) ) ; Apr 27 , 2018 , FriJan 05 , 2018 , Fri // I can not understand why java parse the month of April as...
java date parse missbehaviour
Java
I have gone through the following link Why would a static nested interface be used in Java ? .In my code base I have : And in some other class in a different package : Now , my question is - `` Is it really a good design to put I2 in I1 '' ? EDIT : / And in a different file I have ...
public interface I1 { public static interface I2 { public void doSomething ( ) ; } //some other methods public void myMethod ( I2 myObject ) ; } public abstract class SomeClass implements I2 { //mandatory method ... } public interface XClientSession { static public interface OnQueryResultSentListener { public void onQu...
What is the use of nested interfaces in this code
Java
Why does TreeMap of type Map not define the methods tailMap or headMap.With explicit cast it works : With NavigableMap everything is fine : If I 'm right that 's because of the interface Map lacking corresponding methods , in spite of the face that the object map is concrete implementation of class TreeMap that certain...
Map < String , String > map = new TreeMap < > ( ) ; map.tailMap ( ) ; // can not resolve method tailMap ( ( TreeMap < String , String > ) map ) .tailMap ( `` a '' ) ; NavigableMap < String , String > map1 = new TreeMap < > ( ) ; map1.tailMap ( `` a '' ) ;
Can not resolve method tailMap for TreeMap
Java
I have this piece of code , where I want to return an element if present , otherwise nullbut I got an Exception in thread `` main '' java.lang.NullPointerException anyway
List < String > myList = new ArrayList < > ( ) ; myList.add ( `` Test '' ) ; myList.add ( `` Example '' ) ; myList.add ( `` Sth '' ) ; String str = myList.stream ( ) .filter ( x - > x.equals ( `` eee '' ) ) .findFirst ( ) .orElseGet ( null ) ;
Java8 Lists return element or null
Java
Trying to run a simple hello world example but getting the following error , which I do not understand : How to solve it ? Do I need some libs , plugins , configs which are not yet included ? Here is my pom : Tried using Java 9,10,11,12 and JavaFX 12 & 13 and get the same error .
Graphics Device initialization failed for : d3d , swError initializing QuantumRenderer : no suitable pipeline foundjava.lang.RuntimeException : java.lang.RuntimeException : Error initializing QuantumRenderer : no suitable pipeline found < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //m...
Problems running a javafx application , Netbeans 11 , java 12 , javafx 13
Java
I recently needed to sort a one line file ( integers separated by `` , '' ) into smaller chunks with memory restriction and efficiency in mind . I 'm currently following this logic : Assuming I 'm restricted to 5MB of memory and have to read a one-line file with 10,000,000 integers separated by `` , '' : If I use a ver...
File file = new File ( `` bigfile.txt '' ) ; FileInputStream fis = new FileInputStream ( file ) ; BufferedInputStream bis = new BufferedInputStream ( fis ) ; int BUFFER_SIZE = 10 ; // can and should be biggerbyte [ ] bytes = new byte [ BUFFER_SIZE ] ; while ( ( bis.read ( bytes ) ) ! = -1 ) { // convert bytes to string...
Split huge file of integers ( in one line ) into sorted chunks with memory restriction
Java
I have a rest controller contains many methodsHow can I know which method is being accessed without using print in each method ? Are there any ways to do that ?
@ RestController @ RequestMapping ( `` v1/test '' ) public class TestRestController { ... ... 100 methods ( GET , POST , PATCH , etc ) }
Spring Log for Rest Controller
Java
I noticed something in static initializers which may be a bug in the javac . I have constructed a scenario where I can assign a variable a value but not read that value back.The two examples are below , the first compiles fine , the second gets an error when trying to read a value from tmp , but for some reason assigni...
//Compiles Successfully : public class Script { public static Object tmp ; static { tmp = new Object ( ) ; System.out.println ( tmp ) ; } } //error only on the read but not the assignmentpublic class Script { static { tmp = new Object ( ) ; System.out.println ( tmp ) ; } public static Object tmp ; } public class Script...
Static initializer error if placed before the declaration
Java
The Java-Spec guarantees that a given lamda-definition , e.g . ( ) - > `` Hello World '' , is compiled/converted to exactly one implementation class ( every definition , not every occurence that `` looks '' the same ) .Is there any way I can force the java-compiler/jvm to generate a new lamda-definition instead of shar...
public < In , Out , A > BiFunction < In , Out , Out > weave ( Function < ? super In , A > getter , BiConsumer < ? super Out , ? super A > consumer ) { return ( in , out ) - > { consumer.accept ( out , getter.apply ( in ) ) ; return out ; } ; }
How to force a new instantiation of a lamda-definition
Java
I am confused by the answers and the results i am getting on compiling a 3 line program . Here is the code along with its opcodes : http : //pastebin.com/B1xxAjcp If i am not totally wrong , its evident thatthese lines corresponds to these opcodes : So to my understanding ldc # index means that instead of creating a ne...
String s= '' abcd '' ; String s1=new String ( `` efgh '' ) ; s.concat ( `` ijkl '' ) ; 1 : istore_1 2 : ldc # 2 // String abcd 4 : astore_2 5 : new # 3 // class java/lang/String 8 : dup 9 : ldc # 4 // String efgh 11 : invokespecial # 5 // Method java/lang/String . `` < init > '' : ( Ljava/lang/String ; ) V 14 : astore_...
how to understand whether a new String object has been created
Java
I have several values , like this : ( Elements in a row are in relationship . ) I should find all the values which are in relationship and put them into a list , like this : [ 26,287 154,303 375,338 260,393 ] I have tried to use this code : It creates only one ArrayList , it gives all elements in a row instead of separ...
Vertex relationships ( edges ) Source vertex Destination vertex x1 26 y1 287 x2 154 y2 303 x1 22 y1 114 x2 115 y2 185 x1 26 y1 287 x2 375 y2 338 x1 26 y1 287 x2 260 y2 393 x1 115 y1 185 x2 121 y2 7 x1 200 y1 101 x2 392 y2 238 x1 99 y1 394 x2 375 y2 338 x1 99 y1 394 x2 121 y2 7 x1 274 y1 28 x2 22 y2 114 x1 296 y1 185 x2...
Arraylists of arraylist as a representation of relationships
Java
When we launch jar file by command line We can pass argument by just adding arguments by space . But sometimes I faced with the arguments those start with dash like -Darg1 , -Darg2.What is the difference between them ?
$ java -jar someJar.jar arg1 arg2
What is the difference between java dashed arguments ( like -D ) and the without a dash ?
Java
Consider the following code : I 'm trying to understand why it wo n't compile . Meaning , why does n't the compiler let me refer to List < ? extends Animal > as a List < Animal > ? Is that has something to do with the type erasure mechanism ?
public class Main { static class Animal { } static class Dog extends Animal { } static List < ? extends Animal > foo ( ) { List < Dog > dogs = new ArrayList < > ( ) ; return dogs ; } public static void main ( String [ ] args ) { List < Animal > dogs = Main.foo ( ) ; // compile error } }
Why ca n't List < ? extends Animal > be replaced with List < Animal > ?
Java
Reading this article about JSR-133 , it says : all of the writes to final fields ( and to variables reachable indirectly through those final fields ) become `` frozen , '' ... If an object 's reference is not allowed to escape during construction , then once a constructor has completed and a thread publishes a referenc...
class Parent { /** NOT final . */ private int answer ; public int getAnswer ( ) { return answer ; } public void setAnswer ( final int _answer ) { answer = _answer ; } } public class Child extends Parent { private final Object self ; public Child ( ) { super.setAnswer ( 42 ) ; self = this ; } @ Override public void setA...
Does self-reference in the constructor counts as `` escaping '' ?
Java
Upon discussing the multiple-catch / combined catch block here with ambiguity between the terms `` multiple catch block , '' meaning the Java 7 feature : and `` multiple catch blocks , '' meaning literally , multiple catch blocks : I 've researched to see if the Java 7 feature has a specific , official name that can be...
try { .. } catch ( ExceptionA | ExceptionB ex ) { .. } } catch ( ExceptionA exa ) { .. } catch ( ExceptionB exb ) { .. }
Is there an official name for Java 7 's combined / multi-catch block ?
Java
As usual , I 'm just another highschooler desperate enough to resort to asking the question after lots of googling.I 'm working on one of them programs that can somewhat be applied in real life ( but never are ) . In this case , a change counter that sums up the number of dimes , nickels , quarters and remaining cents ...
System.out.print ( backupInput + `` : `` ) ; // Outputting the quarters if ( quarters > 0 ) { if ( quarters == 1 ) System.out.print ( `` one quarter , `` ) ; else System.out.print ( quarters + `` quarters , `` ) ; } // Outputting the dimes if ( dimes > 0 ) { if ( dimes == 1 ) System.out.print ( `` one dime , `` ) ; els...
How do I include `` and '' in the right place in my program
Java
According to Java Concurrency in Practice , it is dangerous to start a thread within a class constructor . The reason is that this exposes the this pointer to another thread before the object is fully constructed.Despite this topic being discussed in many previous StackOverflow questions , I am still having difficulty ...
private static class ValueHolder { private int value ; private Thread thread ; ValueHolder ( ) { this.value = 10 ; thread = new Thread ( new DoublingTask ( this ) ) ; // exposing `` this '' pointer ! ! ! thread.start ( ) ; // starting thread inside constructor ! ! ! } int getValue ( ) { return value ; } void awaitTermi...
Understanding why is it unsafe to start a thread inside a constructor in terms of the Java memory model
Java
I was working on a part of an in-house library today and wanted to improve some things by adding basic generics to our `` Game '' class.Here is the stripped down version of the , now changed , game class : Pretty standard , I know . But when I wanted to use the getPlayers ( ) method in a game module like this : for ( G...
public abstract class Game < G extends GamePlayer > { private final List < G > players ; public Game ( ) { this.players = new LinkedList < > ( ) ; } public Collection < G > getPlayers ( ) { return players ; } } public class GiftTask implements Runnable { private final Game game ; private final Item [ ] items ; public G...
List < T > returns an object collection
Java
I 'm a bit lost about this fact : I read some similar question here , but the problems in those cases where not mine , so here I am.I use MySQL and Hibernate . In my webapp there is this static HibernateUtil class to access the database : Then I call the util class like in this example : So basically I close the connec...
show status like 'con % ' ; + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -+| Variable_name | Value |+ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -+| Connection_errors_accept | 0 || Connection_errors_internal | 0 || Connection_errors_max_connections | 0 || Connection_errors_peer_a...
Many MySQL connections
Java
I need to retrieve a list of currently open programs using java . The following code gives me a list of all the programs that are active including any background processes however I need only a list of active programs . I am not going to be aware what programs are currently open and so will not be able to find it by se...
try { String line ; Process p = Runtime.getRuntime ( ) .exec ( System.getenv ( `` windir '' ) + '' \\system32\\ '' + '' tasklist.exe '' ) ; BufferedReader input = new BufferedReader ( new InputStreamReader ( p.getInputStream ( ) ) ) ; while ( ( line = input.readLine ( ) ) ! = null ) { System.out.println ( line ) ; } in...
Get a list of active programs in java
Java
I 'm working on a method aimed at sorting an array in ascending order . The array consists of earthquake marker objects , and what I need to do is sorting the array by the `` magnitude '' property of the objects . I tried selection sort but it seems that the elements are n't swapped properly.Here is my code : It turned...
private void sortAndPrint ( int numToPrint ) { Object [ ] quakeArray= quakeMarkers.toArray ( ) ; int indexMax ; for ( int i=0 ; i < quakeArray.length-1 ; i++ ) { indexMax = i ; float max = ( ( EarthquakeMarker ) ( quakeArray [ i ] ) ) .getMagnitude ( ) ; for ( int j =i+1 ; j < quakeArray.length ; j++ ) { if ( ( ( Earth...
Java swap invalid
Java
What doesdeclared inside a class definition body mean ?
static { //something } public class A extends B { static { C.register ( new C ( A.class , ( byte ) D.x.getCode ( ) ) { public DataSerializable newInstance ( ) { return new A ( ) ; } } ) ; } }
Java syntax question
Java
I have a method that returns Set < Set < String > > . In my test , I am trying to check if the expected Sets are present using contains ( ) method . eg . input = `` cat '' , `` dog '' , `` god '' output = [ [ cat ] , [ dog , god ] ] Now , if I do output.contains ( new HashSet < > ( Arrays.asList ( `` cat '' ) ) ) it re...
public class AnagramGroups { public Set < Set < String > > group ( Set < String > words ) { Set < Set < String > > groups = new HashSet < > ( ) ; for ( String word : words ) { findAndAdd ( word , groups ) ; } return groups ; } private void findAndAdd ( String word , Set < Set < String > > groups ) { for ( Set < String ...
Equality in Set < Set > Java
Java
I have this code , a PostFixCalculator but whatever I put in for the while and try , I kept getting an error . The program compiles and runs the way it is posted , but it does not run correctly . I 've hit a wall..
import java.util.Scanner ; public class PostFixCalculator { public static void main ( String [ ] args ) { Scanner kbd = new Scanner ( System.in ) ; int result ; String expression ; System.out.println ( `` Student name , CS-304 , Fall 2014 , Asst 2c . `` ) ; System.out.println ( `` To quit this program , just hit 'retur...
PostFixCalculator while/try error
Java
I have to calculate total fly time minutes between departure airport and arrival airport . This job is done by this code snippet : Here is the problem : When I want to calculate future flight 's duration with those parameters : as a result of those parameters , flightDuration object is : Seems everything is OK , right ...
public int calculateFlightDuration ( String departureDateTime , String depAirportCode , String arrivalDateTime , String arrAirportCode ) { try { LocalDateTime depLocalTime = LocalDateTime.parse ( departureDateTime , formatter ) ; LocalDateTime arrLocalTime = LocalDateTime.parse ( arrivalDateTime , formatter ) ; ZoneOff...
Time difference calculation error
Java
Given an API like : In Java 's Optional type , we can say : But , since Foo is a Bar , I would like to be able to say : As an exercise , I wanted to accomplish this with another type : How would I rewrite this to compile , but also support the ability to widen the type when desired at the same time ?
class Bar { ... } class Foo extends Bar { ... } Optional < Foo > fooOption = ... fooOption.orElse ( aFoo ) // returns something of type Foo Optional < Foo > fooOption = ... fooOption.orElse ( aBar ) // returns something of type Bar public abstract class Option < T > { // this does n't compile public abstract < U super ...
Given ` T ` and ` U ` where ` T extends U ` how to return a ` U `
Java
I have this string : I tried to split the string using the following code : Result is the following array : But I need to split the string as follows : To make it clearer . First of all I need to ignore - > when it splits the string and then remove those empty strings in the result array .
`` round ( ( TOTAL_QTY * 100 ) / SUM ( ORDER_ITEMS- > TOTAL_QTY ) , 1 ) '' String [ ] tokens = function.split ( `` [ ) ( *+-/^ ! @ # % & ] '' ) ; `` round '' '' '' '' TOTAL_QTY '' '' '' '' '' '' 100 '' '' '' '' '' '' '' '' SUM '' '' ORDER_ITEMS '' '' - > TOTAL_QTY '' '' '' '' '' '' '' '' 1 '' `` round '' , '' TOTAL_QTY...
Using String.split ( ) How can I split a string based on a regular expression excluding a certain string
Java
Consider this code : I would expect the last statement to require an explicit cast because , b+=l is evaluated as b = b+l and ( b+l ) part gives an integer.Integer can not be assigned to byte without an explicit cast ?
byte b=1 ; long l=1000 ; b += l ;
Why does this assignment not require an explicit cast ?
Java
I 've read a little about what `` this '' escaping is and realize that the previous code is bad , as I have little idea what the external processes are doing with the this reference , so it should n't be passed outside the constructor until it is constructed.However , due to the final fields in both App and A , I reall...
public class App { private final A a ; private final Server server ; public App ( ) { a = new A ( this ) ; //Bad , this is escaping before it 's initialized . } @ Subscribe //This event fires some time after App is finished constructing . public void registerStuff ( RegisterEvent event ) { server = event.getServer ( ) ...
Preventing `` this '' escaping during construction with final fields
Java
I 've been profiling the x64 version of my application as the memory usage has been outrageously high , all of it seems to be coming from the JavaFX MediaPlayer , i 'm correctly releasing listeners and eventhandlers . Here is the stark contrast . The x32 version at start And now the x64 version at startThe x32 version ...
-XX : MinHeapFreeRatio=40 -XX : MaxHeapFreeRatio=70 -Xms3670k -Xmx256m -Dsun.java2d.noddraw=true -XX : +UseParallelGC
Java - Odd memory consumption between x32 and x64
Java
I want to sort the data according to id and marks pair.ID should be in ascending order and marks should be in descending order , here is my code : output like :
ArrayList < Student > al=new ArrayList < Student > ( ) ; al.add ( new Student ( 1 , '' dg '' ,58 ) ) ; al.add ( new Student ( 2 , '' dg '' ,48 ) ) ; al.add ( new Student ( 1 , '' dg '' ,98 ) ) ; al.add ( new Student ( 2 , '' dg '' ,68 ) ) ; al.add ( new Student ( 1 , '' dg '' ,38 ) ) ; al.add ( new Student ( 2 , '' dg ...
Ascending and Desending order in same program using java
Java
I have this class : For this class I have a simple list filled with some data . List < A > listOfA.Now I want to convert this data to a map . Map < String , List < A > > Currently we using a bunch of methods to archive this in a very complicated way . I think , we can solve it with a simple stream ( ) -operation.I trie...
class A { private List < String > keys ; private String otherData ; private int otherDate2 ; // getter and setters for each } // firstlistOfA.stream ( ) .collect ( Colletors.groupingBy ( a - > a.getKeys ( ) ) ) // produces a Map < String , List < A > > // secondlistOfA.stream ( ) .flatMap ( a - > a.getKeys ( ) .stream ...
GroupBy a list of strings
Java
I have below code snippet and this works fine . Should n't it throw compile time error because I have defined c as ArrayList which will contain String object but I am adding Integer object . So why it did not throw compile time/Run time error ? I know below will throw compile time error but why not above . Whats the lo...
Collection c = new ArrayList < String > ( ) ; c.add ( 123 ) ; Collection < String > ( ) c = new ArrayList ( ) ; c.add ( 123 ) ;
No error with this collection declared with generics ?
Java
Is there a way to let the 'reduction ' of the reduce ( ) method of Stream be optional ? I want to iterate over a list of Periods and join the periods that overlap and maintain both periods if they do n't overlap :
interface Period { boolean overlaps ( Period other ) ; } List < Period > periods = new ArrayList < > ( ) ; periods.stream ( ) .reduce ( new BinaryOperator < Period > ( ) { @ Override public Period apply ( Period period , Period period2 ) { if ( period.overlaps ( period2 ) ) { // join period and period2 into period . } ...
Apply reduction only if certain condition is met
Java
I want to figure out the time complexity of the while loop , I know the running time of the isThere function is N and So is the main for loop in firstAlgo
public class Question2 { //running time of function is N ! ! ! ! ! ! public static boolean isThere ( int [ ] array , int num , int index ) { boolean isItThere = false ; //running time of 1 for ( int i =0 ; i < = index ; i++ ) { //running time i if ( array [ i ] == num ) { //running time of 1 isItThere = true ; //runnin...
Big O time complexity of a while loop with a random Object
Java
I want to use a List < E > but the only method I 'm ever going to use isI am interested in the return value of this method ( the E removed ) . I never need the method remove ( E e ) .The only constructor I 'll ever need is one taking a Collection < ? extends E > .If List is an ArrayList , the remove ( int index ) metho...
E remove ( int index )
A List implementation that is optimised for remove ( int index )
Java
Possible Duplicate : Integer wrapper objects share the same instances only within the value 127 ? How ! = and == operators work on Integers in Java ? I tried to compare two ints with the following cases and got unexpected resultswhen I did the following , @ @ @ was printed.when I did the following , @ @ @ was not print...
class C { static Integer a = 127 ; static Integer b = 127 ; public static void main ( String args [ ] ) { if ( a==b ) { System.out.println ( `` @ @ @ '' ) ; } } } class C { static Integer a = 145 ; static Integer b = 145 ; public static void main ( String args [ ] ) { if ( a==b ) { System.out.println ( `` @ @ @ '' ) ; ...
Unexpected result when comparing ints
Java
I have these two interfaces . One is public ( A ) , the other one is package private ( AA ) . A extends AA..I have this code ( in a different package ) : When running the above code the list.stream ( ) .forEach ( A : :defaultM ) ; throws the below exception . Why ? Why ca n't the method reference access the methods def...
package pkg.a ; @ FunctionalInterfacepublic interface A extends AA { } package pkg.a ; interface AA { default void defaultM ( ) { System.out.println ( m ( ) ) ; } String m ( ) ; } package pkg ; import java.util.Arrays ; import java.util.List ; import pkg.a.A ; public class Test { public static void main ( String [ ] ar...
Why is this method reference failing at runtime but not the corresponding lambda call ?
Java
Reviewing an example use of Optional where the optional is first loaded with a database call and then mapped to a Spring security UserDetails instance . The code looks like this : In the last line would that call equal return new CustomUserDetails ( user.get ( ) ) .Also anyone know if there 's an even shorter more flui...
Optional < User > user = userRepository.findByName ( username ) ; user.orElseThrow ( ( ) - > new UsernameNotFoundException ( `` Ahhh Shuckkkks ! ! ! `` ) ; return user.map ( CustomUserDetails : :new ) .get ( ) ;
Understanding Optional < T > .map ( )
Java
Code : How can I do this in Java ? If I make it as a class field as inSince it is in a thread , it asks me to make the Process P as final . If I make that final , I cant assign value here . p= Runtime.getRuntime ( ) .exec ( my_CMD ) ; . plz help .
main function { Thread t =new Thread ( ) { public void run ( ) { Process p= Runtime.getRuntime ( ) .exec ( my_CMD ) ; } } ; t.start ( ) ; //Now here , I want to kill ( or destroy ) the process p. main function { Process p ; Thread t =new Thread ( ) { public void run ( ) { p= Runtime.getRuntime ( ) .exec ( my_CMD ) ; } ...
How to kill a process which is started by child thread ?
Java
Prior to finding the method Long.numberOfLeadingZeros ( long i ) , I was casting longs to doubles and using Math.getExponent ( double d ) . The idea was to find the double representation of the long , use the exponent to get the highest set bit , and subtract it from 64 to get the number of leading zeros.This mostly wo...
for ( int i = 0 ; i < 64 ; i++ ) { double max = Long.MAX_VALUE > > > i ; double min = Long.MIN_VALUE > > > i ; double neg = -1L > > > i ; System.out.format ( `` Max : % -5d Min : % -5d -1 : % -5d % n '' , Math.getExponent ( dmax ) , Math.getExponent ( dmin ) , Math.getExponent ( dneg ) ) ; } ... Max : 55 Min : 55 -1 : ...
Java - finding leading zeros in a long by conversion to double
Java
Value-based classes have the property that they are final and immutable ( though may contain references to mutable objects ) .Consequently , if you know that your object only contains immutable instances , you could precompute the hashCode of the instance . This could speed up access when using Map or Set operations.Lo...
// copied from Instant # hashCode @ Overridepublic int hashCode ( ) { return ( ( int ) ( seconds ^ ( seconds > > > 32 ) ) ) + 51 * nanos ; }
Precompute hashCode for value-based classes ?
Java
I know that in Java , everything is passed by value . But for objects , it is the value of the reference to the object that is passed . This means that sometimes an object can get changed through a parameter , which is why , I guess , people say , Never modify parameters.But in the following code , something different ...
public class TestClass { static String str = `` Hello World '' ; public static void changeIt ( String s ) { s = `` Good bye world '' ; } public static void main ( String [ ] args ) { changeIt ( str ) ; System.out.println ( str ) ; } }
Pass by `` Reference Value '' ? Some clarification needed
Java
I 've looked at several examples of people creating tile maps , and I am unable to get the tile position where my mouse is pointed at.I am using a spritebatch and GameTile [ ] [ ] to create the map . Keep in mind that the tiles themselves are isometric and not actually a square.The method renderMap ( ) is where the map...
public class MapEditor implements GameScene { private GameContext context ; private SpriteBatch batch ; private OrthographicCamera camera ; public static GameTile [ ] [ ] tiles ; //GameTile.WIDTH = 64 & GameTile.HEIGHT =48 public static final int MAP_WIDTH = 20 ; public static final int MAP_HEIGHT = 36 ; public MapEdit...
Java tile map using Libgdx : finding tile at mouse position
Java
I would like to have a generic and fast parser for dates that comes with random format like:20182018-12-312018/12/312018 dec 31201812311516172018-12-31T15:16:172018-12-31T15:16:17.1234562018-12-31T15:16:17.123456Z2018-12-31T15:16:17.123456 UTC2018-12-31T15:16:17.123456+01:00 ... so many possibilitiesIs there a nice way...
val formatter = new DateTimeFormatterBuilder ( ) .appendPattern ( `` [ yyyy-MM-dd'T'HH : mm : ss ] '' ) .appendPattern ( `` [ yyyy-MM-dd ] '' ) .appendPattern ( `` [ yyyy ] '' ) // add so many things here .parseDefaulting ( ChronoField.MONTH_OF_YEAR , 1 ) .parseDefaulting ( ChronoField.DAY_OF_MONTH , 1 ) .parseDefaulti...
Java or Scala fast way to parse dates with many different formats using java.time
Java
I was trying some Android stuff and learning Kotlin on the way and I was wondering how to initialize Views and properties in general.As far as I understand , the contracts in Kotlin and Java ( `` I will initialize before use '' ) and both UninitializedPropertyAccessException and NullPointerException are more or less eq...
public class Foo { private String bar = null ; public void bar123 ( ) { if ( bar == null ) { bar = `` bar '' ; } } } class Foo { private lateinit var bar : String fun bar123 ( ) { if ( ! : :bar.isInitialized ) { bar = `` bar '' } } }
Advantage of lateinit over null initialization in java ?
Java
I have a bunch of images from sdcard that are load asynchronously on a gridview . Everything works fine , but when accessing a multi select contextual action menu by long clicking in any image the entire activity reloads and all images are loaded again . How to prevent it ? MyadapterContextual action menu codeI appreci...
public class PhotosGridViewImageAdapter extends BaseAdapter { AsyncTaskLoadFiles myAsyncTaskLoadFiles ; public class AsyncTaskLoadFiles extends AsyncTask < Void , String , Void > { File targetDirector ; PhotosGridViewImageAdapter myTaskAdapter ; public AsyncTaskLoadFiles ( PhotosGridViewImageAdapter adapter ) { myTaskA...
Prevent activity to reload when acessing contextual action menu by clicking on a image in async gridview
Java
This snippet of Java code does not result in a compile warning . How can I configure Eclipse to warn in this scenario ? If it matters , I 'm compiling with 1.8 compliance level .
double dd = 1.1 ; int ii = 2 ; ii += dd ; // this is a possible bug
How to configure Eclipse java warning upon int += double
Java
In Bash , if I wanted to iterate through elements of an array in a given order , I could do so like this : Is it possible to do the same ( or relatively the same ) thing in Java ?
for i in 1 3 8 2 5 9 ; do array [ i ] = < some_algorithm_based_value > done
Java - iterate a for loop in a given order
Java
I have a method with the following signature : However I can ’ t call it passing in a Map < String , Set < String > > . For instance , the following doesn ’ t compile : The error message being that : However , if I change to the following all is fine : However I ’ m not at all interested in V , as I just want to know t...
public < T > int numberOfValues ( Map < T , Set < ? > > map ) Map < String , Set < String > > map = new HashMap < > ( ) ; numberOfValues ( map ) ; numberOfValues ( java.util.Map < java.lang.String , java.util.Set < ? > > ) in class can not be applied to ( java.util.Map < java.lang.String , java.util.Set < java.lang.Str...
Why doesn ’ t Map < String , Set < String > > match Map < T , Set < ? > > ?
Java
So I have came across a weird compiling error when using a generic class that has a List ( or Map or Set , etc ) as an attribute.The compiling error occurs while trying to iterate ( using a foreach ) the List : Just to be clear , I know there 's a simple workaround for this problem , but I want to understand what is wr...
Sample.java:11 : error : incompatible types for ( String string : s.getStringList ( ) ) { required : String found : Object import java.util.List ; public class Sample < T > { public List < String > stringList ; public static void main ( String [ ] args ) { Sample s = new Sample ( ) ; // Why this does n't work ? for ( S...
Odd compiling error with generic classes and lists
Java
Imagine you have a menu with dishes each dish should be available in multiple languages ( French , English , Arabic , ... ) . The Dish class contains a list with Language type objects . How do I avoid using instance of when wanting a description of a specific language for that dish ? Should I define for each language a...
class Dish { List < Language > languages void addLanguage ( Language lg ) { ... } } class Language { getDescription ( ) { } } class French extends Language { } class Menu { List < Dish > dishes }
design patterns how to avoid instanceOf when using List
Java
In this code , why can type not be declared as Class < ? extends B > ?
public class Foo < B > { public void doSomething ( B argument ) { Class < ? extends Object > type = argument.getClass ( ) ; } }
Why does n't Class have a nice generic type in this case ?
Java
I was with the similiar topic some time ago . I 'm looking at my app and I think it has a lot of unnecessary code . What I mean is I have service that is responsible for scraping data from different categories of books from two bookstores . Right now I have 5 categories so I have 5 methods , but what if I 'm gon na add...
@ GetMapping ( `` /romances '' ) public Map < Bookstore , List < Book > > get15RomanticBooks ( ) { return categorizedBookService.get15BooksFromRomanceCategory ( ) ; } @ GetMapping ( `` /biographies '' ) public Map < Bookstore , List < Book > > get15BiographiesBooks ( ) { return categorizedBookService.get15BooksFromBiog...
How to get rid of unnecessary ( ? ) code - adjusting to DRY principle
Java
I was trying the following code , I am getting the following output , My question is , why I am not able to assign the list as null inside a called function ?
public void test ( ) { List < Integer > list = new ArrayList < > ( ) ; list.add ( 100 ) ; list.add ( 89 ) ; System.out.println ( list ) ; update1 ( list ) ; System.out.println ( list ) ; update2 ( list ) ; System.out.println ( list ) ; } public void update1 ( List < Integer > list ) { list.remove ( 0 ) ; } public void ...
why null assignment not working in a function
Java
I 'm trying to deploy my Quarkus-app on Heroku . It works fine , but I needed to specify the datasource-parameters with fix values . Because Heroku might rotate this parameters , this is not a really good idea.In Quarkus , I need this 3 parameters in application.properties : Heroku only gives me 1 environment variable ...
quarkus.datasource.usernamequarkus.datasource.passwordquarkus.datasource.jdbc.url
Quarkus datasource with Heroku
Java
Why is this legal : But using an iterator or the syntactic sugar of a for each results in a ConcurrentModificationException : Before everyone starts jumping on the bandwagon telling me to use iterator.remove ( ) ; I 'm asking why the different behavior , not how to avoid the conc mod exception . Thanks .
for ( int i=0 ; i < arr.size ( ) ; i++ ) { arr.remove ( i ) ; } for ( String myString : arr ) { arr.remove ( myString ) ; }
Removing element from list in counted loop vs iterator
Java
I 'm trying to implement this curve as part of the leveling system of a small game I 'm currently working on . The equation is as followsWhich in python can be defined asRunning this function in the Python console returns the values expected . I ported it over to Java , where it takes the form of : However , mysterious...
f ( x ) = -e^- ( ( -log ( 7 ) /100 ) * ( 100-x ) ) +7 f=lambda x : -e**- ( ( -log ( 7 ) /100.0 ) * ( 100-x ) ) +7 public static double f ( float x ) { return ( Math.pow ( -Math.E , - ( ( -Math.log ( 7 ) /100 ) * ( 100-x ) ) ) +7 ) ; }
The equation -e**- ( ( -log ( 7 ) /100.0 ) * ( 100-x ) ) +7 returns NaN
Java
I have this generic function : Recall from the main with this code : I therefore expect ( being listInt an ArrayList of integers ) that the value returned by the function sum is T = Integer and that in this case , give me a conversion error from Double to Integer.The type of the result is instead Double and no error is...
public static < T extends Number > T sum ( List < T > list ) { Number tot = 0 ; for ( Number n : list ) { tot = tot.doubleValue ( ) + n.doubleValue ( ) ; } return ( T ) tot ; } public static void main ( String [ ] args ) { ArrayList < Integer > listInt = new ArrayList < > ( ) ; listInt.add ( 3 ) ; listInt.add ( 5 ) ; l...
Return type of generic method ( Java )
Java
So I went over this block of code several times in a book that I 'm reading : I do n't see any difference between that and the following declaration : Did I miss anything here ? Is there any reason why I should use the long block of code above ? Thanks ,
int [ ] [ ] someArray = new int [ size ] [ ] ; for ( int i=0 ; i < size ; i++ ) someArray [ i ] = new int [ size ] ; int [ ] [ ] someArray = new int [ size ] [ size ] ;
what 's the difference between these blocks of code ?
Java
If we look at the Java standard §14.7 , we see that statements may have label prefixes , e.g . : LabeledStatement : Identifier : StatementIn theory , a label should be able to label any succeeding statement . So , for example , the following compiles accordingly : Intuitively , this also compiles : But the following do...
public class Test { public static void main ( String [ ] args ) { hello : return ; } } public class Test { int i ; public static void main ( String [ ] args ) { Test t = new Test ( ) ; label : t.i = 2 ; } } public class Test { public static void main ( String [ ] args ) { oops : int k = 3 ; } } public class Test { publ...
Java label irregularity ( possible bug ? )
Java
It seems that the actual close ( ) implementation is tucked away somewhere in the hierarchy of base classes and implementations of abstract methods . For example , are you guaranteed that the file descriptor gets released ? Here is the closest thing to what I wanted to know : from DatagramChannelImpl . Can anyone trans...
nd.preClose ( fd ) ; long th ; if ( ( th = readerThread ) ! = 0 ) NativeThread.signal ( th ) ; if ( ( th = writerThread ) ! = 0 ) NativeThread.signal ( th ) ; if ( ! isRegistered ( ) ) kill ( ) ;
How does InputStreamReader.close ( ) work internally ?
Java
I am working on a program where I take RGB values from a portion of an image . I want to remove the darkness in the color and make it bright . What I do is I use Color.RGBtoHSB I then take the brightness channel and set it to the highest value it can be in range then convert the HSB back to RGB . However , when I do th...
System.out.println ( `` Before Conversion : '' ) ; System.out.println ( `` R : `` + rAvg + `` \nG : '' + gAvg + `` \nB : '' + bAvg ) ; Color.RGBtoHSB ( rAvg , gAvg , bAvg , hsv ) ; hsv [ 2 ] = 100 ; //Set to max valueSystem.out.println ( `` H : `` + hsv [ 0 ] * 360 + `` \nS : `` + hsv [ 1 ] * 100 + `` \nV : '' + hsv [ ...
Turning dark color to bright in java
Java
Whilst playing around with solutions for this question , I came up with the following code , which has some compiler warnings . One warning is : Type safety : The expression of type Test.EntityCollection needs unchecked conversion to conform to Test.EntityCollection < Test.Entity > I do n't entirely understand why this...
static class Entity { } static class EntityCollection < E extends Entity > { private EntityCollection ( HashMap < ? , E > map ) { } public static < T extends HashMap < ? , M > , M extends Entity > EntityCollection < M > getInstance ( Class < T > mapType , Class < M > entityType ) throws ReflectiveOperationException { T...
Generic method triggers type safety error - why ?
Java
J. Bloch in his Effective Java suggests we use an enum-based singleton implementation . For instance : This implementation is nice in the case of serialization because enums provide us with the capability of serialization by default ( and we do n't have to be afraid of getting two different instances while deserializin...
public enum Application { INSTANCE ; //methods , fields }
Implementing enum-based singleton
Java
I 've recently started programming in Android and Java in general so please bear with me.I wrote a loop that should , before adding a new name and phone number to a list and hidden array , remove any duplicates it finds right before . Using the current methods I still get constant repeats , and when clicking the button...
List < String > phnnumbers = new ArrayList < String > ( ) ; List < String > names = new ArrayList < String > ( ) ; public void AddAllContacts ( View view ) { try { Cursor phones = getContentResolver ( ) .query ( ContactsContract.CommonDataKinds.Phone.CONTENT_URI , null , null , null , null ) ; while ( phones.moveToNext...
Loop is not catching duplicates and removing them in Android ( Java )
Java
Whenever I make a program I tend to divide different sections in different files , I think it looks more neat that way . To make the problem more concrete say I have this dummy code consisting of four classes , The Alpha and Beta classes communicate with the Gamma . The purpose of the integers is to print out their val...
public class dummy { public static void main ( String [ ] args ) { Alpha a = new Alpha ( ) ; Beta b = new Beta ( ) ; Gamma g = new Gamma ( ) ; int x , y , z , j , k , l , o , p , q ; x = a.getGammaX ( ) ; y = b.getGammaX ( ) ; z = g.getX ( ) ; a.setGammaX ( 1 ) ; j = a.getGammaX ( ) ; k = b.getGammaX ( ) ; l = g.getX (...
Communication between several classes
Java
I am new to Java 8 . I am learning stream API 's reduce method . I am seeing a weird behavior with this code : Output : My question is why combiner function not executing meaning why this line : ... is not executed ?
public class PrdefinedCollectors { public static void main ( String [ ] args ) { Stream < Integer > stream = Stream.of ( 1 , 2 , 3 , 4 , 5 , 6 ) ; List < Integer > dataHolder = new ArrayList < Integer > ( ) ; List < Integer > numbers = stream.reduce ( dataHolder , ( List < Integer > dataStore , Integer data ) - > { Sys...
Why is the reduce combiner function not executed ?
Java
Given the variables : When calling the following method : Using : I get the expected output : But when using : I get : Since strings < - ab and not strings [ 0 ] < - ab.How can I force the compiler to take the ab array as the first value of the strings array , and then having the output : ?
Object [ ] ab = new Object [ ] { `` a '' , `` b '' } ; Object [ ] cd = new Object [ ] { `` c '' , `` d '' } ; public static void m ( Object ... objects ) { System.out.println ( Arrays.asList ( objects ) ) ; } m ( ab , cd ) ; [ [ Ljava.lang.Object ; @ 3e25a5 , [ Ljava.lang.Object ; @ 19821f ] m ( ab ) ; [ a , b ] [ Ljav...
How to make a variatic method take a single array as the first value of the varargs array ?
Java
I have 3 classes , Account , CappedAccount , UserAccount , CappedAccount , and UserAccount both extend Account.Account contains the following : CappedAccount overrides this behavior : UserAccount does n't override any methods from Account , so it does n't need to be stated.My question is , does CappedAccount # add viol...
abstract class Account { ... /** * Attempts to add money to account . */ public void add ( double amount ) { balance += amount ; } } public class CappedAccount extends Account { ... @ Override public void add ( double amount ) { if ( balance + amount > cap ) { // New Precondition return ; } balance += amount ; } }
Is this precondition a violation of the Liskov Substitution Principle
Java
Files.walk is one of the streams that I should close , however , how do I close the stream in code like below ? Is the code below valid or do I need to rewrite it so I have access to the stream to close it ?
List < Path > filesList = Files.walk ( Paths.get ( path ) ) .filter ( Files : :isRegularFile ) .collect ( Collectors.toList ( ) ) ;
How to close implicit Stream in Java ?
Java
I am currently attempting to solve a ProjectEuler problem and I have got everything down , except the speed . I am almost certain the reason the program executes so slowly is due to the nested loops . I would love some advice on how to speed this up . I am a novice programmer , so I am not familiar with a lot of the mo...
public class Problem12 { public static void main ( String [ ] args ) { int num ; for ( int i = 1 ; i < 15000 ; i++ ) { num = i * ( i + 1 ) / 2 ; int counter = 0 ; for ( int x = 1 ; x < = num ; x++ ) { if ( num % x == 0 ) { counter++ ; } } System.out.println ( `` [ `` + i + `` ] - `` + num + `` is divisible by `` + coun...
How would I speed up this program ?
Java
Is there any difference between initialization via : vs initialization via : Is there any reason why one would want to use the former over the latter ? I see a lot of the former ; I 'm not sure if it 's just because that 's what people are used to , or there 's a reason you 'd want to write it that way .
MyWrapper < String > wrapper = new MyWrapper < String > ( ) ; MyWrapper < String > wrapper = new MyWrapper < > ( ) ;
Is there a difference between explicitly putting the type into the diamond operator vs letting java figure it out ?
Java
I tried to do this code-golf challenge in Java 7 . Just for anyone that does n't know : code-golf is to complete a certain task in as few bytes as possible . Obviously Java is n't a suitable programming language to do this in , especially with languages like Jelly ; 05AB1E ; Pyth ; and alike who complete tasks in 1-15 ...
import java.util . * ; String c ( int y ) { String r= '' '' ; Calendar c=Calendar.getInstance ( ) ; c.set ( 1 , y ) ; c.set ( 2,0 ) ; for ( int i=0 ; i++ < 11 ; c.add ( 2,1 ) ) { c.set ( 5 , c.getActualMaximum ( 5 ) ) ; if ( c.get ( 7 ) ==2 ) r+=i+ '' `` ; } return r ; } import java.util . * ; class M { static String c...
Calendar giving unexpected results for year 1
Java
I have an arraylist of multiple arraylists like-the arraylist contains the elements : Now i want to sort the main arraylist . Main arraylist contains 5 inner arraylists.Now the sorting must be like the 7th element of every inner arraylist is compared which is integer and inner arraylists are arranged accorting to the v...
ArrayList < ArrayList < String > > al1=new ArrayList < ArrayList < String > > ( ) ; [ [ Total for all Journals , IOP , IOPscience , , , , , 86 , 16 , 70 , 17 , 8 , 14 , 6 , 17 , 19 , 5 ] , [ 2D Materials , IOP , IOPscience , 10.1088/issn.2053-1583 , 2053-1583 , , 2053-1583 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] , [ ...
Sorting of arraylist of multiple arraylists
Java
Well , I 've got such a code : I do n't know how ( fully or partially ) and when classes are loaded . So : Test t ; - it is not an active usage , but the reference t must be a definite type of . Was Test class loaded ( maybe partially , then how many stages - loading\linking\initializing - it passed ) or nothing happen...
public class Main { public static void main ( String [ ] args ) { Test t ; //1 Integer i = new Integer ( 1 ) ; //2 t = new Test ( ) ; //3 System.out.println ( Test4.a ) ; //4 } } class Test { private int a = 10 ; private Test2 t2 ; //5 List < Test2 > list = new ArrayList < Test2 > ( ) { { for ( int i = 0 ; i < a ; i++ ...
When classes are loaded ?
Java
I wrote a method to calculate how long ago a father was twice as old as his son and in how many years from now this would be true . Unexpectedly , it returns `` -2 years ago '' for an 8-year-old father and a 3-year-old son . Equally unexpectedly , it returns `` -1 years from now '' for a 3-year-old father and a 2-year-...
public class TwiceAsOld { public static void twiceAsOld ( int currentFathersAge , int currentSonsAge ) { int yearsAgo ; int yearsFromNow ; int pastFathersAge = currentFathersAge ; int pastSonsAge = currentSonsAge ; int futureFathersAge = currentFathersAge ; int futureSonsAge = currentSonsAge ; for ( yearsAgo = 0 ; past...
What would cause a for loop to decrement when it 's supposed to increment ?
Java
JDK 8 on mac OS , looking at following code from HashMap.java : Any changes to the returned ks will reflect in keySet as they always point to the same underlying set , if this is true , can it be written as : Are the two code snippets behave equivalent ? If so , why HashMap uses the first variation rather than the seco...
public Set < K > keySet ( ) { Set < K > ks = keySet ; if ( ks == null ) { ks = new KeySet ( ) ; keySet = ks ; } return ks ; } public Set < K > keySet ( ) { if ( keySet == null ) { keySet = new KeySet ( ) ; } return keySet ; }
keySet ( ) method in HashMap could be terser
Java
I was asked the following question on an interview . Given the following code , if methods add and doAction are being invoked by multiple threads , how can we get a NullPointerException when printing toString ? **Cut out all other multithread concerns .
public class Test { private List < Object > obj = new ArrayList < Object > ( ) ; public void add ( Object o ) { obj.add ( o ) ; } public void doAction ( ) { for ( Object o : obj ) { System.out.println ( o.toString ( ) ) ; // maybe NPE , why ? } } }
How can we get NPE , race condition
Java
With the following definitions : Why does BaseServiceImpl.class.getDeclaredMethods ( ) return 2 methods : public java.lang.Object BaseServiceImpl.findOne ( java.io.Serializable ) public java.lang.Object BaseServiceImpl.findOne ( java.lang.Object ) Is there a way to filter these out ?
public interface BaseService < T , ID > { T findOne ( ID id ) ; } public class BaseServiceImpl < T , ID extends Serializable > implements BaseService < T , ID > { @ Override public T findOne ( ID id ) { return null ; } }
Why does Java claim there 's 2 declared methods when bounded generics are involved ?
Java
I am trying to write a Hadoop mapper class in Scala . As a starting point , I have taken a Java example from the book `` Hadoop : the Definitive Guide '' and tried to port it to Scala.The original Java class extends org.apache.hadoop.mapreduce.Mapper : and overrides the methodThis methods gets called and works properly...
public class MaxTemperatureMapper extends Mapper < LongWritable , Text , Text , IntWritable > public void map ( LongWritable key , Text value , Context context ) throws IOException , InterruptedException class MaxTemperatureMapperS extends Mapper [ LongWritable , Text , Text , IntWritable ] @ throws ( classOf [ IOExcep...
Scala class inheriting from a Java generic class
Java
I am doing a static import of members of class Long and Integer : Now if I am trying to use this variable MAX_VALUE and print it I will get an error : This is fine . To remove the error i will have to remove one static import to resolve this ambiguity . The main issue I am getting is , if I use wildcard * with Integer ...
import static java.lang.Integer.MAX_VALUE ; import static java.lang.Long.MAX_VALUE ; import static java.lang.Integer.MAX_VALUE ; import static java.lang.Long.MAX_VALUE ; public class StaticImportDemo2 { public static void main ( String [ ] args ) { //Error : : The field MAX_VALUE is ambiguous System.out.println ( `` Pr...
Static import with same static variable names
Java
Take a look at following code : I am not able to understand this behavior.. ? I was hoping the first eval to be true as well..And that is what I am expecting..
Long minima = -9223372036854775808L ; Long anotherminima = -9223372036854775808L ; System.out.println ( minima==anotherminima ) ; //evaluates to false System.out.println ( Long.MIN_VALUE ) ; Long another= 1L ; Long one = 1L ; System.out.println ( another == one ) ; //evaluates to true
Weird equality behavior in java