lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have a SpringBootApplication , packaged as war file : on the application.properties : but on the logs I see those messages when I deploy the war in the Tomcat 9 : the logs : on my tomcat9/conf/context.xml :
@ SpringBootApplication ( exclude = { SecurityAutoConfiguration.class } ) public class Application extends SpringBootServletInitializer { public static void main ( String [ ] args ) { SpringApplication.run ( Application.class , args ) ; } @ Override protected SpringApplicationBuilder configure ( SpringApplicationBuilde...
Configure DataSource Using JNDI Using external Tomcat 9 Server : Spring Boot
Java
I am adding screenshot for some more information . I am new to Java8 , kindly forgive me if I am asking a bad question . When I was doing research for input of space separated value I got this statement . I understand that below statement takes value as 1 2 3 and returns value [ 1 , 2 , 3 ] as a list.Kindly correct me ...
List < Integer > a = Stream.of ( bufferedReader.readLine ( ) .replaceAll ( `` \\s $ '' , `` '' ) .split ( `` `` ) ) .map ( Integer : :parseInt ) .collect ( toList ( ) ) ; [ 1 ] : https : //i.stack.imgur.com/nlXxd.jpg
Trying to understand the complete meaning of a below statement Stream.of ( bufferedReader.readLine ( ) .replaceAll ( `` \\s $ '' , `` '' )
Java
I am writing some code to handle a stream of binary data . It is received in chunks represented by byte arrays . Combined , the byte arrays represent sequential stream of messages , each of which ends with the same constant terminator value ( 0xff in my case ) . However , the terminator value can appear at any point in...
[ 0x00 , 0x0a , 0xff , 0x01 ] [ 0x01 , 0x01 ] [ 0xff , 0x01 , 0xff ] [ 0x00 , 0x0a , 0xff ] [ 0x01 , 0x01 , 0x01 , 0xff ] [ 0x01 , 0xff ]
Tokenising binary data in java
Java
I am creating a project which will respond to collect multiple bean object , save it to the database and return the status of the transaction . There can be multiple objects that can be sent from the client . For each object , they are having separate database thus separate controller.So I planned to create a framework...
@ RestController @ RequestMapping ( `` /stat/player '' ) public class PlayerController { @ Autowired private StatService < PlayerValue > statPlayer ; @ RequestMapping ( `` /number/ { number } '' ) public Object findByNumber ( @ PathVariable String number ) { // Here returning Object seem odd return statPlayer.findByNum...
Convert automatically into a centralized bean for multiple domain objects
Java
I wanted to pass object as a parameter instead of class object as type literal . I tried many ways but did not get output . If i 'm running above code that will accept following values as parameter passing . If I have a FormBean class thenI want that method can only accept already created intance object . I can not eve...
public < T > List < Map < String , Object > > getUIElementsList ( Class < T > requiredType ) { doSomeThing ( ) ; return this.fieldList ; } FormBean formBean = new FormBean ( ) ; formBean.setUserId ( 252528 ) ; getUIElementsList ( FormBean.class ) ; //restrict this casegetUIElementsList ( formBean ) ;
How do I restrict method to accept only object as parameter instead of Class Objects as Type Literals ?
Java
I wrote a Java program that sleeps for a while : I run the program with : I inspect the processes that Ubuntu creates to run it : What are those threads ( i.e . lightweight processes ) named { java } created for ? Is it possible to find out what programs they run from shell using some commands ? Which processes ( and L...
package com.mycompany.app ; import java.lang.System ; import java.util.concurrent.TimeUnit ; public class Main { public static void main ( String [ ] args ) { System.out.println ( `` the current process 's pid is `` + ProcessHandle.current ( ) .pid ( ) ) ; try { TimeUnit.SECONDS.sleep ( 200 ) ; } catch ( InterruptedExc...
What are threads ( i.e . lightweight processes ) named ` { java } ` created for ?
Java
Is it the compiler or the runtime do the auto-boxing/unboxing ? Consider the following example : At ( 1 ) , the primitive integer value will be converted into something like new Integer ( 1 ) , and returned . That 's effectively some kind of implict consverion known as auto-boxing , but who will do that ? The compiler ...
public Integer get ( ) { return 1 ; // ( 1 ) }
Who will do the Auto-boxing/unboxing ?
Java
The documentation of the sorted operation says : For ordered streams , the sort is stable . For unordered streams , no stability guarantees are made . and the page-summary says : Some intermediate operations , such as sorted ( ) , may impose an encounter orderCan someone explain why sorted operation needs an encounter ...
Set < Integer > mySet = new HashSet < > ( ) ; mySet.add ( 10 ) ; mySet.add ( 4 ) ; mySet.add ( 20 ) ; mySet.add ( 15 ) ; mySet.add ( 22 ) ; mySet.add ( -3 ) ; List < Integer > result = mySet.stream ( ) .sorted ( ) .collect ( Collectors.toList ( ) ) ; System.out.println ( result ) ; mySet.stream ( ) .parallel ( ) .sorte...
Why sorted operation impose an encounter order to a Stream ?
Java
I got a bit of a struggle setting up IntelliJ for a JavaFX project.I set it up using File > Project Structure > Libraries > Add new library > From Maven searching for org.openjfx : javafx-fxml:11.0.2 . So it was found and I deliberately checked Download JavaDocs since this would be useful.However , when I tried to star...
-- module-path lib -- add-modules javafx.controls , javafx.fxml
IntelliJ - JavaFX and JavaDoc : Two versions of module
Java
The following code simply subtracts a value ( 10 in this case , just for the demonstration ) from the current year obtained by using the java.util.Calendar class.I expect this code to display 2003 ( current year - 10 ) but instead , it displays -10 . I assume the constant YEAR has n't been initialized . Why does this h...
public final class Test { private static final Test TEST = new Test ( ) ; private static final int YEAR = Calendar.getInstance ( ) .get ( Calendar.YEAR ) ; private final int eval=YEAR - 10 ; public static void main ( String [ ] args ) { System.out.println ( `` Evaluation `` +TEST.eval ) ; } }
Static members not initialized as expected
Java
I need to develop a Java version of the Iterated Prisoner Dilemma using Repast Simphony as simulator.The ideas is that each Player is an agent , and we have a n x n grid of Player that ca n't be moved . Each Player has to play with 4 neighbours ( northern , southern , western and eastern one ) , finding the best strate...
// myPoint is the location inside the grid ( unique , agents ca n't move and only one per cell is allowed ) public int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = prime * result + ( ( myPoint == null ) ? 0 : myPoint.hashCode ( ) ) ; return result ; } // Returns enemy 's choice in the previous roundp...
Unexpected results using Repast Simphony
Java
I was playing around with Java 9 with the prod code . And I found a couple of Formatting tests failing . After some research , I was able to create a class to reproduce the issue . Which happens in Java 9 but not in Java 8.The class is herehttps : //pastebin.com/87sA5WMbBasically comparing 2 strings : An string literal...
import java.text . * ; import java.util . * ; public class FormatFails { public static void main ( String ... args ) { Currency currency = Currency.getInstance ( `` EUR '' ) ; NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance ( Locale.FRANCE ) ; currencyFormatter.setMaximumFractionDigits ( 0 ) ; currenc...
Equals over String literal and String coming from NumberFormat fails due to different byte representation
Java
In answering this question about lambdas which capture local variables , I defined a simple lambda which captures a local variable , and showed that the lambda has a field with that variable 's value . According to various sources ( e.g . here , here ) , when a lambda captures a local variable , its value is stored in ...
> class A { static Runnable a ( int x ) { return ( ) - > System.out.println ( x ) ; } } | created class A > Runnable r = A.a ( 5 ) ; r == > A $ $ Lambda $ 15/1413653265 @ 548e7350 > import java.lang.reflect.Field ; > Field [ ] fields = r.getClass ( ) .getDeclaredFields ( ) ; fields == > Field [ 1 ] { private final int ...
Lambda field capturing local variable .isSynthetic ( ) returns false
Java
Looking into another question I bumped into this intriguing behavior of the 1.8.0_112 Sun-Oracle compiler ( I have not tested with others ) : The compiler only fails at the last for loop : So despite that intList ( ) return list type List < Integer > in Alpha does not depend on the type parameter T , it seems that the ...
import java.util.List ; interface Alpha < T > { List < Integer > intList ( ) ; } interface Beta { List < Integer > intList ( ) ; } class Main { public static void main ( String [ ] args ) { Alpha rawAlpha = null ; Alpha < Character > charAlpha = null ; Alpha < ? > qmAlpha = null ; Beta beta = null ; for ( Integer i : c...
Why does using raw type variables affect signatures without reference to type-parameters ?
Java
I have try and catch block in JAVA codeAnd my compiled class look like /* * Decompiled with CFR 0.145 . */ ... ... ..I wounder why another try block added in compile time.Full Source code in https : //github.com/vikram06/java_try_catch_bug
import java.io.FileOutputStream ; import java.util.zip.ZipOutputStream ; public class TryTest { public static void main ( String [ ] args ) { String zipPath = '' D : /test '' ; try ( ZipOutputStream zipOut = new ZipOutputStream ( new FileOutputStream ( zipPath ) ) ) { String Hello = '' Hello '' ; System.out.println ( `...
compiled class problem in java try/catch block
Java
Edit : I 've realised that this pattern feels a lot like currying , a technique that functional programmers use to specify function parameters in advance of invocation . The difference here is that we 're currying constructors on objects instead of simply currying functions.Throughout a couple of projects I 've found m...
public abstract class CommentDetector { private final String startPattern ; private final String endPattern ; protected CommentDetector ( String startPattern , String endPattern ) { this.startPattern = startPattern ; this.endPattern = endPattern ; } public boolean commentStartsAt ( int index , String sourceCode ) { // ...
Is there a name for this Design Pattern ? ( Base class with implementations that only invoke constructor )
Java
I 'm working with data of the following form ( four examples given , each separated by a new line ) : I need to extract the publication name and - in case it exists - the issue number . This has to be done with a regex.So given above data , I am looking for finding the following results : The following pattern works on...
some publication , issue no . 3another publication , issue no . 23yet another publicationhere is another publication some publication 3another publication 23yet another publication < null > here is another publication < null > String underTest = `` some publication , issue no . 3 '' ; String pattern = `` ( .* ? ) , iss...
capture group with optional substring
Java
This program does n't do what I wanted . It prints `` sad '' twice , whereas I was hoping it would print `` happy '' and then `` sad '' .
public class Woof { public static class Arf < T > { T yap ; public Arf ( T yap ) { this.yap = yap ; } public String woof ( ) { /* * Should select which doYapStuff ( ) based on whether T * happens to be an Integer , or something else . */ return doYapStuff ( yap ) ; } /* Special case implementation of doYapStuff ( ) whe...
Unable to choose appropriate method using Java Generics
Java
consider this code snippet prints what i am expecting to see first i thought it might be the precedence of ~ and ++ if the ~ is evaluated before ++ the answer will be else if the ++ is evaluated before ~ I searched Oracle tutorials but I could n't find the answer.Can anyone explain this behavior ?
int j = 7 ; System.out.println ( Integer.toBinaryString ( j ) ) ; j = ~j++ ; System.out.println ( Integer.toBinaryString ( j ) ) ; 11111111111111111111111111111111000 11111111111111111111111111111111001 11111111111111111111111111111001 11111111111111111111111111110111
precedence of ~ and ++ in java
Java
I am trying to convert the following PostgreSQL query to jOOQ : What I have is : Is there a way to do using jOOQ 's fluent API so I do n't have to use strings ?
SELECT count ( * ) , to_char ( created_date , 'YYYY-MM-DD ' ) as year_month_date FROM log GROUP BY year_month_date ORDER BY year_month_date jooq.select ( DSL.count ( ) , DSL.field ( `` to_char ( created_date , 'YYYY-MM-DD ' ) as year_month_date '' ) ) .from ( LOG ) .groupBy ( DSL.field ( `` year_month_date '' ) ) .orde...
How do I use Postgres 's to_char in a jOOQ query ?
Java
I got the following Expression that can look like this ( the amount of Sqrt [ XXX ] is unknow ) and I want to turn all Sqrt [ XXX ] into Sqrt ( XXX ) , I want to replace the [ ] brackets of the Sqrt into ( ) bracketsso the above example will look like Sqrt ( A+B ) + Sqrt ( Min [ A , B ] ) * Min [ Sqrt ( C ) , D ] I do ...
Sqrt [ A+B ] + Sqrt [ Min [ A , B ] ] * Min [ Sqrt [ C ] , D ]
How to turn several `` Sqrt [ some text inside ] '' into several Sqrt ( some text inside ) , I mean from [ ] into ( )
Java
Is there an efficient and least redundant way to conditionally put new items in map.The best I can do is the following , but was curious if there was a better way to do the above in Java 9 .
GenericObject genericObject ; ... FieldObject obj = genericObject.getFieldObject ( ) ; if ( obj == null ) { map.put ( `` key1 '' , null ) ; map.put ( `` key2 '' , null ) ; } else { map.put ( `` key1 '' , obj.getField1 ( ) ) ; map.put ( `` key2 '' , obj.getField2 ( ) ) ; } boolean insert = obj ! = null ; map.put ( `` ke...
Efficient way to conditionally add items to HashMap
Java
I want to compare the response from the server with a string , but I get a false result when testing the two strings . Why ? I found this but did n't help : How do I compare strings in Java ? I tried two ways : The code does not run in either case because the value of the test is false.Full codeServer side - C # ( Wind...
BufferedReader in = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) , `` UTF8 '' ) ) ; String code ; if ( Objects.equals ( ( code = in.readLine ( ) ) , `` S '' ) ) { //Input string : `` S '' //code } BufferedReader in = new BufferedReader ( new InputStreamReader ( socket.getInputStream ( ) , `` U...
Why do n't the two equal strings match ?
Java
A friend of mine noticed that was valid in Java . It turns out that the type of list is evaluated to ArrayList < Double > . When using var < Integer > list = new ArrayList < > ( ) ; , list is just ArrayList < Object > .Both of us were not able to figure out , what the generic type of var does , as it seems to be ignore...
var < Integer > list = new ArrayList < Double > ( ) ;
What does var < T > do in Java ?
Java
I 've created my own exception but when I try to use it I receive a message saying that it ca n't be cast to my exception I 've got one interface like thisother like this one and finally a method in another classThis try catch block on the last method is to make maths operation and I want to catch a division by zero ex...
public interface MyInterface { public OtherClass generate ( ClassTwo two , ClassThree three ) throws RetryException ; } public class MyGenerator { public class generate ( ClassTwo two , ClassThree three ) { try { } catch ( MyException my ) } } public Object evaluate ( String expression , Map values ) throws FirstExcept...
Problems handling Exceptions
Java
Going through the java.lang.module I read amongst a class documentation the following : What are the causes from using lambda and streams that are avoided here and what are their possible impacts ? Illustrations would help understand better , not looking for opinions here though .
@ implNote ... is used at VM startup and so deliberatelyavoids using lambda and stream usages in code paths used duringstartup .
Avoiding lambda and stream usage for a class used at VM Startup
Java
I 'm faced with the issue that I need to convert time from 24 format to AM/PM format ( and vice-versa ) removing redundant values such as nanoseconds and seconds by time4j library.I 'm using the time4j library because Java ca n't handle Windows Time Zones and I have to convert them via time4jConversion from 24 hour for...
WindowsZone wzn = WindowsZone.of ( userTimeZoneId ) ; //userTimeZoneId= '' eg . FLE Standart Time '' TZID winZone = wzn.resolveSmart ( new Locale ( `` '' , '' 001 '' ) ) ; System.out.println ( winZone.canonical ( ) ) ; // WINDOWS~Europe/Kiev PlainTime currentTime = SystemClock.inZonalView ( winZone ) .now ( ) .toTime (...
How to convert time 24-hour to AM/PM and remove nanoseconds & seconds via time4j ?
Java
The core Java classes pointed to by the famous BalusC answer ( https : //stackoverflow.com/a/2707195 ) : All the above seem to be classes with private constructors instead of being enums . If enum is the best practice to implement a singleton pattern ( Why is Enum best implementation for Singleton ) , why was it not us...
java.lang.Runtime # getRuntime ( ) java.awt.Desktop # getDesktop ( ) java.lang.System # getSecurityManager ( )
Why does the core Java library NOT use enums for implementing the singleton pattern ?
Java
In android I would like to draw flower by adding each petal from a center point . I used setRotation on the image view but the center point is different for each petal . ( I mean the center point from the flower ) Can anybody look at my code and suggest me correction ? Thanks.Image I get is this
int angle=0 ; int ypos=500 ; int xpos=500 ; RelativeLayout layout = ( RelativeLayout ) findViewById ( R.id.ln1 ) ; for ( int i=0 ; i < 10 ; i++ ) { ImageView image = new ImageView ( this ) ; image.setLayoutParams ( new android.view.ViewGroup.LayoutParams ( 150,400 ) ) ; image.setX ( xpos ) ; image.setY ( ypos ) ; image...
How To Draw A Flower In Android Each Petal By Petal
Java
I have the below classes.I have manually compiled the classes using javac and ran the Driver class.Later removed the entity.class and MyCustomException.class and ran the app like below . java Driver testThe below error is complained about MyCustomException is missing but not about the Entity class . So , not clear why ...
Caused by : java.lang.NoClassDefFoundError : com/techdisqus/exception/MyCustomException public class MyCustomException extends RuntimeException { } public class Entity { } public class Driver { public static void main ( String [ ] args ) { String s = args [ 0 ] ; if ( `` true '' .equals ( s ) ) { Entity entity = new En...
Why throwing an exception tries to loads the class which extends Exception ( though it is not executed ) but not a regular class
Java
The java.time.Duration class built into Java 8 and later represents a span of time unattached to the timeline on the scale of hour-minutes-seconds . The class offers a plus method to sum two such spans of time . The java.time classes use immutable objects . So the Duration : :plus method returns a new third Duration ob...
Duration total = Duration.ZERO ; for ( Duration duration : durations ) { total = total.plus ( duration ) ; }
Using streams to sum a collection of immutable ` Duration ` objects , in Java
Java
I was learning about Streams in Java 8.For example , If I have to double a number : If I have to square a number , then I can use below : But If I have to apply both functions on same Integer array using `` andThen '' method java.util.function.Function , I am doing it via : Is it possible to rewrite this ( 3 statements...
Arrays.stream ( intArray ) .map ( e- > e*2 ) .forEach ( System.out : :println ) ; Arrays.stream ( intArray ) .map ( e- > e*e ) .forEach ( System.out : :println ) ; Function < Integer , Integer > times2 = e - > e * 2 ; Function < Integer , Integer > squared = e - > e * e ; Arrays.stream ( intArray ) .map ( times2.andThe...
Rewrite the algorithm in java stream with less effort ?
Java
I 'm working on an application using Spring Boot and Thymeleaf.I have the following snippet in my custom login page : This paragraph is associated with the following security config : So after a logout the user is redirected to /login ? logout and the logout message is shown.My problem is this message is also shown whe...
< p th : if= '' $ { param.logout } '' > Logged out successfully < /p > @ Overrideprotected void configure ( HttpSecurity http ) throws Exception { http .authorizeRequests ( ) .antMatchers ( `` / '' , `` *.css '' ) .permitAll ( ) .antMatchers ( `` /myendpoint '' ) .authenticated ( ) .and ( ) .formLogin ( ) .loginPage ( ...
Is it possible to allow access to a page only through redirection ?
Java
I 'm in a weird situation where have a JSON API that takes an array with strings of neighborhoods as keys and an array of strings of restaurants as values which get GSON-parsed into the Restaurant object ( defined with a String for the neighborhood and a List < String > with the restaurants ) . The system stores that d...
public Map < String , Set < String > > parseApiEntriesIntoMap ( List < Restaurant > restaurants ) { if ( restaurants == null ) { return null ; } Map < String , Set < String > > restaurantListByNeighborhood = new HashMap < > ( ) ; // Here we group by neighborhood and concatenate the list of restaurants into a set Map < ...
Is there a way to concatenate grouped lists into a set in Java 8 in one line ?
Java
I declared a data class like this : My code is : The console output is : name is nullHow is this possible ? The name attribute is not a nullable string .
data class Product ( val name : String = `` '' , val price : Float = 0f ) val json = `` { 'name ' : null , 'price ' : 50.00 } '' val gson = GsonBuilder ( ) .create ( ) val p = gson.fromJson ( json , Product : :class.java ) println ( `` name is $ { p.name } '' )
Why is Kotlin accepting a null value in an attribute declared as a non-nullable string ?
Java
I have a simple JMX application that has exposed MBeans based on this tutorialIs it possible to launch this application with a custom class in the classpath that extends JCONSOLE , so that when a client tries to access it remotely the extended jconsole window opens ? So for example , I create a simple application and p...
java -classpath JconsoleExtension.jar ; MyApp.jar -com.sun.management.jmxremote.login.config=management.properties -Djava.security.auth.login.config=./sample_jaas.config com.test.running.RunningImplementation com.sun.management.jmxremote=truecom.sun.management.jmxremote.port=1234com.sun.management.jmxremote.login.confi...
Extending JCONSOLE functionality for client remote connections
Java
I 'm trying out Android 's D8 and R8 . As the documentation says the command to run D8 is the following : And for R8 : I found the d8.jar inside % ANDROID_HOME % \build-tools\28.0.3\lib , but I ca n't find the r8.jar.Where r8.jar is located inside Android SDK ?
java -jar build/libs/d8.jar -- release -- output out input.jar java -jar build/libs/r8.jar -- release -- output out -- pg-conf proguard.cfg input.jar
Where r8.jar is located inside Android SDK ?
Java
I 'm triying to understand the differences between the three methods for managing the UI interactions.I 'm really confused with these three terms when triying to figure them out in a real case.The below code shows the function of the invokeAndWait method , but if I replace it byinvokeLater or getEventLock ( ) the progr...
public final class HelloWorldMainScreen extends MainScreen { private LabelField labelField ; public HelloWorldMainScreen ( ) { labelField = new LabelField ( `` Hello World '' ) ; add ( labelField ) ; MainScreenUpdaterThread thread = new MainScreenUpdaterThread ( this ) ; thread.start ( ) ; } public void appendLabelText...
How to modify this example code in order to show the differences between the three methods for updating the UI in BlackBerry
Java
Looking at the following code , why does n't the second invocation of dump get compiled ? And how can I fix it without removing the wildcard ? The JDK 's compiler gives
import java.util.ArrayList ; import java.util.List ; class Column < A , T extends Object > { } public class Generics { static void main ( String [ ] args ) { Integer i = 5 ; // this works List < Column < Integer , ? > > columns1 = new ArrayList < Column < Integer , ? > > ( ) ; dump ( columns1 , i ) ; // this does n't L...
Wildcard in Generics does n't work
Java
I am having trouble with InputProcessor only on my IOS build . This code works for Desktop and Android builds but not iOS.Basically , I need to catch an event anytime the user types on the onscreen keyboard . But in iOS I only see my println for keyTyped intermittantly and only when i type on the on screen keyboard fas...
game name field key typed ! game name field key typed ! game name field key typed ! I/System.out : game name field key down ! I/System.out : game name field key up ! I/System.out : game name field key typed ! I/System.out : game name field key down ! I/System.out : game name field key up ! I/System.out : game name fiel...
libgdx : IOS on screen keyboard not firing events consistently
Java
I am trying to implement the function : For example if I have Map < String , List < Integer > > , I want to create another Map < Integer , List < String > > . I have written some code : but as you can see this only works if the map in the argument does n't contain list as values .
private static < T , K > Map < T , List < K > > invertedMap ( Map < K , List < T > > m ) private static < T , K > Map < T , List < K > > invertedMap ( Map < K , T > m ) { return m.keySet ( ) .stream ( ) .collect ( Collectors.groupingBy ( k - > m.get ( k ) ) ) ; }
How to create Map < T , List < K > > out of Map < K , List < T > > ?
Java
Can anybody explain why the if statement below evaluates false ? it takes in a `` PolyLine '' object , but instanceof returns false because I get an alert of `` 2 '' followed by an alert of `` 4 '' and have no clue how it 's even possible .
public void addShapeToWhiteboard ( PolyLine shape ) { Window.alert ( `` 2 '' ) ; if ( shape instanceof PolyLine ) { Window.alert ( `` 3 '' ) ; this.whiteboard.add ( ( PolyLine ) shape ) ; Window.alert ( `` 3.5 '' ) ; } this.whiteboard.draw ( ) ; Window.alert ( `` 4 '' ) ; }
Java 's instanceof odd behavior
Java
This is in continuation of my previous question . As the original question is closedAs per accepted answer , tasklet can be used , I have also tried implementing custom item writer in a chunk oriented step which uses jackson / JsonFileItemWriter , can we use this or does it have any performance impact ? Question 1 : ``...
public void write ( final List < ? extends Person > persons ) throws Exception { for ( Person person : persons ) { objectMapper.writeValue ( new File ( `` D : /cp/dataTwo.json '' ) , person ) ; } }
Spring Batch Write processed records to file
Java
I am new to the Stream API.I have a question about Stream API , specifically the parallel and sequential stream . The question is : if , for example , i have a pseudo-code like this : Is the Stream API going to execute filter in parallel and mapping sequentially , or does it merely change the `` parallel-characteristic...
someStream .parallel ( ) .filter ( some_predicate ) .sequential ( ) .map ( some_mapping_function ) .terminal_operation ( ) ;
Java Stream API - Parallel and Sequential Streams
Java
In Java 8 , if I have two interfaces with different ( but compatible ) return types , reflection tells me that one of the two methods is a default method , even though I have n't actually declared the method as default or provided a method body.For instance , take the following code snippet : Java 1.8 produces the foll...
package com.company ; import java.lang.reflect.Method ; interface BarInterface { } class Bar implements BarInterface { } interface FooInterface { public BarInterface getBar ( ) ; } interface FooInterface2 extends FooInterface { public Bar getBar ( ) ; } class Foo implements FooInterface2 { public Bar getBar ( ) { throw...
When two interfaces have conflicting return types , why does one method become default ?
Java
Using records ( preview feature java-14 ) in a jlink : ed application , gives below error when using options :
options = [ ' -- strip-debug ' , ' -- compress ' , ' 2 ' , ' -- no-header-files ' , ' -- no-man-pages ' ] java.lang.ClassFormatError : Invalid constant pool index 11 for name in Record attribute in class file myproj/MyClass $ MyRecord at java.base/java.lang.ClassLoader.defineClass1 ( Native Method ) at java.base/java.l...
Records in jlink : ed application throws exception
Java
Suppose the following generic class with 2 types T , Uand the list of its itemsthat need to be sorted according to the first/second attribute . Unfortunately , the class definition contains some issue , the following error appears : How to design the comparator class ? This code is probably completely wrongThanks for y...
public class Pair < T , U > implements Comparable < T , U > { //Error 1 private final T first ; private final U second ; public Pair ( T first_ , U second_ ) { first = first_ ; second = second_ ; } public T getFirst ( ) { return first ; } public U getSecond ( ) { return second ; } } List < Pair < Integer , Integer > > ...
Java : sorting a generic class with two types
Java
I want to have a static method , which whenever called will return a color value that did n't appear yet , and is not too close to last returned color ( i.e . return new Color ( last_value += 10 ) wo n't do ) . It also should be not random , so everytime the application is launched , the sequence of returned colors wou...
private static HashMap < Integer , Boolean > used = new HashMap < > ( ) ; private static int [ ] values = new int [ 0xfffff ] ; // 1/16th of possible colors private static int current = 0 , jump = values.length / 7 ; public static Color getColour ( ) { int value = values [ current ] ; used.put ( current , true ) ; curr...
Algorithm for generating not repeating , spaced-out RGB color values
Java
I 'm looking at some of the code in the Android butterknife library and found this snippet here : I found this a bit peculiar to have what looks like just empty comments after each line , but no comment text . It reminded me a little of line continuation in C macros , but I have never come across this before in java.Do...
private static final List < Class < ? extends Annotation > > LISTENERS = Arrays.asList ( // OnCheckedChanged.class , // OnClick.class , // OnEditorAction.class , // OnFocusChange.class , // OnItemClick.class , // OnItemLongClick.class , // OnItemSelected.class , // OnLongClick.class , // OnPageChange.class , // OnTextC...
Empty trailing comments ? Do they do/mean anything ?
Java
Whenever I try to add the numbers in string like : My program is adding the numbers , but very slowly . But When I altered my program and made it like : I got the result very quickly . Why is that so ?
String s=new String ( ) ; for ( int j=0 ; j < =1000000 ; j++ ) s+=String.valueOf ( j ) ; StringBuffer sb=new StringBuffer ( ) ; for ( int j=0 ; j < =1000000 ; j++ ) sb.append ( String.valueOf ( j ) ) ;
Speed issue while appending strings
Java
I have two arraylists of type String , one of Operands and one of OperatorsThey are filled like soIdeally I would convert this to a single ArrayList that is filled like soIt would be easy to hardcode Polish Notation for three elements , but I have varying numbers of operators and operands ( up to four operands and thre...
ArrayList < String > operands = new ArrayList < String > ( ) ; ArrayList < String > operators = new ArrayList < String > ( ) ; operands = { `` \ '' symbol\ '' : \ '' CHKP % \ '' '' , `` \ '' price\ '' : { $ gt : 23.72\ '' } ; operators = { `` and '' } ; ArrayList < String > polishNotation = { `` and '' , `` \ '' symbol...
Merge two arraylists in a simple form of Polish Notation
Java
As I know lambda expression can be replaced by method reference without any issues . My IDEs say the same , but the following example shows the opposite.The method reference clearly returns the same object , where as lambda expression returns new objects each time.Here is my output :
import java.util.List ; import java.util.stream.Collectors ; import java.util.stream.Stream ; public class Instance { int member ; Instance set ( int value ) { this.member = value ; return this ; } @ Override public String toString ( ) { return member + `` '' ; } public static void main ( String [ ] args ) { Stream < I...
Different behavior between lambda expression and method reference by instantiation
Java
I am integration testing a component . The component allows you to save and fetch strings . I want to verify that the component is handling UTF-8 characters properly . What is the minimum test that is required to verify this ? I think that doing something like this is a good start : One mistake I have made in the past ...
// This is the ☺ characterString toSave = `` \u263A '' ; int id = 123 ; // Saves to DatabasemyComponent.save ( id , toSave ) ; // Retrieve from DatabaseString fromComponent = myComponent.retrieve ( id ) ; // Verify they are same org.junit.Assert.assertEquals ( toSave , fromComponent ) ;
What is the minimum test to verify that a component can save/retrieve UTF8 encoded strings
Java
I 've just encountered an interesting problem related to Java serialization.It seems that if my map is defined like this : And I try to serialize it to a file with ObjectOutputStream : ... I get java.io.NotSerializableException.However , if instead I put values to the map the standard way : ... then serialization work ...
Map < String , String > params = new HashMap < String , String > ( ) { { put ( `` param1 '' , `` value1 '' ) ; put ( `` param2 '' , `` value2 '' ) ; } } ; ObjectOutputStream oos = new ObjectOutputStream ( new FileOutputStream ( outputFile ) ) ; oos.writeObject ( params ) ; Map < String , String > params = new HashMap <...
Serializing maps which are initialized in constructors
Java
I have a domain model class which has a toString implementation that looks like this : The methods getX ( ) , getY ( ) and getZ ( ) are not simple getters , they can perform lookups in the background , generally a lookup to a static map of predefined key-value pairs . Some of them had throws SomeCheckedException in the...
public String toString ( ) { try { return getX ( ) + `` \n '' getY ( ) + `` \n '' getZ ( ) ; //etc . } catch ( Exception e ) { throw new RuntimeException ( e ) ; } }
Catching generic Exception in a toString implementation - bad practice ?
Java
I am trying to figure out how to get generics to jump through hoops.I have : And many `` Subtype '' classes : What I want is to declare a class with two type parameters T and S , where T is bound by Type and S is bound by T and Middle.I ca n't see a way with generics to ensure that S extends T AND implements Middle.Wha...
interface Root { } interface Middle extends Root { } class Type implements Root { } class Subtype1 extends Type implements Middle { } class Subtype2 extends Type implements Middle { } ... class Handler < T extends Root , S extends T , S extends Middle > ; class Handler < T extends Root , S extends < T extends Middle > ...
Generics Puzzler
Java
Consider the following code , which is an extraction of a real use case where LinkedList < E > implements both List < E > and Deque < E > .One can observe that both interfaces have a size ( ) and an isEmpty ( ) method , where the isEmpty ( ) method could be made default in terms of size ( ) .So , let 's do that ( with ...
interface List < E > { public int size ( ) ; default public boolean isEmpty ( ) { return ( size ( ) == 0 ) ; } //more list operations } interface Deque < E > { public int size ( ) ; default public boolean isEmpty ( ) { return ( size ( ) == 0 ) ; } //more deque operations } class LinkedList < E > implements List < E > ,...
Are sub-interfaces the solution to default-method conflicts ?
Java
I 'm using Scanner and a Delimiter to tokenize my .txt file ( it 's a homework that I 've got to do ) . First version of the file looks like this : And I 've used useDelimiter ( `` [ ] * ( , ) [ ] * '' ) second version of the file looks like this : And I ca n't come up with a regexp which would help me to separate numb...
5,5,5,6,5,8,9,5,6,8 , good , very good , excellent , good7,7,8,7,6,7,8,8,9,7 , very good , Good , excellent , very good8,7,6,7,8,7,5,6,8,7 , GOOD , VERY GOOD , GOOD , AVERAGE9,9,9,8,9,7,9,8,9,9 , Excellent , very good , very good , excellent7,8,8,7,8,7,8,9,6,8 , very good , good , excellent , excellent6,5,6,4,5,6,5,6,6...
Java Scanner Dilimiter
Java
I have the following in my class : Is the call to getCounter atomic , or not ?
private static volatile byte counter = 0 ; public static byte getCounter ( ) { return counter ; }
Is simple getter call on volatile variable atomic operation ?
Java
when a programmer use a try block without catch like this what happen to exception and how it possibly handle later ? I try learn it from internet but no clear result for it ...
PersistenceManager pm = PMF.get ( ) .getPersistenceManager ( ) ; try { pm.makePersistent ( c ) ; } finally { pm.close ( ) ; }
what happen to the exceptions when try used the finally only instead of catch and how it handles ?
Java
There is an Eclipse Plugin managed by Maven containing this configuration : In console I run If I open Eclipse in the workspace there is no project .
< project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 http : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelVersion > < groupId > wonttellya < /groupId > < artifac...
Continue development of Plugin
Java
I am totally new to Choco and CP , but I am making a little model to solve the Steiner tree problem , and Choco keeps forcing the first node to be true whatever the graph is ( and its not correct , I checked ) .I have an array es of IntVar that ==1 if the edge is in the solution , or ==0 otherwise . Same for the array ...
s = new Solver ( `` Solver '' ) ; vs = VF.boolArray ( `` vs '' , nbV , s ) ; es = VF.boolArray ( `` es '' , nbE , s ) ; w = VF.integer ( `` w '' , 0 , maxW , s ) ; IntVar [ ] activeEdgeW = new IntVar [ nbE ] ; for ( int i = 0 ; i < nbE ; i++ ) { activeEdgeW [ i ] = VF.enumerated ( `` activeEdgeW [ `` +i+ '' ] '' , new ...
Choco forces a variable to true when it should n't
Java
Is there any way to shorten this if ( ) statement ? To avoid repeating string.equals ( ) somehow ? To something looking similar to this : I am aware that this question looks odd , however if ( ) with such long conditions list is unclear and requires a lot of writing as well .
if ( extension.equals ( `` jpg '' ) || extension.equals ( `` JPG '' ) || extension.equals ( `` png '' ) || extension.equals ( `` PNG '' ) || extension.equals ( `` bmp '' ) || extension.equals ( `` BMP '' ) || extension.equals ( `` jpeg '' ) || extension.equals ( `` JPEG '' ) ) { tmp.setIcon ( new ImageIcon ( getClass (...
Shortening if ( ) with string.equals method
Java
I want to run code compiled before . I compiled anyway it is not important how to compile but running the code is problem.My code.javaThen I compiled this code and code.class ( in the D : // directory ) was generated . Now I want to run this compiled file . My code is : Here there is no error but this code does not do ...
public class code { public static void main ( String [ ] args ) { System.out.println ( `` Hello , World '' ) ; } } import java.io.IOException ; import java.io.InputStream ; public class compiler { public static void main ( String [ ] args ) { final String dosCommand = `` cmd /c java code '' ; final String location = ``...
Running compiled java code at runtime
Java
I 'm reading the Java 8 specification to better understand the Java language.Specifically , the Chapter 7 Packages.However in 7.5.2 7.5.2 Type-Import-on-Demand Declarations I do n't understand the case where we can use TypeName according to the following syntax : The specification says : If the PackageOrTypeName denote...
import PackageOrTypeName . * ;
Import declaration
Java
Function to be refactored ... Function might be used like this ... Edit : Collected suggested implementations and tested efficiency by running them against Person lists.edit2 : Added missing equals method to Person class.Results : ConclusionWhen list size reach 10000 items then so far only Schaffner 's implementation i...
< T > T notUsedRandomItem ( List < T > allItems , List < T > usedItems ) { return allItems.stream ( ) .filter ( item - > ! usedItems.contains ( item ) ) .sorted ( ( o1 , o2 ) - > new Random ( ) .nextInt ( 2 ) - 1 ) .findFirst ( ) .orElseThrow ( ( ) - > new RuntimeException ( `` Did not find item ! `` ) ) ; } System.out...
Is there a more elegant way to get random not used item from list using java 8 ?
Java
I have made a small program in Java that displays its .java source with a gui . It does not use FileChooser to do this . I am reading the .java sources with the aid of following statementswhere name is the name of the .java file i.e . if the file is MyProg.java then name==Myprog . Of course my program is inside the dev...
String resName = `` /dev/classes/ '' +name+ '' .java '' Scanner s = new Scanner ( FilePrinter.class.getResourceAsStream ( resName ) ) ;
Use project 's own .java files as resource files
Java
I 'm preparing for ACM competition and i 'm stuck with this problem . You have buildings with given position Xi and height Hi the shields are made of steel and they need to be supported by at least two buildings with the same height . The right end of the shield must lie on top of some building . All the buildings that...
Input17 31 22 13 24 35 16 27 48 29 310 411 215 216 117 318 319 120 2Output11 3Explanation : first shield : 1,2,3 second shield : 7,8,9,10third shield : 15,16,17,18
Calculating max from [ currPos ] to [ currPos - k ] in large array
Java
I was thinking about changing this question into my situation . I then decided that my situation needed its own question and hopefully answers . After calling FileChannel.truncate ( ) to reduce the size of the file , I call FileChannel.size ( ) , close the FileChannel and then call File.length ( ) . The File exists thr...
public static void truncate ( File file , long size ) throws IOException { FileChannel channel ; Path path ; long channelSize , fileLengthOpen , fileLengthClosed ; path = file.toPath ( ) ; channel = FileChannel.open ( path , StandardOpenOption.READ , StandardOpenOption.WRITE , StandardOpenOption.CREATE ) ; try { channe...
Java FileChannel.size ( ) vs File.length ( ) - After FileChannel.truncate ( )
Java
In C # , if you want to read a string without having to escape the characters , you can use an at-quotewhich is equivalent to Is there a simple way to escape an entire string in Java ?
String file = @ '' C : \filename.txt '' String file = `` C : \\filename.txt ''
Is there a way to use something similar to c # 's at quoting ( @ '' `` ) in java
Java
Is there any way to generate a list of classes in a Java project that are no longer needed by any other classes in that project ? Here 's a diagram to help illustrate the situation ( I hope you enjoy my ASCII diagram since I do n't have enough rep to use an image ) , where C and B depend on project A : I started refact...
A / \ / \ C B
How to get a list of classes in a project that are no longer needed by anything in that project
Java
I 'm writing a program in which on button click data in a pie chart rotates ( slice on 10-12 o'clock moves to 12-2 etc ) . Code below ( kinda ) works , it rotates , but eats the temp slice and creates whole paragraph of errors . It is my first time trying JavaFX and I 'm not really sure how to manage that . Here 's the...
private BorderPane layout ; private Scene scene ; ObservableList < PieChart.Data > pieChartData = FXCollections.observableArrayList ( new PieChart.Data ( `` Post-production age '' , 424236 ) , new PieChart.Data ( `` Production age '' , 1030060 ) , new PieChart.Data ( `` Production age2 '' , 1030060 ) , new PieChart.Dat...
JavaFX Duplicate children PieChart
Java
I am reading a book Effective Java which has the following example . In the below example author copies the reference of objects present in the ObjectOutputStream by the following lineWhy does this reference point to the date object present in the ObjectOutputStream ? what is stored in a reference ?
byte [ ] ref = { 0x71 , 0 , 0x7e , 0 , 5 } ; // Ref # 5 import java.io.ByteArrayInputStream ; import java.io.ByteArrayOutputStream ; import java.io.ObjectInputStream ; import java.io.ObjectOutputStream ; import java.util.Date ; final class Period { private final Date start ; private final Date end ; /** * @ param start...
How does referencing work in Java
Java
I have some selenium tests running on Firefox browser.unfortunatly , although I take care to create a new profile , I always have the /firstrun/ page of Firefox showing up when my test start , which is rather annoying , since that page gets it content over the web.I 've tried disabling it the following waybut it stills...
FirefoxProfile profile = new FirefoxProfile ( profileDir ) ; if ( ! exists ) { profile.setPreference ( `` signed.applets.codebase_principal_support '' , true ) ; profile.setPreference ( `` capability.principal.codebase.p0.granted '' , true ) ; profile.setPreference ( `` startup.homepage_override_url '' , `` about : bla...
How to bypass the firefox update page when using Selenium ?
Java
BackgroundA bit input stream is backed by an array of bytes . There are a handful of methods that read from that byte array into various coerced primitive arrays.ProblemThere is duplicated code . Java lacks generics on primitive types , so perhaps the repetition is unavoidable.CodeThe repetitious code is apparent in th...
@ Overridepublic long readBytes ( final byte [ ] out , final int offset , final int count , final int bits ) { final int total = offset + count ; assert out ! = null ; assert total < = out.length ; final long startPosition = position ( ) ; for ( int i = offset ; i < total ; i++ ) { out [ i ] = readByte ( bits ) ; } ret...
How to avoid duplication of code regarding primitive types ?
Java
Please help me complete my isEmpty method : What code would I put int to establish that if I am dealing with an array it will return true if it 's length is zero ? I want it to work no matter the type whether it is int [ ] , Object [ ] . ( Just so you know , I can tell you that if you put an int [ ] into an Object [ ] ...
public static boolean isEmpty ( Object test ) { if ( test==null ) { return true ; } if ( test.getClass ( ) .isArray ( ) ) { // ? ? ? } if ( test instanceof String ) { String s= ( String ) test ; return s== '' '' ; } if ( test instanceof Collection ) { Collection c= ( Collection ) test ; return c.size ( ) ==0 ; } return...
Given that an Object is an Array of any type how do you test that it is empty in Java ?
Java
I have couple of enums implementing some common interface and I would like to return class literal from the method . However I am unable to specify the intersection type correctly . See below the code sample illustrating the problem. # getEnum1 method does n't compile . Interestingly it works as parameter value in # en...
public class GenericsTest { interface Iface { } enum E1 implements Iface { } enum E2 implements Iface { } < E extends Enum < E > & Iface > Class < E > getEnum1 ( ) { return E1.class ; //ERROR incompatible types : java.lang.Class < GenericsTest.E1 > can not be converted to java.lang.Class < E > } Class < ? extends Enum ...
Return class literal as intersection type
Java
I was going through the JLS documentation on Thread and Locks http : //docs.oracle.com/javase/specs/jls/se7/html/jls-17.html # jls-17.5 . I am confused with above example ( ex no 17.5-1 ) mentioned in the section as to how f.y could be seen as zero.The Reader Threads will either read the object f as null in which case ...
class FinalFieldExample { final int x ; int y ; static FinalFieldExample f ; public FinalFieldExample ( ) { x = 3 ; y = 4 ; } static void writer ( ) { f = new FinalFieldExample ( ) ; } static void reader ( ) { if ( f ! = null ) { int i = f.x ; // guaranteed to see 3 int j = f.y ; // could see 0 } } }
Values read in Multithreading environment
Java
In my scala code , I 'm using a java library which defines an object with a public attribute called `` val '' : Is there a way to get this attribute in scala ?
public class XYZ { public int val= ... }
Scala : `` val '' as identifier possible ? Linking to java library needs it
Java
Can you use underscores in numbers in Java ? I saw this code in a blog , and it works , but will it continue to work in the future ? Is it a feature or a bug ?
long oneBillion = 1_000_000_000L ;
Are underscores allowed in numeric literals in Java ?
Java
I have an entity that has a position value in the list . And you need to determine the value of the next position , by obtaining the last value and increasing by one.If there is no one element , then return zero.Is it possible to somehow make changes in a single line so that for the obtained maximum value immediately i...
public class App { public static void main ( String [ ] args ) { ArrayList < Entity > entities = new ArrayList < > ( ) ; long nextPositionOrFirstIfNotExistWhenEmpty = getNextPositionOrFirstIfNotExist ( entities ) ; if ( nextPositionOrFirstIfNotExistWhenEmpty ! = 0L ) { throw new RuntimeException ( `` Invalid '' ) ; } e...
How in the java stream when executing the .max ( ) method do increment value
Java
I 'd like to be able to write , for examplewhich would do the same thing as the existingbut also include private and protected methods . Any ideas how I could do this ?
Method [ ] getMethods ( Class < ? > c ) Class.getMethods ( )
Is it possible to retrieve all members , including private , from a class in Java using reflection ?
Java
I recently had a technical interview and got small coding task on Stream API.Let 's consider next input : The task is to find Students with unique subjects using Stream API.So for the provided input expected result ( ignoring order ) is [ John , Anthony ] .I presented the solution using custom Collector : But the solut...
public class Student { private String name ; private List < String > subjects ; //getters and setters } Student stud1 = new Student ( `` John '' , Arrays.asList ( `` Math '' , `` Chemistry '' ) ) ; Student stud2 = new Student ( `` Peter '' , Arrays.asList ( `` Math '' , `` History '' ) ) ; Student stud3 = new Student (...
More efficient solution on coding task using Stream API ?
Java
I was asked this question on the interview . I did n't answer and actually I do n't understand how it works.I 'm not asking why does it produce a correct answer ... First of all , why does the algorithm eventually stop ? To me it 's not that obvious.In order for it to stop , carry has to become 0 . Ca n't someone expla...
int add ( int x , int y ) { while ( y ! = 0 ) { int carry = x & y ; x = x ^ y ; y = carry < < 1 ; } return x ; }
How to add numbers without +
Java
I am watching Programming Methodology ( Stanford ) ( CS106A ) course on Java . In lecture 14 Professor Sahami told about memory allocation in Java for functions and object on stack and heap . He told that for any method called on an object , a stack is allocated and argument list and this reference is allocated space o...
public class foo { private int i ; public foo ( int i ) { this.i = i ; // where this reference came from } }
this reference inside the construstor
Java
I 've a parameterized interface : And classes implementing the interface : The number of different MyClass*X* is known and exhaustive , and there is only one instance of each MyClass*X* , so I would like to use an enum : To be able to use MyEnum.MY_CLASS_1.run ( someOtherClass1 ) ; for example ( I would then have every...
public interface MyInterface < T > { void run ( T e ) ; } public class MyClass1 implements MyInterface < SomeOtherClass1 > { public void run ( SomeOtherClass1 e ) { // do some stuff with e } } public class MyClass2 implements MyInterface < SomeOtherClass2 > { public void run ( SomeOtherClass2 e ) { // do some stuff wit...
How are generics managed by enums ?
Java
It seems the need for a type like the following would be so ubiquitous that something like it should be already built into Java : It can then be used in other classes like this trivial example that calls a bunch of executers on an object.Is there a built-in type equivalent or a common library equivalent ? Is there a na...
public interface Executer < T > { void execute ( T object ) ; } class Handler < T > implements Executer < T > { List < Executer < T > > executerList ; Handler ( List < Executer < T > > executer ) { this.executerList = executer ; } void execute ( T t ) { for ( Executer < T > executer : this.executerList ) { executer.exe...
Is there a built-in Java type that guarantees an execute ( T t ) method ?
Java
So here I have this long line of if statements , that are supposed to detect if the value of int [ ] anArray ; is within a certain range . anArray = new int [ 15 ] ; The values of int [ ] anArray ; , starting from anArray [ 0 ] are:49 50 51 59 0 5 9 10 15 19 50 55 89 99 100This is the part of the code that determines i...
int [ ] counterarray = new int [ 10 ] ; for ( x = 14 ; x > = 0 ; x -- ) { System.out.println ( anArray [ x ] ) ; if ( anArray [ x ] > = 0 & & anArray [ x ] < 10 ) { counterarray [ 0 ] = counterarray [ 0 ] + 1 ; } if ( anArray [ x ] > = 10 & & anArray [ x ] < 20 ) { counterarray [ 1 ] = counterarray [ 1 ] + 1 ; } if ( a...
How can I reduce this long list of if statements ?
Java
If I have JungleCat as a subclass of Cat ( JungleCat extends Cat ) , and then I say : I 'm wondering what are the object types of cat1 , cat2 , cat3 , cat4 , and cat5 ? I 'm also wondering why there 's redundancy in instantiating an object : why do you need to list two object types when you instantiate an object.I 'm s...
JungleCat cat1 = new JungleCat ( ) ; Cat cat2 = new Cat ( ) ; Cat cat3 = new JungleCat ( ) ; JungleCat cat4 = new Cat ( ) ; //this one is illegal , right ? JungleCat cat5 ;
Why do you need to list two object types when you instantiate an object ?
Java
I have kind of a general java question I 'm looking for an answer to . Lets say I have an object with a property height and I have a method that uses height to make some calculation . Is it better to pass the property height to the method or is it any different to pass the full object and use a getter to retrieve the v...
public getHeightInMeters ( Object object ) { return object.getHeight ( ) *x ; } public getHeightInMeters ( Height height ) { return height*x ; }
Java parameter passing question
Java
I ran into this today and the only thing I can think is that this is a bug in the Java compiler . The following code compiles , but certainly seems incorrect ( since testMethod has a differenet signature in the child but overrides the parent ) and will throw class cast exceptions at runtime.And using the above structur...
public interface TestInterface < T > { public List < String > testMethod ( ) ; // < -- List < String > } public class TestClass implements TestInterface { @ Override public List < Integer > testMethod ( ) { // < -- List < Integer > overriding List < String > ! ! return Collections.singletonList ( 1 ) ; } } public void ...
Adding a Generic allows you to override a method with a different return type ?
Java
I am new to wildcards and am having an issue iterating through a Collection type . I had to transform this function to work on any Collection type , not just List and here is what I did : changed to : However , when I compile the code I receive the errors : Am I not using iterable correctly ? Any help is appreciated !
void sell ( List < T > items ) { for ( T e : items ) { stock.add ( e ) ; } } void sell ( Collection < ? super T > items ) { Iterator ir = items.iterator ( ) ; while ( ir.hasNext ( ) ) { stock.add ( ( T ) ir.next ( ) ) ; } } Note : Shop.java uses unchecked or unsafe operations.Note : Recompile with -Xlint : unchecked fo...
Use iterable on Collection < ? super T >
Java
According to the Java Language Specification ( Example 17.4-1 ) the following snippet ( starting in A == B == 0 ) ... ... can result in r2 == 2 and r1 == 1 . This is because the result of executing B = 1 ; does not depend on whether or not r2 = A has been executed , thus the JVM is free to swap the order of the executi...
Thread 1 Thread 2 -- -- -- -- -- -- -- -- r2 = A ; r1 = B ; B = 1 ; A = 2 ; Thread 1 Thread 2 -- -- -- -- -- -- -- -- B = 1 ; r1 = B ; A = 2 ; r2 = A ; Thread 1 Thread 2 -- -- -- -- -- -- -- -- r2 = A ; r1 = B ; monitorenter obj monitorenter objmonitorexit obj monitorexit objB = 1 ; A = 2 ;
Is this instruction reordering allowed by the JLS or not ?
Java
I have accidentally run into Striped64.java class from Kamon Monitoring tool . At line 95 I found this comment : Although I understand what CAS is , I am unable to find out what a release-only form of CAS is . Could someone shed some light on this ?
JVM intrinsics note : It would be possible to use a release-onlyform of CAS here , if it were provided .
Release-Only form of CAS
Java
I 've noticed that in Java if the current thread is beeing suspended within a try-block the corresponding finally block is not being executed such as inCan this observation be generalized to the suspension of threads i.e . is it true what the Oracle doc says that it can only used to bypass return , break and continue ?...
Semaphore lock = new Semaphore ( 0 ) ; try { lock.acquire ( ) ; } finally { // do something }
finally-block and thread suspension
Java
It is a well know fact that in Java one needs to initialize a local variable before using it ( cf . JLS ) A local variable ( §14.4 , §14.14 ) must be explicitly given a value before it is used , by either initialization ( §14.4 ) or assignment ( §15.26 ) , in a way that can be verified using the rules for definite assi...
The local variable result may not have been initialized .
What is the design rational for `` variable may not have been initialized '' ?
Java
How can I do something like the following JavaScript code , in Java ? What I want to to do is to continue evaluating statements or methods , until it gets something instead of null.I would like the caller code to be simple and effective .
var result = getA ( ) || getB ( ) || getC ( ) || 'all of them were undefined ! ' ;
How can I evaluate next statement when null was returned in Java ?
Java
I have decided to check the Java Compiler 's perspicacity ; thus , I have written a simple class.I was wondering whether the compiler will optimize the condition to something simpler like : I compiled the class and then disassembled it with the javap tool . When I took a look at the output , I was truly dumbfounded , b...
public class Foo { public Foo ( boolean a , int b ) { if ( a == true & & a ! = false ) { b = 1 ; } } } if ( a == true ) { } Compiled from `` Foo.java '' public class Foo { public Foo ( boolean , int ) ; Code : 0 : aload_0 1 : invokespecial # 1 // Method java/lang/Object . `` < init > '' : ( ) V 4 : iload_1 5 : iconst_1...
Strange optimization of `` if '' conditions in Java
Java
Lets say I have these two classes , one extending the otherWhat I want to do is warn the user to call the super-class 's method foo if they have n't in the override method , is this possible ? Or is there a way to know , using reflection that a method that overrides a method of its super-class calls the original method...
public class Bar { public void foo ( ) { } } public class FooBar extends Bar { @ Override public void foo ( ) { super.foo ( ) ; // < -- Line in question } } public abstract class Bar { public Bar ( Class < ? extends Bar > cls ) { Object instance = getInstance ( ) ; if ( ! instance.getClass ( ) .equals ( cls ) ) { throw...
Warn developer to call ` super.foo ( ) ` in java
Java
The crux of the question is , why does this cause a compile-time error ? BackgroundI understand why generics are n't covariant in general . If we could assign List < Integer > to List < Number > , we 'd expose ourselves to ClassCastExceptions : We get a compile-time error at line 2 to save us from a run-time error at l...
List < Collection > raws = new ArrayList < Collection > ( ) ; List < Collection < ? > > c = raws ; // error List < Integer > ints = new ArrayList < Integer > ( ) ; List < Number > nums = ints ; // compile-time errornums.add ( Double.valueOf ( 1.2 ) ) ; Integer i = ints.get ( 0 ) ; // ClassCastException List < Collectio...
Why ca n't I cast a Collection < GenericFoo > to a Collection < GenericFoo < ? > >