lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have a service that downloads a large file inside an AysncTask 's doInBackground ( ) method : While this is being executed ( the file is downloading ) , scrolling through a ListView can be from a little choppy to very choppy.I 've tried creating a new process for the downloading service , changing the priority of the...
data = new byte [ 8192 ] ; output = new FileOutputStream ( fileLoc ) ; connection = ( HttpURLConnection ) new URL ( currUrl ) .openConnection ( ) ; input = new BufferedInputStream ( connection.getInputStream ( ) ) ; while ( ( count = input.read ( data ) ) ! = -1 ) { output.write ( data , 0 , count ) ; }
Downloading file causes UI to stutter
Java
I want to know how I can use my object ObjetTWS with the parameter of my function ObjectTWS ( ) . And how I can put the object in a Arraylist or a List.I already try this but it says ObjetTWS undefined :
public class ObjetTWS { String nom ; List < String > jobAmont ; List < String > jobAval ; String type ; public ObjetTWS ( String p_nom , String p_type , String p_jobAmont , String p_jobAval ) { ObjetTWS obj = new ObjetTWS ( ) ; obj.nom = p_nom ; obj.jobAmont.add ( p_jobAmont ) ; obj.jobAval.add ( p_jobAval ) ; obj.type...
Java object in Arraylist or List
Java
I am writing a simple multithread practice with java . All I need to do is basically make a JFrame with two buttons ( `` start '' and `` end '' ) . If the user clicks the `` start '' button , the console will start printing out `` Printing '' . And if `` end '' is clicked , the console will stop printing . Clicking `` ...
//import not shownpublic class Example extends JFrame implements Runnable { private static boolean print , started ; //print tells whether the thread should keep printing //things out , started tells whether the thread has been //started private JButton start ; //start button private JButton end ; //end button private ...
How to start/resume and stop/pause a thread inside the action listener in java
Java
Let 's say we have the following block of code : All the typecasting makes the code look ugly , is there a way of declaring 'thing ' as ObjectType inside that block of code ? I know I could do and work with 'differentThing ' from then on , but that brings some confusion to the code . Is there a nicer way of doing this ...
if ( thing instanceof ObjectType ) { ( ( ObjectType ) thing ) .operation1 ( ) ; ( ( ObjectType ) thing ) .operation2 ( ) ; ( ( ObjectType ) thing ) .operation3 ( ) ; } OjectType differentThing = ( ObjectType ) thing ; if ( thing instanceof ObjectType ) { ( ObjectType ) thing ; //this would declare 'thing ' to be an ins...
Declaring variable to be of certain type
Java
So I am trying to figure out why a program is compiling the way it is , hopefully you guys can explain it for me.So the output for the above program is going to beCar Running Car Running Car Running My question is , why do I have to do a try/catch block to call drive ( ) method for the v and c2 objects but not the c ? ...
class Vehicle { public void drive ( ) throws Exception { System.out.println ( `` Vehicle running '' ) ; } } class Car extends Vehicle { public void drive ( ) { System.out.println ( `` Car Running '' ) ; } public static void main ( String [ ] args ) { Vehicle v = new Car ( ) ; Car c = new Car ( ) ; Vehicle c2 = ( Vehicl...
Need clarification about inheritance and exceptions
Java
Reading myself into Lisp , currently on this page ( http : //landoflisp.com ) , I found the following statement on the second last paragraph on the page that shows when clicking the link CLOS GUILD : The important thing to note about the example is that in order to figure out which mix method to call in a given situati...
( defclass color ( ) ( ) ) ( defclass red ( color ) ( ) ) ( defclass blue ( color ) ( ) ) ( defclass yellow ( color ) ( ) ) ( defmethod mix ( ( c1 color ) ( c2 color ) ) `` I do n't know what color that makes '' ) ( defmethod mix ( ( c1 blue ) ( c2 yellow ) ) `` you made green ! `` ) ( defmethod mix ( ( c1 yellow ) ( c...
Does Java support dispatching to specific implementations based on types of multiple objects like Lisp does ?
Java
I 've found such an example of using String.format ( ) in a book : According to the book the output should be : 1,000,000,000 . But when I run the code I only get 1 000 000 000 without the commas . Why ? how can I get it with commas ?
package stringFormat ; public class Main { public static void main ( String [ ] args ) { String test = String.format ( `` % , d '' , 1000000000 ) ; System.out.println ( test ) ; } }
How to insert commas into a number ?
Java
Output : By definition on the tutorials point pageA Set is a generic set of values with no duplicate elements . A TreeSet is a set where the elements are sorted.Why is the output for both s and s1 sorted ? I was expecting only s1 's output to be sorted .
Set < Integer > s = new HashSet < Integer > ( ) ; s.add ( 77 ) ; s.add ( 0 ) ; s.add ( 1 ) ; System.out.println ( s ) ; TreeSet < Integer > s1 = new TreeSet < Integer > ( ) ; s1.add ( 77 ) ; s1.add ( 0 ) ; s1.add ( 1 ) ; System.out.println ( s1 ) ; s = [ 0 , 1 , 77 ] s1= [ 0 , 1 , 77 ]
Why does this HashSet look sorted when printed ?
Java
Hello I 'm testing the class that has some validating methods and I 've been wondering if there is a way to reduce the duplicated code.I also have validators for other fields such as username etc . I was thinking about implementing a helper method that would accept : tested credential as String , List but I 've got a p...
@ Testvoid testCorrectEmailValidator ( ) { List < String > correctEmails = Arrays.asList ( `` test @ test.com '' , `` test123 @ test123.com '' , `` test @ test.com.in '' , `` test.test2 @ test.com '' , `` test.test2.test3 @ test.com '' , `` TEST.2test @ test.com '' ) ; for ( String email : correctEmails ) { boolean isV...
passing static method as parameter in Java
Java
If I execute the statementwill I actually get an instance of moo ? This seems at both the same time obvious and non-intuitive . Functionally , this is what should happen , but at the same time this is not-expected if you did n't know the internals.EDIT : I realized this seems unintuitive b.c . in Java constructors can ...
var foo = function ( ) { return new moo ( ) ; } var moo = function ( ) { return this ; } new foo ( )
Will new return the named function constructor instance- ?
Java
The factory in this tutorial obviously violates the OCP . Every time a shape is added to the system , we need to add it in the factory to support it.I 'm thinking of another implementation and I 'd like to know if there are any drawbacks.This implementation looks it does n't violate OCP , and is n't complex . Is there ...
public class ShapeFactory { //use getShape method to get object of type shape public Shape getShape ( Class < ? extends Shape > shapeType ) { return shapeType.newInstance ( ) ; } }
Factory design pattern and violation of OCP ( Open-Closed Principle )
Java
I was reading Unsigned arithmetic in Java which nicely explained how to do unsigned longs using the following methodHowever I 'm confused by Guava 's implementation . I 'm hoping someone can shed some light on it .
public static boolean isLessThanUnsigned ( long n1 , long n2 ) { return ( n1 < n2 ) ^ ( ( n1 < 0 ) ! = ( n2 < 0 ) ) ; } /** * A ( self-inverse ) bijection which converts the ordering on unsigned longs to the ordering on * longs , that is , { @ code a < = b } as unsigned longs if and only if { @ code flip ( a ) < = flip...
Guava 's UnsignedLong : Why does it XOR Long.MIN_VALUE
Java
I am trying to understand where good contracts end and paranoia starts . Really , I just have no idea what good developer should care about and what shall he leave out : ) Let 's say I have a class that holds value ( s ) , like java.lang.Integer . Its instances are aggregated by other objects ( MappedObjects ) , ( one-...
class MappedObject { public void bind ( Integer integer ) { MegaMap.getInstance ( ) .remove ( fInteger , this ) ; fInteger = integer ; MegaMap.getInstance ( ) .add ( fInteger , this ) ; } ... private Integer fInteger ; }
Should my classes restrict developers from doing wrong things with them ?
Java
I have classes called say CalculationOutcome and FileHashOutcome . Their constructors have ( ActualResult , Throwable ) arguments , and at the end of a chain of CompletionStages I have handle ( XxxOutcome : :new ) .It might make intentions clearer and save some boilerplate if I could write say PossiblyWithError < FileH...
class FileHashOutcome { private final String hash ; private final Throwable throwable ; FileHashOutcome ( String hash , Throwable throwable ) { // Usual assignments } } CompletionStage < FileHashOutcome > future = SomeExternalLibrary.calculateHash ( file ) // ... It 's a CompletionStage < String > at this stage ... .ha...
Is there a java8 standard library class that means `` possibly with exception '' in the same way as java.util.Optional means `` possibly null '' ?
Java
Recently , I stumbled upon the following java syntax : At first , I thought that it is a syntax error , but to my surprise , the code gave no compilation or runtime error . I have the following questions : Is there a standard definition and documentation for such declaration in Java ? What happens when this code is com...
ArrayList < String > nodes = new ArrayList < String > ( ) { { add ( `` n1 '' ) ; add ( `` n2 '' ) ; } } ;
Strange syntax in ArrayList declaration in java
Java
I have created anonymous class by implementing interface I inside public static void main ( ) method . So , by java 8 for the abstract method test ( ) , the implementation is provided from imple ( ) method of class C.So , inside public static void main ( ) method , printing _interface.getClass ( ) , I gotpackage_path.M...
@ java.lang.FunctionalInterfaceinterface I { void test ( ) ; } class C { void imple ( ) { System.out.println ( this.getClass ( ) ) ; System.out.println ( `` Inside Implementation '' ) ; } } class Main { public static void main ( String [ ] args ) { I _interface = new C ( ) : :imple ; System.out.println ( _interface.get...
Why does this.getClass give it 's own class name rather than Anonymous class name ?
Java
When fiddling with unit tests for a highly-concurrent singleton class I stumbled upon the following weird behaviour ( tested on JDK 1.8.0_162 ) : The last 2 lines of the main ( ) method disagree on the value of INSTANCE - my guess is that JIT got rid of the method completely since the field is static final . Removing t...
private static class SingletonClass { static final SingletonClass INSTANCE = new SingletonClass ( 0 ) ; final int value ; static SingletonClass getInstance ( ) { return INSTANCE ; } SingletonClass ( int value ) { this.value = value ; } } public static void main ( String [ ] args ) throws NoSuchFieldException , IllegalA...
Breaking JIT optimisations with reflection
Java
How is this different from synchronizing on the class , i.e . synchronized ( Bob.class ) { ... }
class Bob { private static final Object locke = new Object ( ) ; private static volatile int value ; public static void fun ( ) { synchronized ( locke ) { value++ ; } } }
Why synchronize on a static lock member rather than on a class ?
Java
Assume I have an object Car , with five parameters , { numwheels , color , mileage , horsepower , maxSpeed } .I have a method that needs 3 of these values.Which of the 2 options is said to be best practice ? Is it better to pass enclosing object and reduce the number of parameters , OR just pass in bare-minimal data to...
void compute ( Car c , Person p ) { return c.mileage + c.horsepower + c.maxSpeed + p.age ; } void compute ( int mileage , int horsepower , int maxSpeed , int age ) { return mileage + horsepower + maxSpeed + age . ; }
Is it good to pass minimal parameters ?
Java
Suppose I have a string : String s = `` 1,2,3,4,5,6 '' . I would like to create a method combineFunctions ( ) that would take a variable length sequence of Functions as an argument and apply all of the operations in that order . The functions may have different < T , U > types . Example uses of such a function would be...
Combine < String > c = new Combine < > ( s ) ; List < String > numbers = c.combineFunctions ( splitByComma ) ; Integer max = c.combineFunctions ( splitByComma , convertToInt , findMax ) ; public < U > void combineFunctions ( Function < ? extends Object , ? extends Object > ... functions ) { }
Create a method that accepts variable length of Function arguments with possibly different types
Java
how do i pull the `` 16 '' out for both Bar Foo Bar : Foo8:16 Foo Bar Bar foo barz 8:16 Foo Bar Bar foo barz Here is what i have triedAnd here is the error i getI tested the regex ( `` ( [ 0-9 ] + : [ 0-9 ] + ) + '' ) at http : //regexr.com/ and it correctly highlight the `` 8:16 ''
String V , Line = '' Bar Foo Bar : Foo8:16 Foo Bar Bar foo barz '' ; V = Line.substring ( Line.indexOf ( `` ( [ 0-9 ] + : [ 0-9 ] + ) + '' ) +1 ) ; V = V.substring ( V.indexOf ( `` : '' ) +1 , V.indexOf ( `` `` ) ) ; System.out.println ( V ) ; Exception in thread `` main '' java.lang.StringIndexOutOfBoundsException : S...
How to pull phrase out of a string
Java
I 'm solving a problem with math.pow function when the answer appear on text field with any enter value such as 10.It will be appear in commas.I use a decimal format library but nothing happen.Is there a different way to do that.I want answer like thisCode : Main
10000000000Not10,000,000,000 public class Gra extends JFrame { private JTextField textField ; private JTextField textField_1 ; DecimalFormat d = new DecimalFormat ( `` '' ) ; public Gra ( ) { super ( `` Frame '' ) ; getContentPane ( ) .setLayout ( null ) ; textField = new JTextField ( ) ; textField.setBounds ( 163 , 20...
Java : Double Datatype Decimal format commas issue
Java
What 's the difference between the following statements : andIn my script it 's noted that the former would be a correct way to create an array of generics ( although it leads to a compiler warning ) . But I ca n't quite figure out what 's the use of the ( List < E > [ ] ) statement . List < E > [ ] is n't even it 's o...
List < E > [ ] x = ( List < E > [ ] ) new List [ 100 ] ; List < E > [ ] x = new List [ 100 ] ; List < E > [ ] x = ( List [ ] ) new List [ 100 ] ;
Conversion of arrays with generics
Java
While Using TDD I found myself needing to test a constant ( final ) hashmap which contains lookup values ( PLEASE SEE REASON WHY THIS WAS THE CASE UNDER UPDATE ) See below With TDD its stressed to test one thing at a time so i started calling my class verifying the validity of each of the elements as below . TEST STYLE...
private static final Map < Integer , String > singleDigitLookup = new HashMap < Integer , String > ( ) { { put ( 0 , '' Zero '' ) ; put ( 1 , '' One '' ) ; put ( 2 , '' Two '' ) ; put ( 3 , '' Three '' ) ; put ( 4 , '' Four '' ) ; put ( 5 , '' Five '' ) ; put ( 6 , '' Six '' ) ; put ( 7 , '' Seven '' ) ; put ( 8 , '' E...
Proper unit testing technique
Java
language : javaversion : 12.0.2String source code as follows : How to understand this sentence : 'The static initialization block is used to set the value here to communicate that this static final field is not statically foldable , and to avoid any possible circular dependency during vm initialization . '
/* @ implNote * The actual value for this field is injected by JVM . The static * initialization block is used to set the value here to communicate * that this static final field is not statically foldable , and to * avoid any possible circular dependency during vm initialization . */static final boolean COMPACT_STRING...
Static initialization by JVM
Java
I work on some kind of cache and from time to time , we need to prune the table to 500 records , based on a last_access_date ( only keep the 500 recently accessed rows ) .With `` plain '' SQL , this could be done with : Now as there is no LIMIT or something like ROWNUM in JPQL , the only solution I found was in native ...
DELETE FROM records WHERE id not in ( SELECT id FROM records ORDER BY last_access_date DESC LIMIT 500 )
Prune table to 500 records in JPQL
Java
The purpose of a constructor is initializing values for the fields , setting the initial state of the object . So what will happen if some fields or all fields were not initialized in the constructor ? Is it calling a default constructor provided by the JVM before the user defined constructor ? So , in this example , w...
class Name { int x ; boolean y ; Name ( ) { // no initialize } public static void main ( ) { Name n = new Name ( ) ; System.out.println ( n.x + `` , `` + n.y ) ; } }
What will happen if none or only some fields are initialized in a constructor
Java
Something peculiar I stumbled upon the other day.Consider the following code ( it collects the distinct word length counts of the given Strings , but that 's not important ) : and its equivalent method reference version : The first ( lambda ) version does not require you to import java.util.Map to compile , the second ...
static void collectByLambda ( Collection < String > list ) { Collection < Integer > collected = list.stream ( ) .collect ( Collectors.collectingAndThen ( Collectors.groupingBy ( String : :length ) , m - > m.keySet ( ) ) ) ; } static void collectByMethodReference ( Collection < String > list ) { Collection < Integer > c...
Why does calling a method not require an import of the class ?
Java
I 'm using spring mvc and i have Hibernate Validator in my domains , and i have some test that pass in eclipse , but does n't in console ( using gradle ) .In eclipse i have installed only java-7-openjdk-i386 , but in the console i use java version `` 1.8.0_25 '' , i do n't know if this has something with.Part of my dom...
@ Entity @ Table ( name = `` users '' , uniqueConstraints = { @ UniqueConstraint ( columnNames = `` username '' ) , @ UniqueConstraint ( columnNames = `` email '' ) } ) public class User { @ NotNull @ Pattern ( regexp = `` ( ? : [ a-z0-9 ! # $ % & '*+/= ? ^_ ` { | } ~- ] + ( ? : \\. [ a-z0-9 ! # $ % & '*+/= ? ^_ ` { | ...
Different kind of exception while i run test both eclipse and console ?
Java
I have such scenario ( this is Java pseudo code ) : There is a main thread which:1 ) creates an instance of an array of type C:2 ) creates and submits tasks which populate ( by doing CPU bound operations ) the arr to a pool P1 : Each task populates different range of indexes in arr so at this point synchronization is n...
C [ ] arr = new C [ LARGE ] ; for ( int i = 0 ; i < populateThreadCount ; i++ ) { p1.submit ( new PopulateTask ( arr , start , end ) ) } for ( int i = 0 ; i < uploadThreadCount ; i++ ) { p2.submit ( new UploadTask ( arr , start , end ) ; } C [ ] arr = new C [ LARGE ] ; for ( int i = 0 ; i < populateThreadCount ; i++ ) ...
How to synchronize the handover of array between 2 pool threads ?
Java
I 'm new in Java concurrency , so i ask what is the best way to perform action like this : I have a static method which matches a sub image within an image . It looks like that : The method returns null if nothing was matched , else it returns the Point of the match.Now I have 40 different sub images for one ( big ) im...
public static Point match ( final BufferedImage subimage , final BufferedImage image )
How to execute this paralell task in Java8
Java
Snippet 1 : Snippet 2 : Snippet 3 : Snippet 1 is compiling fine but Snippet 2 & Snippet 3 compile with type incompatibility errors . While it 's good that Snippet 2 & Snippet 3 fail , I do not understand how they are evaluated . In other words , I think I am missing some basics in terms of how the lambdas themselves ar...
Optional.of ( s ) .map ( str - > str ) .orElse ( `` '' ) ; Optional.of ( s ) .map ( str - > str ) .orElse ( Optional.empty ( ) ) ; Optional.of ( s ) .map ( str - > Optional.of ( str ) ) .orElse ( `` hello '' ) ;
Java 8 Lambda Chaining - Type Safety Enforcement
Java
I have a Runnable object , that runs a ping operation - If I launch this in current thread like this : I get this output : But if I run it in a new thread like this : I get this : Why are the outputs different ?
Runnable r1 = new Runnable ( ) { @ Override public void run ( ) { try { List < String > commands = new ArrayList < String > ( ) ; commands.add ( `` ping '' ) ; commands.add ( `` -c '' ) ; commands.add ( `` 10 '' ) ; commands.add ( `` google.com '' ) ; System.out.println ( `` Before process '' ) ; ProcessBuilder builder...
Why my Process terminate ?
Java
I have a subclass called CDAccount that has its own variables that are n't defined in the super class . The subclass also has a copy constructor that takes in a superclass object.This constructor is called by this line of code that 's in a different class.I 'm looking for a way to set the subclass variables in the copy...
private Calendar maturityDate ; private int termOfCD ; public CDAccount ( Account cd ) { super ( cd ) ; } if ( accounts.get ( index ) .getType ( ) .equals ( `` CD '' ) ) { return new CDAccount ( accounts.get ( index ) ) ; }
Copy constructor of subclass that has its own variables
Java
How this is possible ? How am I able to change variables marked as final ? I was using AIDE app in Android ... it compiled successfully and printed 33 .
public class Main { public static void main ( String [ ] args ) { final int NUM ; NUM = 22 ; NUM = 33 ; System.out.println ( NUM ) ; } }
Why can I re-assign a new value to a final variable in Android AIDE ?
Java
I 'm Working on an android app that has a requirement to switch theme based on the themeCode given from server . I 'm using sharePref to save the theme code and applying it with setTheme ( R.style.themeName ) ; . Its working fine till the basic theme attributes like For this I has created different styles in styles.xml...
colorPrimarycolorPrimaryDarkcolorAccentwindowActionBarwindowNoTitle style= '' @ style/AppTheme.EditText.PersonName ''
How to consider variation while switching theme ?
Java
I declared a 2d-array matrix in Java of type byte . When checking the memory used with the dimensions ( 10^6 x 4 ) it was drastically different from the same size matrix but with dimensions ( 4 x 10^6 ) .In the first case I get 6MB so the array takes 4MB as expected . However in the second case the matrix takes 28MB . ...
// Measure memory before matrix initialization - > 2MBSystem.out.println ( `` Meg used= '' + ( Runtime.getRuntime ( ) .totalMemory ( ) - Runtime.getRuntime ( ) .freeMemory ( ) ) / ( 1000*1000 ) + '' M '' ) ; byte [ ] [ ] test = new byte [ 4 ] [ 1000000 ] ; // init// Measuring memory after - > 6MB as expectedSystem.out....
Switching out array sizes in 2d array takes different amount of memory
Java
Really simple question but perhaps someone can explain . I have 2 lines of code : I expect the output of 31 536 000 000 but I get 1 471 228 928.If I remove the 1000 from the formula the answer is correct but the 1000 pushes it over the edge.The variables format is Long so it should be 264 in size , plenty big enough . ...
long millisPerYear = 365*24*60*60*1000 ; System.out.println ( `` millis per year = `` + millisPerYear ) ;
Strange Java Math Result
Java
I 'm working with a Java API used for `` macros '' that automate a piece of software . The API has , among other things , the classes Simulation ( a global state of sorts ) and FunctionManager . There 's nothing I can do to modify these classes . I 'd like to make a BetterFunctionManager class that extends FunctionMana...
Simulation simulation = getCurrentSimulation ( ) ; FunctionManager functionManager = simulation.getFunctionManager ( ) ; BetterFunctionManager betterFunctionManager = simulation.getFunctionManager ( ) ;
Extending a class that is instantiated by another class
Java
Curious why declaring an empty array of non-emtpy array ( s ) is legal in Java : P.S . I have read the related question on zero-size arrays : Why does Java allow arrays of size 0 ? Is this for the same reason ?
int [ ] [ ] array = new int [ 0 ] [ 1 ] ; System.out.println ( array [ ] [ 0 ] ) ; //wo n't compile.System.out.println ( array [ 0 ] [ 0 ] ) //triggers an out of bounds exception .
Why is declaring an empty array of non-empty array ( s ) legal in Java ?
Java
I have things ( say , for context , numbers ) that can perform operations on their own type : and actors that act on all subtypes of a certain upper bound : I want to make an actor that acts polymorphically on any numerical type : Now , clearly this does n't work because Number and Number < N > are not the same . In fa...
interface Number < N > { N add ( N to ) ; } class Int implements Number < Int > { Int add ( Int to ) { ... } } interface Actor < U > { < E extends U > E act ( Iterable < ? extends E > items ) ; } class Sum implements Actor < Number > { < N extends Number < N > > N act ( Iterable < ? extends N > items ) { ... } } interf...
how to upper-bound a self-referential type ?
Java
For example , a class include two methods , When I invoking find ( null ) , why jvm actually execute the last one ? In accepted answer of Calling Java varargs method with single null argument ? we can read that Java does n't know what type it is supposed to be . It could be a null Object , or it could be a null Object ...
public void find ( Object id ) ; public void find ( Object ... ids ) ;
When passing null as argument to overloaded varargs method ( Object ... o ) and non-varargs method ( Object o ) , why varargs method is executed ?
Java
The following two lines of code : each produce the same output : I expected the bottom line to produce since it should be willing to split after the ^ and before the t. Can someone point out where my thinking is wrong ?
System.out.println ( Arrays.toString ( `` test '' .split ( `` ( ? < ! ^ ) '' ) ) ) ; System.out.println ( Arrays.toString ( `` test '' .split ( `` ( ? ! ^ ) '' ) ) ) ; [ t , e , s , t ] [ , t , e , s , t ]
Why does splitting on ` ( ? ! ^ ) ` and ` ( ? < ! ^ ) ` produce the same answer ?
Java
I 'm writing a class in Java which is a subclass of another class I wrote , and its constructor explicitly calls the superclass 's constructor . The constructor of the superclass may throw several types of exceptions when initialized directly , however when I initialize an instance of my subclass there are several exce...
public class Persian_Cat extends Cat { public Persian_Cat ( File file ) { try { super ( file ) ; } catch ( InvalidArgumentException e ) { } catch ( FileNotFoundException e ) { } } }
Using exception handling to eliminate irrelevant exceptions in subclass constructor
Java
Does the @ Embeddable for @ ManyToMany relations and additional columns , works with String ? I do not use @ Generated Value for @ IdBecause my Entity ApplikationUserby business logic has always an IdHere my code : EDIT - 23.11.2020Regards the lack of interest , its seems to be possible to us @ Embeddable with String ?
@ Id @ Column ( length = 128 ) private String applikationUserId ; @ EmbeddedIdprivate ApplikationUserPopupMessageId applikationUserPopupMessageId ; @ ManyToOne ( fetch = FetchType.EAGER ) @ MapsId ( `` applikationUserId '' ) private ApplikationUser applikationUser ; @ ManyToOne ( fetch = FetchType.EAGER ) @ MapsId ( ``...
org.hibernate.PropertyAccessException : Could not set field value [ STRING ] value by reflection for String
Java
I am confused about a subject and can not find it on the web . As I understand it , when the program starts the class loader loads the .class files and store them in the memory as objects with the type Class.My question is when we use : Is the new object created using .class file , or using the Class object already in ...
Test test = new Test ( ) ;
When we create an object using new operator , does it use the actual .class file to create an object in java
Java
Cloud Foundry is it possible to copy missing routes from one app to another while doing blue green deployment ? I have an app with few manually added routes , while doing blue green deployment ( automated through script ) I want to copy missing/manually added routes into new app . Is it possible ? Script : Eg : appblue...
# ! /bin/bashpath= '' C : /Users/ ... /Desktop/cf_through_sh/appName.jar '' spaceName= '' development '' appBlue= '' appName '' appGreen= '' $ { appName } -dev '' manifestFile= '' C : /Users/ ... /Desktop/cf_through_sh/manifest-dev.yml '' domains= ( `` domain1.com '' `` domain2.com '' ) appHosts= ( `` host-v1 '' `` hos...
cloud foundry copy routes from one app to another
Java
I 'm looking for the best way ( readability and efficiency ) of providing a default value for a HashMap get operation but to also have the underlying map updated with that default value if a value is not already present.I understand there are 3rd party libraries out there , but I 'd prefer to stick with standard Java ....
Map < String , List < Integer > > someIntegerListLookup = new HashMap < > ( ) ; String key = `` key '' ; ... List < Integer > integerList = someIntegerListLookup.get ( key ) ; if ( integerList == null ) { integerList = new ArrayList < > ( ) ; someIntegerListLookup.put ( key , integerList ) ; } // getOrDefaultList < Int...
Java 8 : Get default value from HashMap and update underlying map
Java
Here 's a brief example from the JLS section 8.4.8.2.According to the discussion of the example , the output of running main ( ) will be `` Goodnight , Dick '' . This is because static methods are called based on the static type of the variable/expression they are called on . Here 's my question : Any even moderately f...
class Super { static String greeting ( ) { return `` Goodnight '' ; } String name ( ) { return `` Richard '' ; } } class Sub extends Super { static String greeting ( ) { return `` Hello '' ; } String name ( ) { return `` Dick '' ; } } class Test { public static void main ( String [ ] args ) { Super s = new Sub ( ) ; Sy...
Is the Java compiler allowed to be flow sensitive for static calls ?
Java
Above code builds and runs perfectly but it should n't . Comparator.comparing takes a function reference and only those methods which takes one argument and returns one argument can be mapped on this . But in above code getValue is mapped and works fine but it does n't take any parameter . Code should give build issue ...
public static void main ( String o [ ] ) { Map < String , Integer > map = new HashMap < String , Integer > ( ) ; map.put ( `` a '' , 1 ) ; map.entrySet ( ) .stream ( ) .sorted ( Comparator.comparing ( Entry : :getValue ) ) .forEach ( System.out : :println ) ; }
Function interface as function reference
Java
I have an groove code ( with some java style elements ) Is it possible to do it simpler ? I would like to have something likeor
dates.forEach new Consumer < Period > ( ) { @ Override void accept ( Period period ) { println period } } dates.forEach println dates.forEach println date
How to simplify groovy loop code
Java
I would like to do this : But it fails to compile unless I insert a cast within a : Interestingly , if I remove the generic from a it works : And if I port the original code to Kotlin , it also works ( this makes me think it 's a limitation of Java , and not something that is fundamentally unknowable ) : My question is...
< T extends java.util.Date > T a ( @ Nonnull T ... dates ) { return b ( dates ) ; // compile error } < T extends Comparable < T > > T b ( T ... comparables ) { return comparables [ 0 ] ; } < T extends java.util.Date > T a ( @ Nonnull T ... dates ) { return ( T ) b ( dates ) ; // warning about unsafe cast in IntelliJ } ...
Java generic method can not call another generic method with looser constraint and return its value
Java
Consider this case : As I understand type bounds , in this case effective upper bounds of both T and E is class A . So the question : why javac does n't accept class A as argument in declaration of field b , but accepts wildcard ? extends A in declaration of field b2 ?
class A { } class B < T extends A , E extends T > { B < ? , A > b ; B < ? , ? extends A > b2 ; }
Wildcard and type pameter bounds in java
Java
Is it good to have a class with short methods used to catch Exceptions ?
class ContractUtils { public static String getCode ( Contract contract ) throws MyException { try { return contract.getInfo ( ) .getCode ( ) ; //throws ContractException and LogicException } catch ( Exception e ) { throw new MyException ( `` error during code reading : '' +e.getMessage , e ) ; } } //other methods like ...
Classes used to manage exception
Java
I wrote this example following a test ConcurrentModificationException concept : When I executed the above main method , ConcurrentModificationException does n't get thrown and the output console prints the following result : By with my knowledge of this issue , when in a loop for list , when modifying the list , a Conc...
public class Person { String name ; public Person ( String name ) { this.name = name ; } } public static void main ( String [ ] args ) { List < Person > l = new ArrayList < Person > ( ) ; l.add ( new Person ( `` a '' ) ) ; l.add ( new Person ( `` b '' ) ) ; l.add ( new Person ( `` c '' ) ) ; int i = 0 ; for ( Person s ...
Why does n't my sample throw ConcurrentModificationException
Java
How to break stream computation based on previous results ? If it 's obvious that stream.filter ( ... ) .count ( ) would be less than some number - how to stop stream computation ? I have the following code which checks if some sampleData passes the predicate test : I could have thousands of sampleData . The problem is...
// sampleData.size ( ) may be greater than 10.000.000Set < String > sampleData = downloadFromWeb ( ) ; return sampleData.stream ( ) .filter ( predicate : :test ) .count ( ) > sampleData.size ( ) * coefficient ;
Stop java stream computations based on previous computation results
Java
I wrote a code for processing and had formerly sorted pixels with selection sort . I have to hand it in and the teacher said it is taking to long like this , so I decided to divide the pixels brightness into parts of 50 and just sort it very roughly . The image that comes out is n't completely sorted though and I reall...
PImage img ; PImage two ; PImage sorted ; int j = 0 ; int x = j ; int y = x ; int u = y ; int h = u ; int d = 1 ; void setup ( ) { size ( 736,1051 ) ; img = loadImage ( `` guy.png '' ) ; two = loadImage ( `` guy2.png '' ) ; background ( two ) ; } void draw ( ) { loadPixels ( ) ; for ( int y = 0 ; y < height ; y++ ) { f...
Processing - Rough pixel sorting algorithm stops after a part of the image
Java
Let 's say I have an Interface 'Inter ' , and Inter has a methodHow can I specify that the type of the return object has to be the same as the object upon which the method is called ? So if I have two classes 'C1 ' and 'C2 ' that implement Inter , if an instance of C1 calls someMethod ( c1.someMethod ( ) ) the result w...
Inter someMethod ( ) ; void someMethod2 ( Inter inter )
How can I specify as return type of a method the type of the object upon which the method is called ?
Java
I 'm trying to get an authorization token from Google+ using their sdk on Android , but it always raises an 'GoogleAuthException Unknown'Here is the code I use : I doubled checked the client_id I got from the google console.What is really troubling is that this code works for my staging flavor , with a staging client_i...
private static final String LOGIN_SCOPES = `` https : //www.googleapis.com/auth/plus.login `` + `` https : //www.googleapis.com/auth/userinfo.email '' ; protected static final String SCOPES = `` oauth2 : server : client_id : '' + BuildConfig.GOOGLE_SERVER_CLIENT_ID + `` : api_scope : '' + LOGIN_SCOPES ; String token = ...
Unknown GoogleAuthException while trying to get an authorization token
Java
I am wondering if there is already an implemented feature in streams ( or Collectors ) which first groups a stream by an attribute and then returns the first element in the list sorted by another attribute . E.g . the following code tries to group a stream of objects using the first attribute and then wants to collect ...
class MyClass { String att1 ; String att2 ; } Map < String , MyClass > myMap = myClassStream ( ) .collect ( Collectors.groupingBy ( MyClass : :getAtt1 ) ) ; //Now I want to do Sorting after grouping to collect only the element which has the highest value of attr2 . Map < String , MyClass > postAnalyticsMap = new HashMa...
Java Stream group by one attribute and collect max element by another attribute
Java
I have a Java puzzle I 'm having trouble solving . Given the following three classes : I need to complete the class B1 , however I want , without change the classes A1 and C1 or adding new files , such that for at least one argument , C1 will always print the string `` success ! `` .I think that I need to override the ...
public class A1 { protected boolean foo ( ) { return true ; } } public class B1 extends A1 { } public class C1 { private static boolean secret = false ; public boolean foo ( ) { secret = ! secret ; return secret ; } public static void main ( String [ ] args ) { C1 c = new C1 ( ) ; for ( int i = 0 ; i < args.length ; i+...
Java puzzle accessing main 's arguments without them being passed in
Java
For Android development in general , is it more expensive to do the following : ( Example 1 ) Over this implementation ( Example 2 ) I could n't find any break down of performance implications when using .get ( ) multiple times instead of creating a new instance of that object each iteration.I 'm thinking that .get ( )...
for ( int x=0 ; x < largeObjectCollection.size ( ) ; x++ ) { largeObjectCollection.get ( x ) .SomeValueOne = `` Sample Value 1 '' ; largeObjectCollection.get ( x ) .SomeValueTwo = `` Sample Value 2 '' ; largeObjectCollection.get ( x ) .SomeValueThree = `` Sample Value 3 '' ; //Continues on to over 30 properties ... } f...
Are there performance implications when using ArrayList.get ( ) many times per iteration ?
Java
This is the userService class that requires a bean of type com.example.repository.userRepository that could not be foundThe error message reads : Consider defining a bean of type 'com.example.repository.userRepository ' in your configuration.This is the repository : this is the application class }
package com.example.services ; import javax.transaction.Transactional ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.stereotype.Service ; import com.example.modal.User ; import com.example.repository.userRepository ; @ Service @ Transactionalpublic class UserService { @ Aut...
Spring boot says it requires a certain bean
Java
I 'm checking out the heterogeneous container pattern from Bloch 's Effective Java and I 'm trying to determine why the class reference is needed when inserting objects into the heterogeneous container . Ca n't I use instance.getClass ( ) to get this reference ? Is n't JPA 's entity manager an example of this ?
interface BlochsHeterogeneousContainer { < T > void put ( Class < T > clazz , T instance ) ; < T > T get ( Class < T > clazz ) ; } interface AlternativeHeterogeneousContainer { // Class < T > not needed because we can use instance.getClass ( ) < T > void put ( T instance ) ; < T > T get ( Class < T > clazz ) ; }
When inserting objects into a type-safe heterogeneous container , why do we need the class reference ?
Java
What is the difference between : And : In both case i end up with an initilized static variable
private static Object myVar = new Object ( ) ; private static Object myVar2 ; static { myVar2 = new Object ( ) ; }
Static initialisers ?
Java
I have two different process ( A and B ) , and A has to start after B , B must not join the A 's transaction , B has to wait until A finish its commit.what propagation should i use ? Now it is like : andNow i use it defult @ Transactional , and its not work properly . I think i should use PROPAGATION.I hope the questio...
@ TransactionalA ( ) @ TransactionalB ( )
Which propagation to use in Spring ?
Java
The result is : but if i delete the finalize method in class A , the result is:so , the result shows that when I override the finalize method , the weak object is n't put into the reference queue , is that because the aObject resurrected ? But I do n't do anything in the finalize method
public class Test { public static void main ( String [ ] args ) throws Exception { A aObject = new A ( ) ; ReferenceQueue < A > queue = new ReferenceQueue < > ( ) ; PhantomReference < A > weak = new PhantomReference < > ( aObject , queue ) ; aObject = null ; System.gc ( ) ; TimeUnit.SECONDS.sleep ( 1 ) ; System.out.pri...
why the reference do n't put into reference queue when finalize method overrided
Java
As I can do to get to see the result of two or more identical numbers contained in a list . Everything has to be based on lists , the code itself is simple but I have no idea how to achieve the same values print screen.All this is done under 5 numbers entered in a list.example : Introduce 1 - 2 - 3 - 3 - 4And the outpu...
package generarlista ; import java.util . * ; public class GenerarLista { /** * @ param args the command line arguments */ public static void main ( String [ ] args ) { int num ; Scanner read = new Scanner ( System.in ) ; List < Integer > lista = new ArrayList < > ( ) ; System.out.println ( `` A list of 5 integers is g...
Equal values in a list java
Java
I would like to concatenate a stream of arrays via a mutable accumulator.Currently I am doing the following for Stream < Foo [ ] > : However , for something that feels quite generically useful , it 's disappointing that the standard library does n't provide something more immediate.Have I overlooked something , or is t...
Foo [ ] concatenation = streamOfFooArrays.collect ( Collector.of ( ArrayList < Foo > : :new , ( acc , els ) - > { acc.addAll ( Arrays.asList ( els ) ) ; } , ( acc1 , acc2 ) - > { acc1.addAll ( acc2 ) ; return acc1 ; } , acc - > acc.toArray ( new Foo [ x.size ( ) ] ) ) ) ;
How should one concatenate a stream of arrays ?
Java
I am a little bit confused about when the class actually is loaded by the JVM . I noticed that the class loader will load the class when the class is referenced.I am using java6 environment and run with -verbose : class for tracking class loading.For example : However , in this casewhen my test program initialize Class...
MyObject obj = new MyObject ( ) ; //MyObject.class will be loaded // ClassC.javapackage com.gogog22510.test ; public class ClassC { } // ClassB.javapackage com.gogog22510.test ; public class ClassB extends ClassC { } // ClassA.javapackage com.gogog22510.test ; public class ClassA { public ClassC test ( ) { return new C...
Confusion about class loading
Java
I 'm a little curious about some of the code that I saw at school and whether or not this is common practice in the field or just bad design.Consider the following interface and the two classes that implement it ... Notice in the Cycle class the arguments in x ( ) and y ( ) are actually used ... But here in the Center ...
public abstract interface Anchor { public abstract double x ( double x ) ; public abstract double y ( double y ) ; } public class Cycle implements Anchor { public Anchor anchor ; public double radius ; public double period ; public double phase = 4.0D ; public Cycle ( Anchor anchor , double radius , double period ) { t...
Is it common practice to have args in a method signature for the sole purpose of fulfilling a contract
Java
I am following an example of strategy pattern from hereEverything in the tutorial is clear but this : So the Context class expects a Strategy argument in its constructor . The definition of Strategy is : The above being an interface , the Context Class expects an object of type Strategy . In the StrategyPatternDemo cla...
public class Context { private Strategy strategy ; public Context ( Strategy strategy ) { this.strategy = strategy ; } public int executeStrategy ( int num1 , int num2 ) { return strategy.doOperation ( num1 , num2 ) ; } } public interface Strategy { public int doOperation ( int num1 , int num2 ) ; } public class Strate...
Unable to understand Strategy pattern
Java
I have a task about building a pyramid using list of numbers , but there is one problem with one test . In my task I need to sort a list . I use Collections.sort ( ) : But this test fails with OutOfMemoryError instead of my own CannotBuildPyramidException ( it will be thrown in another method after sorting ) . I unders...
Collections.sort ( inputNumbers , ( o1 , o2 ) - > { if ( o1 ! = null & & o2 ! = null ) { return o1.compareTo ( o2 ) ; } else { throw new CannotBuildPyramidException ( `` Unable to build a pyramid '' ) ; } } ) ; @ Test ( expected = CannotBuildPyramidException.class ) public void buildPyramid8 ( ) { // given List < Integ...
Java OutOfMemory during sorting
Java
I 'm using the code included here to determine whether given values are valid dates . Under one specific case , it 's evaluating the following street address : 100 112TH AVE NEObviously not a date , but Java interprets it as : Sun Jan 12 00:00:00 EST 100The code in question : The console returns : 11:41:40.063 DEBUG Te...
String DATE_FORMAT = `` yyyyMMdd '' ; try { DateFormat dfyyyyMMdd = new SimpleDateFormat ( DATE_FORMAT ) ; dfyyyyMMdd.setLenient ( false ) ; Date formattedDate ; formattedDate = dfyyyyMMdd.parse ( aValue ) ; console.debug ( String.format ( `` % s = % s '' , '' formattedDate '' , formattedDate ) ) ; } catch ( ParseExcep...
Java DateFormat.parse thinks `` 100 112TH AVE NE '' is a date
Java
I 've got an implementation of the k-means algorithm and I would like to make my process faster by using Java 8 streams and multicore processing.I 've got this code in Java 7 : And I would like to use Java 8 with parallel streams to speed up the process.I have tried a bit and came up with this solution : This solution ...
//Step 2 : For each point p : //find nearest clusters c//assign the point p to the closest cluster cfor ( Point p : points ) { double minDst = Double.MAX_VALUE ; int minClusterNr = 1 ; for ( Cluster c : clusters ) { double tmpDst = determineDistance ( p , c ) ; if ( tmpDst < minDst ) { minDst = tmpDst ; minClusterNr = ...
for each loops as streams in Java8 - k-means
Java
I have a webservice call to get an authorization token and use it for subsequent webservice calls . Now what we had done earlier was whenever we make any web service call , we first make the token web service and then make the call for actual web service . Method to get the token is as shown below . Basically what this...
public static String getAuthTicket ( ) { String authTicket = null ; HttpResponse httpResponse = getAuthResponse ( ) ; String body ; if ( httpResponse.getStatusLine ( ) .getStatusCode ( ) == 200 ) { try { body = IOUtils.toString ( httpResponse.getEntity ( ) .getContent ( ) ) ; Gson gson = new GsonBuilder ( ) .disableHtm...
Making static method Synchronized or Not
Java
I 'm playing with Java 15 's new records feature , and how it interacts with reflection . I 've run into some strange behaviour , where I can sometimes access a record 's constructor via reflection , and sometimes not . For example , given the following Java file : Recording.java : This behaves as follows : In other wo...
public class Recording { public static void main ( String [ ] args ) { System.out.println ( `` Constructors : `` + MainRecord.class.getConstructors ( ) .length ) ; System.out.println ( `` Methods : `` + MainRecord.class.getDeclaredMethods ( ) .length ) ; } record MainRecord ( int i , String s ) { } } ❯ javac -- enable-...
Java record constructor invisible through reflection
Java
I was digging in sources of Android by looking for an answer of how system recognizes @ null keyword that mentioned in a layout . For instance , So far I followed this route : TypedArray # getDrawable ( int index ) ResourcesImpl # getValue ( @ AnyRes int id , TypedValue outValue , boolean resolveRefs ) AssetManager # g...
< LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : background= '' @ null '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' / >
How Android interprets @ null keyword in layouts ?
Java
I am trying to get the group by , count and sum from list of the object using java stream and collection . I am not sure how do I achieve the desired result . InputModelInputModel [ ( May,100 , IT,10 ) , ( June,300 , IT,7 ) , ( July,300 , IT,7 ) , ( May,1000 , HR,5 ) , ( June,300 , HR,7 ) , ( July,600 , HR,5 ) ] Output...
String month ; BigDecimal salary ; String department ; String noOfEmp ; String monthBigDecimal salaryString noOfEmp Map < String , Integer > result= inputModels.parallelStream ( ) .collect ( Collectors.groupingBy ( InputModel : :getMonth , LinkedHashMap : :new , Collectors.summingInt ( InputModel : :getNoOfEmp ) ) ) ;
How to perform group by , count and sum from list of object in single stream and store in another list of object ?
Java
Someone asked this question yesterday . I understand that java interprets 3.0 to be a double , and 3f to be a float , and the doubles have 64-bit precision and floats have 32-bit precision . If someone asked me , I would have given an answer similar to the ones given ; however , I wanted to provide empirical evidence t...
System.out.println ( `` Double : `` + Double.toHexString ( d ) ) ; //prints 0x1.8p1 System.out.println ( `` Float : `` + Float.toHexString ( f ) ) ; //prints 0x1.8p1 System.out.println ( `` Double : `` + new Double ( d ) .byteValue ( ) ) ; //prints 3 System.out.println ( `` Float : `` + new Float ( f ) .byteValue ( ) )...
Issues obtaining empirical evidence to show difference in internal storage between float and double
Java
I have the following List : I need to order it with this condition : In the first place , the ones that contains the char `` o '' or `` O '' Then , the rest of them.The result should be : How can I do it in Java 8 ?
List < String > fruits = new ArrayList < String > ( Arrays.asList ( `` Apple '' , `` Banana '' , `` Orange '' , `` Watermelon '' , `` Peach '' ) ) ; Orange , Watermelon , Apple , Banana , Peach
Ordering List by a specific character ( Java 8 )
Java
Is it important to save all class code as individual .java files like following way ? Or can I make a single java file as Test.java . Please explain anonymous class , how can we create anonymous class in java , and what is the advantage/disadvantage over normal class ?
Outer.java , Inner.java , Test.java class Outer { private int data = 50 ; class Inner { void msg ( ) { System.out.println ( `` Data is : `` + data ) ; } } } class Test { public static void main ( String args [ ] ) { Outer obj = new Outer ( ) ; Outer.Inner in = obj.new Inner ( ) ; in.msg ( ) ; } }
Is this necessary to make two class of this java program ?
Java
I have a spring restful web service and am trying to save to a database named little-data but my app keeps saving to the test database instead . Below is my application.yml file : I have also tried this for my application yaml file : And here is my model for posts : All of the requests work fine but they save to the wr...
spring : data : mongodb : port : 27017 uri : mongodb : //127.0.0.1/little-data repositories : enabled : true authentication-database : adminserver : port : 8090 spring : data : mongodb : host : 127.0.0.1 port : 27017 database : little-data repositories : enabled : true authentication-database : adminserver : port : 809...
Spring app saving documents to test db instead of custom db
Java
I 'm using the Java Scanner.I have a .txt file with this text saved in it . All I am trying to do is open this file with a scanner and extract the `` CurrentValue '' of 70,197 from the file and save it as an int . However , every time the file is opened it will not read a line and throws a NoSuchElementException with `...
PriceDB = { [ `` profileKeys '' ] = { [ `` Name - 回音山 '' ] = `` Name - 回音山 '' , } , [ `` char '' ] = { [ `` Name - 回音山 '' ] = { [ `` CurrentValue '' ] = `` 一口价:|cffffffff70,197|TInterface\\MoneyFrame\\UI-GoldIcon:0:0:2:0|t|r '' , } , } , } Scanner scanner ; if ( region.equals ( `` US '' ) ) { scanner = new Scanner ( ne...
Why is this character 口 causing my scanner to fail ?
Java
Output :
//take the input from usertext = br.readLine ( ) ; //convert to char arraychar ary [ ] = text.toCharArray ( ) ; System.out.println ( `` initial string is : '' + text.toCharArray ( ) ) ; System.out.println ( text.toCharArray ( ) ) ; initial string is : [ C @ 5603f377abcd
different behaviour of println ( ) in java
Java
I have the following code on my main method , and when I iterate through the Set and print the values , the values are already sorted . What 's the reason ? Output :
Set < Integer > set = new HashSet < Integer > ( ) ; set.add ( 2 ) ; set.add ( 7 ) ; set.add ( 3 ) ; set.add ( 9 ) ; set.add ( 6 ) ; for ( int i : set ) { System.out.println ( i ) ; } 23679
Why the class HashSet < T > has values already sorted when I use the iterator ?
Java
My code as followsI run the program and I found its output is 5 15.It made me confused , I ca n't understand what differences between using for statements and using foreach statements.Thanks for giving me a hand .
public class Test { public static void main ( String [ ] args ) { int count1 = 0 , count2 = 0 ; Test [ ] test1 = new Test [ 5 ] ; Test [ ] test2 = new Test [ 5 ] ; if ( test1 == null || test2 == null ) System.out.println ( `` null '' ) ; for ( int j = 0 ; j < 3 ; j++ ) { for ( int i = 0 ; i < test1.length ; i++ ) { if ...
Error occured while using java foreach statements
Java
I just wrote some code with the following structure : I was rather surprised that this compiled , and that if I invokedthen it would pick the first one . Obviously this is in some sense the natural one to pick , but if the first method did n't exist , this would be a reasonable way of invoking the second ( with an empt...
public void method ( int x ) { // ... } public void method ( int x , String ... things ) { // ... } method ( 3 ) ;
Why does this not produce an ambiguity ?
Java
I have a HashMap < Integer , Integer > and i 'm willing to get the key of a specific value.for example my HashMap : I 'm looking for a java stream operation to get the key that has the maximum value . In our example the key 2 has the maximum value.So 2 should be the result.with a for loop it can be possible but i 'm lo...
Key|Vlaue2 -- - > 31 -- - > 05 -- - > 1 import java.util . * ; public class Example { public static void main ( String [ ] args ) { HashMap < Integer , Integer > map = new HashMap < > ( ) ; map.put ( 2,3 ) ; map.put ( 1,0 ) ; map.put ( 5,1 ) ; ///////// } }
get a specific key from HashMap using java stream
Java
In an Android example class theres this method : When I reference the class , the items are indeed added . I never saw a method like this , a. how is this called and b. I suppose this method is called whenever the class is referenced ( or the first time it is referenced ) ?
static { addItem ( ... ) ; }
Static method without a name
Java
In Java , I see a lot of codes like below.What I am wondering is , is it enough just to show error message ? I am new to Java . What I want to learn is how to handle error efficiently , and know best practices for error-handling . In general , what should I do in catch block ? Example 1 : printStackTrace ( ) Example 2 ...
} catch ( SomeException e ) { e.printStackTrace ( ) ; } } catch ( SomeException e ) { e.getMessage ( ) ; } } catch ( IOException E ) { System.out.println ( `` Error occured . Please try again . `` ) ; }
What to do when catching e ( rror ) in Java
Java
I have tried with data and data1 variables . It 's always calling to String ... data.So , what is the difference between String [ ] data and String ... data in java .
public class ArrayTest { public static void main ( String [ ] args ) { ArrayTest arrayTest = new ArrayTest ( ) ; // Option one String [ ] data = { `` A '' , `` B '' , `` C '' } ; // Option two String data1 = `` A '' ; arrayTest.test ( data ) ; } public void test ( String [ ] ... data ) { System.out.println ( `` -- -Fro...
What is the difference between String [ ] data and String ... data in java
Java
Why this is happening . If I pass anonymous generic class to type determination method - all is good . But if I pass object in this method - console output is E. Console : Please explain to me .
public static void main ( String [ ] args ) { printType ( new ArrayList < Integer > ( ) { } ) ; printType ( new ArrayList < Integer > ( ) ) ; } public static void printType ( final List < ? > list ) { System.out.println ( ( ( ParameterizedType ) list.getClass ( ) .getGenericSuperclass ( ) ) .getActualTypeArguments ( ) ...
Runtime generic type determination
Java
I faced an interesting problem today : Lets suppose the following conditions1 . There are n number of users2 . The system collects GPS coordinates of each driver as they move3 . We have to query last 10 GPS Coordinate records per user sorted by LAST_UPDATE_DATE in descending order4 . There are over 1982008 records in t...
CREATE TABLE ` gps_coordinate ` ( ` ID ` BIGINT ( 50 ) NOT NULL AUTO_INCREMENT , ` user_id ` VARCHAR ( 255 ) NULL DEFAULT ' 0 ' , ` driver_id ` INT ( 20 ) NULL DEFAULT ' 0 ' , ` latitude ` VARCHAR ( 50 ) NULL DEFAULT ' 0.00000000 ' , ` longitude ` VARCHAR ( 50 ) NULL DEFAULT ' 0.00000000 ' , ` distance_in_miles ` VARCH...
TOP [ N ] Records Group By per user query in the best possible way
Java
I am new to Java . While learning the printf method I came across the below question : What would be the output of following program ? The answer is : Can someone help me to understand how true is getting printed without me passing it ?
System.out.printf ( `` % 1 $ d + % b '' , 456 , false ) ; System.out.println ( ) ; System.out.printf ( `` % 1 $ d + % b '' , 456 ) ; 456 + true456 + true
System.out.printf ( ) usage
Java
I want to implement a simple Cache interface : I realized it 's part of interface java.util.Map . So objects like HashMap should be able to be be passed to functions needing a Cache object.But on the other hand I do n't want to make my own Cache class implement the whole Map interface because I do n't really need other...
public interface Cache { Object get ( Object key ) ; Object put ( Object key , Object value ) ; void clear ( ) ; }
Partially inherit an interface in Java ?
Java
Above line 's output is , While below line 's , output is , Why does 2e-5 is not solved down with -10^5 giving the output ,
System.out.println ( 2e+5 ) ; 200000.0 System.out.println ( 2e-5 ) ; 2.0e-5 0.00002
Why does +e canceled and -e not ?
Java
The following code will set str to `` testss '' Where as the following code will set it to `` tests '' I would have expected both operations to produce the same result . Can someone explain why replaceAll adds an extra s to the end of the string ?
String str = `` test '' .replaceAll ( `` ( . * ) $ '' , '' $ 1s '' ) ; String str = `` test '' .replaceFirst ( `` ( . * ) $ '' , '' $ 1s '' ) ;
Why replaceFirst and replaceAll give different results ?
Java
As a result of me trying to extract some common wrapping lambda routines that I use in most of my projects , I 've been able to create CheckedFunction , subclassed by PermeableFunction FunctionalInterface that bypasses the need of try/catch blocks . I 've tested that on Oracle jdks for windows ( v1.8.0_251 ) /linux ( v...
import java.nio.file.Files ; import java.nio.file.Path ; import java.nio.file.Paths ; import java.util.function.Function ; public class Main { public static void main ( String [ ] args ) { PermeableFunction < Path , Long > function = PermeableFunction.from ( Files : :size ) ; Path doesNotExist = Paths.get ( `` /does/no...
Lamdas that bypass try/catch blocks for checked exceptions
Java
I noticed that if else / ternary ( condition ? a : b ) assigment is faster than conditional assigment in if only statement . I performed JMH benchmarks on different JDKs but i will focus on JDK 12 . ( ops / sec , higher is better ) Source code : findMax_if_else perfasm output ( ternary is almost the same ) : findMax_if...
@ State ( Scope.Benchmark ) public class FindMaxBenchmark { public static int SIZE = 1_000_000 ; @ Benchmark @ CompilerControl ( CompilerControl.Mode.DONT_INLINE ) public static void findMax_if ( Blackhole bh , Mock mock ) { int result = Integer.MIN_VALUE ; int [ ] data = mock.tab ; for ( int i = 0 ; i < data.length ; ...
Different performance of `` if '' and `` if else '' in Java