lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have below codeIs there a clear way to handle p ! =null , p2 ! =null , p1 ! =null . I can add p , p1 , p2 to a list and iterate through it as below but I was looking for a cheaper way than adding products to list and then iterating through them. ? Also , I would like to if checking for null each time is expensive tha...
Set < Product > getallProducts ( ) { Product p = getProduct ( brand , price ) ; Product p1 = getProduct ( brand , price , location ) ; Product p2 = getProduct ( brand , price , qty ) ; Set < SuperProducts > superProducts = new HashSet < > ; if ( p ! =null ) { SuperProduct sp = getSuperProduct ( p ) superProducts.add ( ...
Is there a better way of handling multiple null checks in Java ?
Java
I have an abstract class which is defined as : I do n't wan na use question mark ( ? ) and use some generic variable as like T or U . How can I do that ?
public abstract class BaseClass < T extends FirstClass , U extends BaseAnother < ? extends SecondClass > > {
Nested Generic Type Parameters Parameters
Java
Consider the following code : In this code , a non-comparable object is first added to a PriorityQueue . This code works fine , as already answered here.Then , a second object is added to this queue . As expected per PriorityQueue.add Javadoc , a ClassCastException is thrown because the second object is not comparable ...
import java.util.PriorityQueue ; public class Test { public static void main ( String argv [ ] ) { PriorityQueue < A > queue = new PriorityQueue < > ( ) ; System.out.println ( `` Size of queue is `` + queue.size ( ) ) ; // prints 0 queue.add ( new A ( ) ) ; // does not throw an exception try { queue.add ( new A ( ) ) ;...
Size of PriorityQueue increases when non-comparable objects are added
Java
Following are the outputs when I try to run the code in eclipse multiple times . I believed so far that whenever the last line of the code from either try/catch block is about to be executed ( which could be return or throws new Exception ( ) type of stmt ) , finally block will be executed , but here the output differe...
class TestExceptions { public static void main ( String [ ] args ) throws Exception { try { System.out.println ( `` try '' ) ; throw new Exception ( ) ; } catch ( Exception e ) { System.out.println ( `` catch '' ) ; throw new RuntimeException ( ) ; } finally { System.out.println ( `` finally '' ) ; } } } trycatchExcept...
Why is Output different every time ? try catch finally exception code
Java
First thing , I know many people have asked same thing , but this one is nearly same but I have few more questions.I have an image of 48px x 48px , so if I set this image in ImageView with then image looks bigger but if I use following fixed size , it gets smallerI think it 's now showing properly ( not pixelated ? ) w...
layout_width= '' wrap_content '' layout_height= '' wrap_content '' layout_width= '' 48dp '' layout_height= '' 48dp ''
ImageView , why different size ?
Java
I 'm studying up for the SCJP exam , upon doing some mock tests I came across this one : It asks what is the output of the following : I thought it would be 21 20 , since t.i would invoke getInt , which then increments k to make 21.However , the answer is 1 20 . I do n't understand why it would be 1 , can anyone shed s...
class TestClass { int i = getInt ( ) ; int k = 20 ; public int getInt ( ) { return k+1 ; } public static void main ( String [ ] args ) { TestClass t = new TestClass ( ) ; System.out.println ( t.i+ '' `` +t.k ) ; } }
Confused over initialisation of instance variables
Java
In the following example that uses JDBC ( this question though is not specific to JDBC ) : If I do not initialize the conn to null then the compiler complains that in the catch block I can not use a reference that has not been initialized . Java by default initializes a object reference to null then why do I need to ex...
Connection conn = null ; try { ... .. Do the normal JDBC thing here ... . } catch ( SQLException se ) { if ( conn ! = null ) { conn.close ( ) ; } }
Why Initializing References to Null Is allowed In Java ?
Java
My maths says the following Java program would need approx 8GB ( 2147483645 * 4 bytes ) of RAM : This is backed up by observing the program when running : But unless you set the max heap to around 12.5GB , the program fails to start : Can understand the need for a bit of wiggle-room but why do we need so much ?
package foo ; public class Foo { public static void main ( String [ ] args ) throws Exception { int [ ] arr = new int [ Integer.MAX_VALUE-2 ] ; Thread.sleep ( 500000L ) ; } } $ java -Xmx12000m -cp ./ foo.FooException in thread `` main '' java.lang.OutOfMemoryError : Java heap space at foo.Foo.main ( Foo.java:5 ) $ java...
Java heap - bigger than it needs to be
Java
I need help on this code I seem to have a problem regarding on summing the even numbers , what I want to happen is that the even numbers will be outputted and at the same time there will be an output where all the even numbers are summed within the inputted range of the user . I am just a beginner at coding and I hope ...
import java.util . * ; public class Loop { //Start public static void main ( String args [ ] ) { Scanner console = new Scanner ( System.in ) ; System.out.println ( `` Enter Start Number '' ) ; int start =console.nextInt ( ) ; System.out.println ( `` Enter End Number '' ) ; int end =console.nextInt ( ) ; int sum = 0 ; S...
How To Sum The Even Numbers Using Loop
Java
Is there any built-in Java6 method ( perhaps in lang or reflection ? ) for performing : Which takes an Object array and returns an array containing the type of each element ?
private Class [ ] getTypes ( final Object [ ] objects ) { final Class [ ] types = new Class [ objects.length ] ; for ( int i = 0 ; i < objects.length ; i++ ) { types [ i ] = objects [ i ] .getClass ( ) ; } return types ; }
Object [ ] to Class [ ] in Java
Java
I found a mysterious problem with a Java code for homework . A friend program an application which this at the beginning : The boolean 'end ' is false while all the execution and when the user quits the application this happens : The println shows like the value of 'end ' changes to true and logically in my friend 's c...
public void run ( ) { vm.setVisible ( true ) ; while ( ! end ) ; System.out.println ( `` Finish '' ) ; vm.setVisible ( false ) ; } private class CloseSys implements ActionListener { public CloseSys ( ) { super ( ) ; } public void actionPerformed ( ActionEvent e ) { System.out.println ( `` CLOSE SYS '' ) ; System.out.pr...
Java does n't break a while when runs in Linux
Java
The following program on IntelliJ warns me `` Condition ' i < = 2 ' is always 'true ' '' . If I replace the condition with i > 2 , I get `` Condition ' i > 2 ' is always 'false ' '' . Same with i == 2.But if I replace it with i > = 2 I do n't have any warnings.Why in the last case IntelliJ does not warn me that this co...
public static void main ( String [ ] args ) { int i = 0 ; if ( i < = 2 ) { System.out.println ( `` ok '' ) ; } }
IntelliJ - Warning message does not appear for the condition i > = 2 when i is known
Java
I Have an ArrayList < String > that I use to store PackageInfo ( an example of an element in the arraylist is `` com.skype.raider '' ) .The arralist is initialized as follows : And In The Class ConsturctorWhen i invoke pkgs.remove ( String ) , it does n't work , but when i repeatedly try and remove , it eventually work...
private List < String > pkgs ; pkgs = new ArrayList < > ( ) ; private void togglePackage ( String selectedPackage , CheckBox chk_app ) { String m_pkg = selectedPackage.toString ( ) ; //redundant .toString ( ) boolean checked = ! chk_app.isChecked ( ) ; //checkbox boolean toggle if ( checked & & ! pkgs.contains ( m_pkg ...
ArrayList.Remove does not work the first time invoked
Java
Two Main Problems to solve:1 ) Type check is lostUsing the array argument Single.zip ( ) version I lose the strongly typed arguments.2 ) Source argument Can not be NullableI can not send nullable source values as argument of Single.zip ( ) function3 ) I want an alternative to the method taking an Object [ ] not typed :...
public static < T , R > Single < R > zipArray ( Function < ? super Object [ ] , ? extends R > zipper , SingleSource < ? extends T > ... sources ) ... f < $ > a1 < * > a2 < * > a3 < * > a4 < * > a5 < * > a6 < * > a7 < * > a8 < * > a9 < * > a10 < * > a11 public static < T1 , T2 , R > Single < R > zip ( SingleSource < ? e...
How can I generalize the arity of rxjava2 Zip function ( from Single/Observable ) to n Nullable arguments without lose its types ?
Java
I want to use Java 's stream API to do some calculations on a list of objects : List < Item > .stream ( ) ... The Item class contains many attributes . For some of those I need to take the average value across all items in the collection , for other attributes I need to do other forms of calculations . I have been doin...
ItemCalculation itemCalculation = ItemCalculation.builder ( ) .amountOfItems ( itemList.size ( ) ) .averagePrice ( itemList.stream ( ) .mapToDouble ( item - > item.getPrice ( ) ) .average ( ) .getAsDouble ( ) ) .averageInvestmentValue ( itemList.stream ( ) .mapToDouble ( item - > getTotalInvestmentValue ( item.getInves...
Combining multiple java streams in a structured way
Java
I have written a basic code in Thread and the output which i got is pretty surprising.The output here i am expecting is that it will be printCurrent Thread : Thread [ main,5 , main ] Current Thread : Thread [ Fred,5 , main ] Current Thread : Thread [ main,5 , main ] This result i can understand , that there is only one...
public class ThreadImp implements Runnable { public static void main ( String [ ] args ) { ThreadImp threadImp = new ThreadImp ( ) ; Thread t =new Thread ( threadImp ) ; t.setName ( `` Fred '' ) ; t.start ( ) ; threadImp.run ( ) ; t.run ( ) ; } public void run ( ) { System.out.println ( `` Current Thread : `` + Thread....
Little confused on the thread behaviour
Java
i 've got this question on interview : Can you explain : why ? I have no suggestions .
public Integer v1 = 127 ; public Integer v2 = 127 ; public Integer v3 = 513 ; public Integer v4 = 513 ; public void operatorEquals ( ) { if ( v1==v2 ) System.out.println ( `` v1 == v2 '' ) ; else throw new RuntimeException ( `` v1 ! = v2 '' ) ; if ( v3==v4 ) System.out.println ( `` v3 == v4 '' ) ; else throw new Runtim...
Integer 's specific ( Java Core )
Java
The problem is related to integration between Java and Scala . I have simplified it a little bit to make things clearer . I have two classes written in Java : In Java I have a method that uses the classes in the following way : I would like to do the same thing in scala . But the code below does n't compile.The message...
class A < T > { } class AT extends A < Boolean > { } public A < Boolean > a ( ) { return new AT ( ) ; } def a ( ) : A [ Boolean ] = { return new AT ( ) ; }
can not implicitly cast A [ T ] to AT , where A [ T ] extends AT
Java
Ending a turn-based game that allows one action per turn is fairly trivial - you can just have a boolean value update when various win or loss conditions are met , and check the boolean 's value every time you loop through a turn to figure out when the game ends.The game I 'm writing , however , involves more complex t...
public static void main ( String [ ] args ) { Game game = new Game ( 2 , Difficulty.NOVICE ) ; game.run ( ) ; while ( game.getGameState ( ) == State.INCOMPLETE ) { //Hold while waiting for game to complete . } } public class Game extends Thread { public void checkState ( ) { //Let 's presume a win condition was thrown ...
Instantly ending a game with complex turns
Java
I am sure this must have been asked before but I can not seem to find a similar example . I understand well polymorphism and method overloading , but here is a seemingly simple scenario with a solution that escapes me : let 's say I have a base class with several derived classes . I will use shapes for this exampleetc....
base Shapederived Circle extends Shapederived LineSeg extends Shape Circle.intersect ( LineSeg ) Circle.intersect ( Circle ) LineSeg.intersect ( Circle ) for some shape sForeach shape in Shapes if ( s.intersect ( shape ) ) - do something
polymorphism-like handling of parameters - simple OO ?
Java
Can you please explain what 's going in the last 2 print statements ? That 's where I get lost .
public class Something { public static void main ( String [ ] args ) { char whatever = '\u0041 ' ; System.out.println ( '\u0041 ' ) ; //prints A as expected System.out.println ( ++whatever ) ; //prints B as expected System.out.println ( '\u0041 ' + 1 ) ; //prints 66 I understand the unicode of 1 adds up the //unicode r...
Why I am returning integers instead of characters in the 3rd and 4th print statement ?
Java
i know why a can not be cast to B , because of B is not inherit from A.my question is about , why B b1 = ( B ) i ; is allowed since B is not implements from I ? and why B b1 = ( B ) i ; this line will not force a runtime exception since i is null ?
interface I { } class A { } class B { } public class Test { public static void main ( String args [ ] ) { A a = null ; B b = ( B ) a ; // error : inconvertible types I i = null ; B b1 = ( B ) i ; } }
explain this output about Object reference casting ?
Java
Since private methods are implicitly final.private or static or final methods are early bind means they ca n't be overridden.But in my code it is actually running properly.Also I want to make sure what the benefit is of making a private member static , besides the fact that you can use class-name.member , over a non-st...
public class B extends A { public static void main ( String [ ] args ) { new B ( ) .privateMethod ( ) ; //no error -output B-privateMethod . } private void privateMethod ( ) { System.out.println ( `` B-privateMethod . `` ) ; } } class A { private void privateMethod ( ) { System.out.println ( `` A-privateMethod . `` ) ;...
when should make private member to static , and how is this being override in my case
Java
I come from the Java world , so to me it 's all object.foo ( ) , but in Objective C , is object messaging the only way to invoke a method ?
[ object foo ] ;
Syntax for invoking a method in Objective C ?
Java
I am using the Google Natural Language API to analyze entities from different texts . Is there a way to change the language of the input text to , for example english , as it is the case with the AlchemyAPI withthanks
service.setLanguage ( LanguageSelection.ENGLISH ) ;
Google Natural Language API with Java - setLanguage
Java
I 'm running a spark job on Dataproc which reads lots of files from a bucket and consolidates them to one big file . I 'm using google-api-services-storage 1.29.0 by shading it . Until now it worked fine , consolidating ~20-30K files . Today I tried it with about 5 times as many files and suddenly I 'm getting a deadlo...
org.conscrypt.NativeCrypto.SSL_read ( Native Method ) org.conscrypt.NativeSsl.read ( NativeSsl.java:416 ) org.conscrypt.ConscryptFileDescriptorSocket $ SSLInputStream.read ( ConscryptFileDescriptorSocket.java:547 ) = > holding Monitor ( java.lang.Object @ 1638155334 } ) java.io.BufferedInputStream.fill ( BufferedInputS...
Deadlock in Google Storage API
Java
I am struggling with the following riddle of my coworker : This outputs true . I am little bit surprised because it looks like s1 is interned . But this is no constant expression , is n't it ? But then I am even more surprised why the following prints false.Why does the introduction of s3 change the output ?
public class App1 { public static void main ( String [ ] args ) { String s1 = `` Ja '' .concat ( `` va '' ) ; // seems to be interned ? ! String s2 = s1.intern ( ) ; System.out.println ( s1 == s2 ) ; // true } } public class App2 { public static void main ( String [ ] args ) { String s1 = `` Ja '' .concat ( `` va '' ) ...
String interning riddle
Java
There are a bunch of questions where people have realized that creating a method reference with an expression that evaluates to a null value will result in a NullPointerException . As an example : This is due to the following paragraph in the java specification : First , if the method reference expression begins with a...
String s = null ; Supplier < char [ ] > fun = s : :toCharArray ; public static char [ ] callback ( Supplier < char [ ] > supplier ) { return supplier.get ( ) ; } public static void main ( String [ ] args ) { String s = null ; callback ( s : :toCharArray ) ; }
What is the reason behind null checks in method reference expression evaluation ?
Java
Eclipse 4 gives a warning which says the stmt may potentially not be closed and cause a resource leak : Under which circumstance would that happen ?
class Test { public void test ( ) { PreparedStatement stmt = null ; try { stmt = HibernateSession.instance ( ) .connection ( ) .prepareStatement ( `` '' ) ; } catch ( final SQLException e ) { e.printStackTrace ( ) ; } finally { if ( stmt ! = null ) try { stmt.close ( ) ; } catch ( final SQLException e ) { e.printStackT...
Under which circumstance would this resource be leaking ?
Java
I have two snippets , one in Java and one in c # .the Java snippet returns 7101.674and in c # produces a result of 7103.674.why am I off by 2 and what is correct ?
float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; long e = 1234L ; int f = 0xa ; int g = 014 ; char h = ' Z ' ; char ia = ' ' ; byte j = 123 ; short k = 4321 ; System.out.println ( a+b+ca+d+e+f+g+h+ia+j+k ) ; float a = 1234e-3f ; float b = 1.23f ; float ca = 1.234e3f ; float d = 43.21f ; l...
why does java and c # differ in simple Addition
Java
DescribtionIm working on a little java game server ... in order to update and save the game in another thread , im forced to deep clone some of my entities . Otherwhise a internal hibernate exception occurs : `` ConcurrentModificationException '' when updating my entities So my flow currently looks like this : Mark gam...
// Run the database operation for updating the entities async in a new thread , return updated entities once done return CompletableFuture.runAsync ( ( ) - > { var session = database.openSession ( ) ; session.beginTransaction ( ) ; try { // Save entities for ( var entity : entities ) session.update ( entity ) ; session...
How do we update a deep cloned entity ?
Java
toArray method hides < E > passed to Collection < E > interface . Below is the method signature.Because of which below is possible . And results into ArrayStoreExceptionI wanted to know why was such decision taken ? Why was such a case allowed while designing the API ? As anyway this code results in to RuntimeException...
< T > T [ ] toArray ( T [ ] a ) ; ArrayList < String > string = new ArrayList < String > ( ) ; string.add ( `` 1 '' ) ; string.add ( `` 2 '' ) ; Integer intArray [ ] = new Integer [ 2 ] ; intArray = string.toArray ( intArray ) ;
Why < T > for toArray hides < E > of Collection < E > ?
Java
I 'm trying to write a regex that matches either \ or /.No matter in what order I write it : or It is somehow escaping either my square bracket or my forward slash . What 's the correct way of showing this particular case ?
[ //\ ] [ /\\ ]
Writing : [ \/ ] ( \ or / regex ) correctly ?
Java
So , basically i have two Arrays : and I want to fill in a new array ( listD ) all elements of listA that are missing from listB.The output should be like this : Output : 2 , -5 , -121 , 102 , -35 , 0 , -125 , 802 , -10My code is the following : I then use the following for loop to run trough both arrays and check if t...
int [ ] listA = { 2 , -5 , -121 , 102 , -35 , -2 , 0 , -125 , 802 , -10 } ; int [ ] listB = { 6 , 99 , -1 , 12 , 1 , -2 } ; int arraySize = 0 ; //Variable to determine size of the new array ; int difElements = 0 ; //Variable to count every different element ; for ( int i = 0 ; i < listA.length ; i++ ) { for ( int j = 0...
Fill an new array with elements of array A that are missing form array B - Java
Java
Problem : Given two Collection < ? > s , check if both contain the same elements.Assuming that the actual implementation of the collection is unknownAssuming that the elements do not occur in the same orderAssuming that no element does occur twice in the same collectionSolution 1 : Solution 2 : I would assume Solution ...
boolean equals = c1.containsAll ( c2 ) & & c2.containsAll ( c1 ) ; boolean equals = new HashSet < ? > ( c1 ) .equals ( new HashSet < ? > ( c2 ) ) ;
Performance of element-compare in java collections
Java
Consider the following situation : This is a situation where three resources have been created inside try resources : a Connection , a Statement , and a ResultSet.What will happen to these three resources after the try block ends ? Will they all be closed , even if they have n't any reference to them , or will only the...
try ( ResultSet resultSet = DriverManager.getConnection ( `` jdbc : ... '' , `` user '' , `` pass '' ) .createStatement ( ) .executeQuery ( sql ) ) { . . . }
Using `` try with resources '' for resources created without any reference
Java
So , I am trying to store 3 longs to a file , but it will a lot of data so I convert them to byte arrays and save them . My current method for saving them : longToBytes method : The byte array gets saved to the file , but the first byte gets truncated . the print statement in longToByes prints 8 three times.The origina...
try ( FileOutputStream output = new FileOutputStream ( path , true ) ) { //Put the data into my format byte [ ] data = new byte [ 24 ] ; main.getLogger ( ) .log ( Level.INFO , `` Saving most sig bits '' ) ; System.arraycopy ( ByteUtils.longToBytes ( uuid.getMostSignificantBits ( ) ) , 0 , data , 0 , 8 ) ; System.arrayc...
byte getting read wrong from file ?
Java
A simple swing application draws two independent JDialogs , that contains different JEditorPanes with different html content . In one JEditorPane we use css rules to set borders of table visible . But another JEditorPane uses the same css rules and draws 3px table border as well , but it should n't ( we do not set it e...
public static void main ( String args [ ] ) { String text1 = `` < html > < body > < table > < tr > < td > somthing ONE < /td > < /tr > < /table > < /body > < /html > '' ; String text2 = `` < html > < body > < table > < tr > < td > somthing TWO < /td > < /tr > < /table > < /body > < /html > '' ; JDialog jd = new JDialog...
Different JEditorPanes show html content , using the same css rules
Java
The standard Collector summingInt internally creates an array of length one : I was wondering if it is n't possible to just define : This however does n't work since the accumulator just seems to be ignored . Can anyone explain this behaviour ?
public static < T > Collector < T , ? , Integer > summingInt ( ToIntFunction < ? super T > mapper ) { return new CollectorImpl < > ( ( ) - > new int [ 1 ] , ( a , t ) - > { a [ 0 ] += mapper.applyAsInt ( t ) ; } , ( a , b ) - > { a [ 0 ] += b [ 0 ] ; return a ; } , a - > a [ 0 ] , CH_NOID ) ; } private < T > Collector ...
java.util.stream.Collectors : Why is the summingInt implemented with an array ?
Java
I 've following code ( simplified to focus on issue ) . That prints the timezone information using SimpleDateFormat pattern.Do you know why z is treated differently on different machines ? And if there is a way to tell Java to treat it uniformly across all the machines ? This class is being used in JavaMail and that is...
import java.text.SimpleDateFormat ; import java.util.Calendar ; public class DateFormatTest { String PATTERN = `` z '' ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat ( this.PATTERN ) ; public static void main ( final String [ ] args ) { new DateFormatTest ( ) .printTimezone ( ) ; } public void printTimezone...
Java SimpleDateFormat interprets ' z ' differently on different OS
Java
I recently use this code , and realize that in anonymous class , I ca n't access the instance by .this , like this : I know how to solve it ( just declare a `` me '' variable ) , but I need to know why I ca n't use < Class > .this ?
Sprite sprFace = new Sprite ( ) { @ Override protected void onManagedUpdate ( float pSecondElapsed ) { runOnUpdateThread ( new Runnable ( ) { @ Override protected void run ( ) { Sprite.this.getParent ( ) .detach ( Sprite.this ) ; // Here } } ) ; } } ;
Why ca n't I use < Class > .this in anonymous class ?
Java
I have the following program that fails to compile : Just block 1 compiles fine and works as expected - I can conditionally select an object and call a method on it inline.Just block 2 also compiles fine and works as expected - I can conditionally assign a method reference to a Supplier < String > variable and call .ge...
Lambda.java:31 : error : method reference not expected here String res = ( ( Supplier < String > ) ( args.length > 0 ? Lambda : :foo : Lambda : :bar ) ) .get ( ) ; ^Lambda.java:31 : error : method reference not expected here String res = ( ( Supplier < String > ) ( args.length > 0 ? Lambda : :foo : Lambda : :bar ) ) .g...
Call method on chosen method reference inline
Java
Is it possible for Java application to know the its own current directory . I am referring to result of pwd.For instance , when executed
~/Documents/workspace/Project/bin $ java com/foo/bar/baz/Runner files/text1.txt program should know ~/Documents/workspace/Project/bin~/Documents/workspace/Project $ java com/foo/bar/baz/Runner files/text1.txt program should know ~/Documents/workspace/Project
Can Java program know its current directory ?
Java
Consider the following returnsNull function and a call to it with a generic type : The Eclipse compiler , when set to Java 8 , accepts it , but javac in Java 8 rejects it with : The underlying difference seems to be that given a two parameterized types P1 < T > and P2 < T > , Eclipse allows conversion from the outer ty...
public static < T > List < T > returnNull ( Class < ? extends T > clazz ) { return null ; } public static void main ( String [ ] args ) { List < AtomicReference < ? > > l = returnNull ( AtomicReference.class ) ; } incompatible types : can not infer type-variable ( s ) T ( argument mismatch ; java.lang.Class < java.util...
Eclipse ECJ accepts this code , javac does n't - who is right ?
Java
In Java 8 time API , you can create a LocalDateTime which falls in the overlap of time during the DST time change in autumn ( Central European Time ) .You can convert this to a ZonedDateTime which represents a precise moment in time using a ZoneId . Doing this does not actually resolve the ambiguity - there could still...
@ Testpublic void TimeSetOnDST ( ) throws Exception { LocalDateTime time = LocalDateTime.of ( 2016 , 10 , 30 , 2 , 30 ) ; // in the DST time overlap ZonedDateTime of = ZonedDateTime.of ( time , ZoneId.of ( `` Europe/Zurich '' ) ) ; System.out.println ( of ) ; // 2016-10-30T02:30+02:00 [ Europe/Zurich ] // But why not 2...
How does Java 8 time api choose the offset on DST change period
Java
In my project recently I 've encountered code that compiles perfectly fine , however is very surprising to any reader and should not pass static analysis.We use Checkstyle , PMD , ErrorProne and SonarLint but none of these tools complains on such construct . Is there any rule that could be enabled or tool that can be u...
class BracketsAfterMethodSignature { Object emptyArray ( ) [ ] { return new Object [ ] { } ; } }
Prohibit brackets after method signature in Java code
Java
I have 8 files . Each one of them is about 1.7 GB . I 'm reading those files into a byte array and that operation is fast enough.Each file is then read as follow : When processed using a single core in a sequential sense it takes abour 60 seconds to complete . However , when distributing the computation over 8 separate...
BufferedReader br=new BufferedReader ( new InputStreamReader ( new ByteArrayInputStream ( data ) ) ) ; byte [ ] content=org.apache.commons.io.FileUtils.readFileToByteArray ( new File ( filePath ) ) ; For each file read the file into a byte [ ] add the byte [ ] to a listend ForFor each item in the list create a thread a...
BufferedReader in a multi-core environment
Java
I have two constructors that compile just fine but I 'd expect Java to complain about the possibility of ambiguity.What gives ?
public Foo ( int id , Bar bar , String name , String description ) { } public Foo ( int id , Bar bar , String ... values ) { }
Variable argument constructor _may_ conflict , but compiles
Java
I have written a piece of framework that adds the possibility for type-safe invocations of its interface . Now , when writing the JUnit tests , I want to show that specific expressions that earlier led to runtime errors are checked by the compiler now.Probably it 'd be best to simply comment that code out and leave it ...
// this does not compile , because nameProp is of type Property < String > Integer name = interface.getProperty ( nameProp ) ; assertCompilationError ( ) { Integer name = interface.getProperty ( nameProp ) ; }
How to assert that an expression does not compile
Java
I am looking for a way to search for a subsequence in a given sequence that sums up to a given number ( sum , here 4 ) with a lexicographical priority.Take for instance the following example : Different subsequences can sum up to 4 . For instance 1,2,1 , 2,2 2,1,1 . In case multiple of such sequences exists , the lexic...
1,2,2,4,1,1
Grouping a squence is subsequences with a given sum with lexicographical priority
Java
Currently I try to store some news from a web api with the help of JPA.I have 3 entities i need to store : Webpage , NewsPost and the Query that returned the news post . I have one table for each of the three . My simpliefied JPA entities looking like the following ones : Currently I 'm doing the following : I create t...
@ Entity @ Data @ Table ( name = `` NewsPosts '' , schema = `` data '' ) @ EqualsAndHashCode @ NoArgsConstructor @ AllArgsConstructor @ Builderpublic class NewsPost { @ Id @ Column ( name = `` id '' ) private long id ; @ Basic @ Column ( name = `` subject '' ) private String subject ; @ Basic @ Column ( name = `` post_...
JPA starts to consume more and more memory after each iteration
Java
So here is the situation : I need to register people 's vote for certain dates . In short , a date is proposed and people vote for the date they want.The data structure is the following : A vote is : Where VoteType is just an enum : Now I already made a stream that returns the amount of votes for the availability ( Vot...
private HashMap < LocalDateTime , Set < Vote > > votes ; public class Vote { private String name ; private VoteType vote ; public Vote ( String name , VoteType vote ) { super ( ) ; this.name = name ; this.vote = vote ; } } public enum VoteType { YES , NO , MAYBE } public Map < LocalDateTime , Integer > voteCount ( Vote...
Getting the Set with the most elements nested in a HashMap using Java Streams
Java
I 'm looking to create a test application which can check various flight information from an airline providerI 'm struggling with the concept of classes and methods and which ones to create.My current thought process is as follows : The data is downloaded from a website , due to the size of data , I only want to downlo...
BritishAirwaysFlightData ( ) BritishAirwaysFlightData // Used to download the BA Flight database and store in the object ( Assumging his is only small i.e . 500kb ) getStartDate ( String source_airport , String dest_airport ) // Takes source and destination airport and return date when flights startgetEndDate ( String ...
Which Classes Methods to create ?
Java
I use this technique frequently but I 'm not sure what to call it . I call it associative enums . Is that correct ? Example :
public enum Genders { Male ( `` M '' ) , Female ( `` F '' ) , Transgender ( `` T '' ) , Other ( `` O '' ) , Unknown ( `` U '' ) ; private String code ; Genders ( String code ) { this.code = code ; } public String getCode ( ) { return code ; } public static Genders get ( String code ) { for ( Genders gender : values ( )...
What would this enum pattern be called ?
Java
I have the following method with generics that executes the getter of each item in the list it receives : It works perfectly fine if I call it as this : But , it gives me a compile error if I do it in a single line : The error says : The method setListIds ( List-Integer- ) in the type MyDTO is not applicable for the ar...
public static < T , S > List < S > getValues ( List < T > list , String fieldName ) { List < S > ret = new ArrayList < S > ( ) ; String methodName = `` get '' + fieldName.substring ( 0 , 1 ) .toUpperCase ( ) + fieldName.substring ( 1 , fieldName.length ( ) ) ; try { if ( list ! = null & & ! list.isEmpty ( ) ) { for ( T...
Different return type of generic method depending on invocation location
Java
I have solved a Y-combinator problem . Just now I found that I can not reference a generic parameter recursively.for example : Q : How can I use generic parameter on the method g to avoid introducing an additional interface G , and the generic parameter should avoiding the UNCHECKED warnings ? Thanks in advance .
Y = λf . ( λx.f ( x x ) ) ( λx.f ( x x ) ) IntUnaryOperator fact = Y ( rec - > n - > n == 0 ? 1 : n * rec.applyAsInt ( n - 1 ) ) ; IntUnaryOperator Y ( Function < IntUnaryOperator , IntUnaryOperator > f ) { return g ( g - > f.apply ( x - > g.apply ( g ) .applyAsInt ( x ) ) ) ; } IntUnaryOperator g ( G g ) { return g.ap...
How to reference a generic parameter recursively ?
Java
Let 's say I have the following two tables : And I want to write a JPQL query that changes some Bar.flag values based on a collection of Foo ids.If this were plain SQL I 'd write something like this : You ca n't translate this to JPQL however , because the bar_id column is n't mapped to a property of the entity.As bar_...
@ Entity public class Foo { @ Id private int id ; @ ManyToOne ( ) @ JoinColumn ( name = `` bar_id '' ) private Bar bar ; } @ Entity public class Bar { @ Id private int id ; private Boolean flag ; } UPDATE Bar SET flag = true WHERE id IN ( SELECT bar_id from FOO where id = 3 ) ;
How do I refer to columns only mapped for joins in JPQL ?
Java
When I read Effective Java item 27 , the type casting between UnaryFunction < Object > and UnaryFunction < T > confused me.Why UnaryFunction < Object > can be casted to UnaryFunction < T > ? I know the generic type will be erased after complier . So ( UnaryFunction < T > ) IDENTITY will eventually be ( UnaryFunction < ...
interface UnaryFunction < T > { T apply ( T t ) ; } public class Main { private static final UnaryFunction < Object > IDENTITY = new UnaryFunction < Object > ( ) { public Object apply ( Object t ) { return t ; } } ; @ SuppressWarnings ( `` unchecked '' ) public static < T > UnaryFunction < T > identityFunction ( ) { re...
Why UnaryFunction < Object > can be casted to UnaryFunction < T > ?
Java
There is a simple proxy : Pre filter : and properties : In general , everything works well.But the web pages that the proxy sends have links likeA must be of the form like : How to configure a server to send the correct links ? Cases:1.When accessing the myserver directly from the Internet like : server sends the page ...
@ EnableZuulProxy @ SpringBootApplicationpublic class Application { public static void main ( String [ ] args ) { SpringApplication.run ( Application.class , args ) ; } @ Bean public SimpleFilter simpleFilter ( ) { return new SimpleFilter ( ) ; } } public class SimpleFilter extends ZuulFilter { private static Logger lo...
Spring Boot and Zuul routes
Java
so I just saw this code at work , and the author told me it 's for inline optimization.then he calls it in main like thisInstead of having a default constructor with the code from init ( ) in it . He told me it 's for inline optimization . Is this correct ? How is it faster ? where do I read up about this ?
Class Test { ... void init ( ) { //sets variables , call functions , etc } ... } Test t=new Test ( ) ; t.init ( ) ;
Java inline optimization is this correct ?
Java
I have the following code that is functionally working I have tried this : But this throws to add a return statement . Also , the classBooked variable needs to be declared final , but that can not be done . What is the mistake being done ? Also , once true , I need to break from it . that is why I thought of adding fin...
for ( UniversityClass class : allClasses ) { Period < Date > classDate = class.getClassDates ( ) ; if ( classDate.start ( ) .before ( classEndDate ) & & classDate.end ( ) .after ( classBeginDate ) ) { classBooked = true ; break ; } } allClasses.stream ( ) .filter ( class - > { Period < Date > classDate = class.getClass...
How to convert a for-loop to find the first occurrence to Java streams ?
Java
I am using Hibernate for a few years but am not sure about the usage of Query and Criteria.I understood , that one of Hibernate strengths are to control the field name in one place.If I have the following code : What if I change `` name '' of the Cat in the java object ? Even when using refactor replace ( like in Elips...
List cats = sess.createCriteria ( Cat.class ) .add ( Restrictions.like ( `` name '' , `` Fritz % '' ) ) .add ( Restrictions.between ( `` weight '' , minWeight , maxWeight ) ) .list ( ) ;
Hibernate and how to avoid name change of modals
Java
Ok I know i asked before but i got a little further than what i had . So here is my problem.I have to write a program that will read in two numbers from the user ( double type ) . The program should then display a menu of options to the user allowing them to add , multiply or divide the first number by the second . My ...
import java.util . * ; public class tester { public static void main ( String [ ] args ) { Scanner console = new Scanner ( System.in ) ; double MyDouble1 ; double MyDouble2 ; System.out.print ( `` Please enter the first decimal number : `` ) ; MyDouble1 = console.nextDouble ( ) ; System.out.print ( `` Please enter the ...
Switch Statement help in Java
Java
Imagine you want to count how many non-ASCII chars a given char [ ] contains . Imagine , the performance really matters , so we can skip our favorite slogan.The simplest way is obviouslyThen you think that many inputs are pure ASCII and that it could be a good idea to deal with them separately . For simplicity assume y...
int simpleCount ( ) { int result = 0 ; for ( int i = 0 ; i < string.length ; i++ ) { result += string [ i ] > = 128 ? 1 : 0 ; } return result ; } private int skip ( int i ) { for ( ; i < string.length ; i++ ) { if ( string [ i ] > = 128 ) break ; } return i ; } int smartCount ( ) { int result = 0 ; for ( int i = skip (...
Strange performance drop after innocent changes to a trivial program
Java
I am trying to use java 8 features . While reading official tutorial I came across this code and there was a question : Which method will be invoked in the following statement ? '' String s = invoke ( ( ) - > `` done '' ) ; and answer to it was The method invoke ( Callable < T > ) will be invoked because that method re...
static void invoke ( Runnable r ) { r.run ( ) ; } static < T > T invoke ( Callable < T > c ) throws Exception { return c.call ( ) ; }
How does this lambda feature in java 8 work ?
Java
I am observing some peculiar behavior with Java8 and the new Stream-API.I would expect the performance of the following two statements to be identical , but it 's not.versusBoth statements should return true , and I would n't expect any performance difference given that they can both short circuit on the first match fo...
LongStream.iterate ( 1 , n - > n + 1 ) .limit ( 5000 ) .anyMatch ( n - > isPerfectCube ( ( n*n*n ) + ( ( n*n ) *p ) ) ) ; LongStream.iterate ( 1 , n - > n + 1 ) .anyMatch ( n - > isPerfectCube ( ( n*n*n ) + ( ( n*n ) *p ) ) ) ;
Java Stream-API performance with infinite series
Java
I have this line of codeI have a bytearray ( content [ ] ) in little endian and need to recreate a 2 byte value . This code does the job just fine but prior to testing i had it written like thisand the result was not right . My question is why is 0xff necessary in this scenario ?
int b1 = 0xffff & ( content [ 12 ] < < 8 | 0xff & content [ 11 ] ) ; int b1 = 0xffff & ( content [ 12 ] < < 8 | content [ 11 ] ) ;
Java bitwise operation
Java
I 'm trying to define a custom ClassLoader . And of course my code to test it : The problem is that my lines never get printed . Clearly I 'm missing something .
public class ExampleLoader extends ClassLoader { public Class < ? > findClass ( String name ) throws ClassNotFoundException { System.out.println ( `` This never gets printed '' ) ; return super.findClass ( name ) ; } public Class < ? > loadClass ( String name , boolean b ) throws ClassNotFoundException { System.out.pri...
ContextClassLoader not hooking
Java
I have a const experience value , person object , list of skill and method ( can not modify it ) hasSkill ( skill , person , experience ) which returns boolean.I want to check that person has every skill from the list.My code is : I am pretty sure that there is better solution but can not find it ; what should I do to ...
int experience = 5 ; private hasAllSkills ( person ) { return skillList.stream ( ) .filter ( s - > hasSingleSkill ( s , person ) ) .collect ( Collectors.toList ( ) ) .size ( ) == skillList.size ( ) ? true : false ; } private boolean hasSingleSkill ( Skill s , Person p ) { return hasSkill ( s , p , experience ) ; }
Check statement for every list item
Java
I 'm no native English speaker , so please excuses any translation errors.I 'm not really having a coding problem . It 's more of a conceptual question.I wrote two times the same piece of code translating an image into a list of RGB values . ( 1 combination of 3 values for each pixel ) .I wrote the code first in VB.net...
Dim bmp As New Bitmap ( File ) For x As Integer = 0 To w - 1 For y As Integer = 0 To h - 1 Dim c As Color = bmp.GetPixel ( x , y ) Dim Red as integer = c.R Dim Green as integer = c.G Dim Blue as integer = c.B Next ynext x BufferedImage image = ImageIO.read ( new File ( File ) ) for ( int i = 0 ; i < w ; i++ ) { for ( i...
RGB colors in java Vs VB.net
Java
Given this little pice of code : i do n't understand the output that is shown : what is the second listed constructor in here with the second parameter to the Builder . I thought that the output will only show the private constructor of Hello but not the second one .
import java.util.Arrays ; public class Sample { private final int test ; private Sample ( int test ) { this.test = test ; } public static void main ( String [ ] args ) { System.out.println ( Arrays.toString ( Hello.class.getDeclaredConstructors ( ) ) ) ; } public static class Hello { private final int i ; private Hello...
getDeclaredConstructors ( ) lists 2 constructors but there is only one
Java
The following little Java example wo n't compile for unclear reasoning : The line with ctx.put produces following error : If working without wildcards the attribute pattern works fine.Is there any explanation why the compiler does not accept the value with wildcard typing ?
package genericsissue ; import java.util.ArrayList ; import java.util.List ; interface Attribute < V > { } interface ListAttribute extends Attribute < List < ? > > { } public class Context { public < T , A extends Attribute < T > > void put ( Class < A > attribute , T value ) { // implementation does not matter for the...
Failing to compile correlated Java Generics parameters with wildcards
Java
On page 65 and 66 of Java Concurrency in Practice Brian Goetz lists the following code : About this class Goetz writes : `` ... the delegating version [ the code above ] returns an unmodifiable but 'live ' view of the vehicle locations . This means that if thread A calls getLocations ( ) and thread B later modifies the...
@ ThreadSafepublic class DelegatingVehicleTracker { private final ConcurrentMap < String , Point > locations ; private final Map < String , Point > unmodifiableMap ; public DelegatingVehicleTracker ( Map < String , Point > points ) { locations = new ConcurrentHashMap < String , Point > ( points ) ; unmodifiableMap = Co...
How does DelegatingVehicleTracker ( p. 65 Goetz ) return a `` live '' view ?
Java
I have a question regarding this . statement.Let 's say I have this code right here ( very stupid and useless but gets the message across ) : So do I have this code right ? When I am using this.SumAddG ( ) - Am I referring to the result of the method SumAddG ( ) using the instance variables of this class instance ?
class Calculate { int x , y ; final int g = 5 ; //Constructor public Calculate ( int a , int b ) { x = a ; y = b ; } public int sumAddG ( ) { return ( x+y+g ) ; } //comparing method public boolean same ( Calculate in ) { if ( this.sumAddG ( ) == in.sumAddG ( ) ) { // < -- This is what I am curious about return true ; }...
this.method ( ) is referring to ?
Java
Consider the following sql query : Markus Winand in his book `` SQL Performance explained '' names this approach as one of the worst performance anti-patterns of all , and explains why ( the database has to prepare plan for the worst case when all filters are disabled ) .But later he also writes that for the PostgreSQL...
SELECT a , b , cFROM tWHERE ( id1 = : p_id1 OR : p_id1 IS NULL ) AND ( id2 = : p_id2 OR : p_id2 IS NULL ) CREATE FUNCTION func ( IN p_id1 BIGINT , IN p_id2 BIGINT ) ... $ BODY $ BEGIN ... END ; $ BODY $ getSession ( ) .doWork ( connection - > { ResultSet rs = connection.createStatement ( ) .executeQuery ( `` select * f...
Smart logic queries performance inside functions for PostgreSQL
Java
We have a map of Student to record Map < Student , StudentRecord > .Student class is as follows : Additionally , we have a list of Student Id ( List < String > ) provided.Using Java streams , what would be the most efficient way to filter out records of students whose Id exists in the provided list ? The expected outco...
Student { String id ; String grade ; Int age ; }
Intersecting List with keys of Map
Java
I have a set of Java annotation that I quite frequently use , like this : As I use all these annotations together quite often , and I may have to add to them in everywhere they are used once in a while , I would like to create a new annotation that I can use instead . This annotation should then `` resolve '' to all th...
@ SomeAnnotation ( Something ) @ SomeOtherAnnotation @ SomeLastAnnotation ( SomethingElse ) class Foo { /* ... */ } @ MySuperAnnotationclass Foo { /* ... */ }
Java annotation that expands/resolves to many annotations ?
Java
After asking [ How to parse Japanese Era Date string values into LocalDate & LocalDateTime ] , I was curious about the following case ; Is there a way to parse Japanese numbers on top of Japanese Calendar characters , essentially a pure Japanese date , into LocalDate ? Using only Java DateTime API . I do n't want to mo...
明治二十三年十一月二十九日
How to Parse Date Strings with Japanese Numbers in Java DateTime API
Java
Inside a bat file I have the following : java -Ddatabase.host=127.0.0.1 -Xms128M -Xmx1024M com.temp.util.manual.serial.Assignment -folder C : \temp\ -destination C : \temp\out.csvThe -folder and -destination params are supposed to be passed to the main method of the Assignment class being called , but instead they are ...
Unrecognized option : -'destination'Error : Could not create the Java Virtual Machine.Error : A fatal exception has occurred . Program will exit.Press any key to continue . . . @ echo offsetlocal EnableDelayedExpansion EnableExtensions set FILETYPE= % ~n0set CLASSPATH=jar1.jarset CLASSPATH= % CLASSPATH % ; anotherjar.j...
How do I stop Java program arguments being mistaken for VM arguments ?
Java
I was reading Java SCJP book by Khalid A. Mughal ( for JE6 ) , and in topic 7.6 Interfaces and Page number 313 , it is given that A subinterface can override abstract method declarations from its superinterfaces . Overridden methods are not inherited.I could not quite understand what `` Overridden methods are not inher...
interface A { void abc ( ) ; } interface B extends A { @ Override void abc ( ) ; } interface C extends B { void abc ( ) ; }
interface - Overridden methods are not inherited
Java
I need some clarification about how minor gc collections behave . calling a ( ) or calling b ( ) in a long-lived application , if they could behave worstly when old space gets bigger Where does my doubt comes from ? I found out that in an app in which the used tenured space gets bigger , there is an increase of minor g...
//an example instance lives all application life cycle 24x7public class Example { private Object longLived = new Object ( ) ; public void a ( ) { var shortLived = new ShortLivedObject ( longLived ) ; // longLived now is attribute shortLived.doSomething ( ) ; } public void b ( ) { new ShortLivedObject ( ) .doSomething (...
Could increase gc time short lived object that has references to old lived object ?
Java
I 'm trying to understand the benefit of a programming language being statically typed , and through that , I 'm wondering why we need to include type in declaration ? Does it serve any purpose rather than to make type explicit ? If this is the case , I do n't see the point . I understand that static typing allows for ...
myClass test = new myClass ( ) ;
Why is the declaration of type important in a statically typed language ?
Java
having since can not do so there is a the aList is built by other routing at runtime , and that part of code has a function to take a List < IData > from the the aListthe question is if the List < ? extends IData > aList is point to ArrayList < ChildClassA > ( ) or ArrayList < ChildClassB > ( ) , can it do ListData < I...
class BaseClass implements IData ( ) ; class ChildClassA ( ) extends BaseClass ; class ChildClassB ( ) extends BaseClass ; List < BaseClass > aList = new ArrayList < ChildClassA > ( ) List < ? extends IData > aList for pointint to either ArrayList < ChildClassA > ( ) , or ArrayList < ChildClassB > ( ) List < ? extends ...
How to assign List < ? extends BaseClass > to List < BaseClass >
Java
Looking for modern way to realise String translation to replace bad looking if-else or switch constructions : or
if ( `` UK '' .equals ( country ) ) name = `` United Kingdom '' ; if ( `` GE '' .equals ( country ) ) name = `` Germany '' ; if ( `` FR '' .equals ( country ) ) name = `` France '' ; if ( `` IT '' .equals ( country ) ) name = `` Italy '' ; [ ... ] switch ( country ) { case `` UK '' : name = `` United Kingdom '' ; break...
Java alternative of bad looking if-else or switch constructions
Java
For a given type of Map , are there any guarantees that iterating over the Collection views returned by the keySet , values and entries methods are iterated in the same order ? Background : I 'm wondering whether transforming tois guaranteed to keep iteration order unchanged .
public static void doSomethingForEachEntry ( Map < String , Integer > someMap ) { for ( String key : someMap.keySet ( ) ) { doSomething ( someMap.get ( key ) ) ; } } public static void doSomethingForEachEntry ( Map < String , Integer > someMap ) { for ( Integer value : someMap.values ( ) ) { doSomething ( value ) ; } }
Is iteration order over the different Collection views of a given Map guaranteed to be consistent ?
Java
I 'm using the Mockito mock framework to mock a generic class in Java . The usage of the framework seems to be pretty clear from the documentation , I did n't find an example for mocking generic classes . The mock framework contains the following method : I have a generic type IState < StateId , Event > and I want to i...
public static < T > T mock ( Class < T > classToMock ) { ... } IState < StateId , Event > mockState = Mockito.mock ( IState.class ) ; Type safety : The expression of type IState needs unchecked conversion to conform to IState < StateId , Event > IState < StateId , Event > mockState = Mockito.mock ( IState < StateId , E...
Generic classes in generic methods
Java
So I 'm writing some code that involves extending a class I have previously written in which files are created and named using a constructor that takes in a name and a size of type long . In that original class , I verified within the constructor that the entered file name contained one `` . '' character but did not re...
public class Song extends DigitalMedia { private String artist ; private String album ; private String name ; private long size ; public Song ( String aName , long aSize , String aArtist , String aAlbum ) { super ( aName , aSize ) ; setArtist ( aArtist ) ; setAlbum ( aAlbum ) ; }
Checking the validity of a variable before calling the super constructor
Java
I 'm trying to make sure I understand the performance implications of synchronized in java . I have a couple of simple classes : So , as you can see in the previous example , I 'm synchronizing on ClassOne.setClassTwo and ClassTwo.setVal and ClassTwo.setVal2 . What I 'm wondering is if the performance is exactly the sa...
public class ClassOne { private ClassTwo classTwo = new ClassTwo ( ) ; public synchronized void setClassTwo ( int val1 , int val2 ) { classTwo.setVal ( val1 ) ; classTwo.setVal2 ( val2 ) ; } public static void main ( String [ ] args ) { ClassOne classOne = new ClassOne ( ) ; classOne.setClassTwo ( 10 , 100 ) ; } } publ...
Java synchronization across objects
Java
My question is the following : Its usual for Java code to have generic collections implemented like : And used like this for example : Since the generic type of genericCollection is erased , the JVM does n't seems to have a way to know that really inside 'data ' array of genericCollection there are only MyObject instan...
public class GenericCollection < T > { private Object [ ] data ; public GenericCollection ( ) { // Backing array is a plain object array . this.data = new Object [ 10 ] ; } @ SuppressWarnings ( `` unchecked '' ) public T get ( int index ) { // And we just cast to appropriate type when needed . return ( T ) this.data [ ...
Do typed arrays help the JIT to optimize better ?
Java
I often have to compare to instances of a certain type for equality , but I do not need to compare everything , but only certain fields . I usually do it like this : As I have to to this really often , I am wondering if there is a generic way to do this . All the objects I have to compare extend a certain base class . ...
Comparator < SomeType > c = Comparator.comparing ( SomeType : :getNumber ) .thenComparing ( SomeType : :getType ) .thenComparing ( SomeType : :getSite ) .thenComparing ( SomeType : :getAddition ) .thenComparing ( SomeType : :getImportantFlag ) ; if ( c.compare ( old , new ) == 0 ) { ... } public static < T extends Base...
Generic object comparison method with a variable number of method references for comparison
Java
Well , I am attempting to read a text file that looks like this : FTFFFTTFFTFT3054 FTFFFTTFFTFT4674 FTFTFFTTTFTF ... etcAnd when I am reading it , everything compiles and works wonderfully , putting everything into arrays like this : studentID [ 0 ] = 3054studentID [ 1 ] = 4674 ... etc studentAnswers [ 0 ] = FTFFFTTFFT...
public static String [ ] getData ( ) throws IOException { int total = 0 ; int [ ] studentID = new int [ 127 ] ; String [ ] studentAnswers = new String [ 127 ] ; String line = reader.readLine ( ) ; String answerKey = line ; StringTokenizer tokens ; while ( ( line = reader.readLine ( ) ) ! = null ) { tokens = new StringT...
Why is my array deleting the zeroes from a file I am reading ?
Java
The following is a constructor of String class But , I wonder how couldhappen ? The comment says 'trim the baggage ' , what does baggage refer to ?
public String ( String original ) { int size = original.count ; char [ ] originalValue = original.value ; char [ ] v ; if ( originalValue.length > size ) { // The array representing the String is bigger than the new // String itself . Perhaps this constructor is being called // in order to trim the baggage , so make a ...
how could 'originalValue.length > size ' happen in the String constructor ?
Java
To my understand correctly anonymous classes are always final : This has been mentioned specifically in JLS 15.9.5 However , when i run the following code to check that it is showing that Inner class is not final.Output of above program is : Please clear my doubt as i am not able to understand this behavior .
public class Test { static class A < T > { } public static void main ( String arg [ ] ) { A < Integer > obj = new A ( ) { } ; if ( ( obj.getClass ( ) .getModifiers ( ) & Modifier.FINAL ) ! = 0 ) { System.out.println ( `` It is a final `` + obj.getClass ( ) .getModifiers ( ) ) ; } else { System.out.println ( `` It is no...
Anonymous Inner classes and Final modifier
Java
I came across this question while I was doing some interview prep . The choices given were : O ( n ) O ( n^2 ) From what I understand the answer should have been O ( n ) as on every iteration a new instance of the array is being created and the previous reference is being lost . However , the book mentions the answer t...
public class Main { public static void main ( String [ ] args ) { // n is some user input value int i = 0 ; while ( i < n ) { int [ ] a = new int [ n ] ; for ( int j = 0 ; j < n ; j++ ) { a [ j ] = i * j ; } i++ ; } } }
Space complexity of the piece of code below ?
Java
Below is some code snippet from the netty 4.0.24 framework . It 's kind of confusing to interpret the B type parameter .
public abstract class AbstractBootstrap < B extends AbstractBootstrap < B , C > , C extends Channel > implements Cloneable { ... }
How to interpret this Java generic type definition ?
Java
I have two string variables ticker and detail . I 'm trying to print out the two strings in one line . It just would n't work . I 've tried so many different ways of doing this . To exclude the possibility of an uninitialized string I tried printing them out in different lines ... this works.This example works ... exce...
System.out.println ( ticker ) ; System.out.println ( detail ) ; IWM|0 # 0.0|0 # 0.0|0 # -4252 # 386|GLD|0 # 0.0|0 # 0.0|0 # -4704 # 818| System.out.println ( ticker.concat ( detail ) ) ; System.out.println ( ticker+detail ) ; StringBuffer sb = new StringBuffer ( ) ; sb.append ( ticker ) ; sb.append ( detail ) ; System....
Strange behavior with java strings
Java
I have used log4j 's rolling policy for compressing files that reach to certain amount in size . Below log4j properties are working properly.But problem here is after it generates a compressed file , it also renames the file which is present in the compressed gz file with the name of gz file.For my scenario , I do n't ...
log4j.appender.FILE=org.apache.log4j.rolling.RollingFileAppenderlog4j.appender.FILE.rollingPolicy=org.apache.log4j.rolling.FixedWindowRollingPolicylog4j.appender.FILE.rollingPolicy.maxIndex=13log4j.appender.FILE.triggeringPolicy=org.apache.log4j.rolling.SizeBasedTriggeringPolicylog4j.appender.FILE.triggeringPolicy.MaxF...
Log4j 's rollingPolicy.FileNamePattern is also changing name of files that are zipped in
Java
I have an interfaceLets say that there are two implementations , one that uses Database to get the data and another one that uses a Webservice.As you can already see , the problem is the super generic exception launched . As both implementations need to raise the same kind of exception . The Jdbc implementation really ...
public interface DataDAO { public void doSomething ( ) throws Exception ; } public class DataDAOJdbc implements DataDAO { public void doSomething ( ) throws Exception { //Implement } } public class DataDAOWebService implements DataDAO { public void doSomething ( ) throws Exception { //Implement } } public interface Dat...
Interface implementation launches different exceptions
Java
I am currently preparing for an exam and am working on the following task : Generate an infinite Stream containing the integers ( 0 , 1 , -1 , 2 , -2 , 3 , -3 , ... ) .Following stream generate a normal infinite stream : Is there a method or lambda expression that produces both positive and negative numbers ?
Stream < Integer > infiniteStream = Stream.iterate ( 1 , i - > i + 1 ) ;
Generate an infinite Stream < Integer > containing the integers ( 0 , 1 , -1 , 2 , -2 , 3 , -3 , ... )
Java
This program supposed to avoid null when calling toFloat with null . but I 'm still getting NPE .. any helpSystem.out.println ( toFloat ( null , null ) ) ;
private static Float toFloat ( Float def , String str ) { try { return str ! = null ? Float.parseFloat ( str ) : def ; } catch ( NumberFormatException e ) { return def ; } }
NPE when trying to return null