lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I have tried this using Jodatime DateTime , I have also tried using Jodatime MutableDateTimeBoth are giving me the same result , 1965/10/13 06:09:54.I expect , 1965/10/13 05:26:40 , instead . I 'm getting this using Oracle query given below , And upon contradiction between Joda and Oracle , I tried Wolframalpha , that ... | DateTime dateTime = DateTime .parse ( `` 1-JAN-1900 '' , DateTimeFormat.forPattern ( `` dd-MMM-yyyy '' ) ) .plusSeconds ( 2075866000 ) ; String dateTimeStr = DateTimeFormat.forPattern ( `` yyyy/MM/dd HH : mm : ss '' ) .print ( dateTime ) ; System.out.println ( dateTimeStr ) ; MutableDateTime dateTime = MutableDateTime ... | DateTime is giving unexpected result |
Java | Having a String representation of a number ( no decimals ) , what 's the best way to convert it to either one of java.lang.Integer or java.lang.Long or java.math.BigInteger ? The only condition is that the converted type should be of minimal datatype required to hold the number.I 've this current implementation that wo... | package com.stackoverflow.programmer ; import java.math.BigInteger ; public class Test { public static void main ( String [ ] args ) { String number = `` -12121111111111111 '' ; Number numberObject = null ; try { numberObject = Integer.valueOf ( number ) ; } catch ( NumberFormatException nfe ) { System.out.println ( ``... | Convert String representation to minimal Number Object |
Java | I need to pass an x/y around . I was just using java.awt.Point . I do this a lot considering it 's the nature of the app , but tons slower then normal arrays . I also tried to create my own `` FastPoint '' which is just an int x/y and very simple class constructor , that 's really slow too.Time is in millescond . java.... | public class FastPoint { public int x ; public int y ; public FastPoint ( int x , int y ) { this.x = x ; this.y = y ; } } for ( int i = 0 ; i < maxRuns ; i++ ) { point = new Point ( i , i ) ; } for ( int i = 0 ; i < maxRuns ; i++ ) { a [ 0 ] = i ; a [ 1 ] = i ; } | Why are Points slow |
Java | I 'm here asking for a simple way to add some custom code in the JPA Entity generated by Eclipse from database.Basically what I want to achieve is to add public String properties containing the names of the entity properties , and use them when I need to provide `` property name '' as String and be sure that there wo n... | @ Entity @ Table ( name= '' clients '' ) @ NamedQuery ( name= '' ClientModel.findAll '' , query= '' SELECT c FROM ClientModel c '' ) public class ClientModel implements Serializable { private static final long serialVersionUID = 1L ; @ Id @ Column ( name= '' id_client '' ) private long idClient ; public String name ; p... | Custom code generation for JPA entities from database |
Java | There is the following sequence : 101001000100001 ... How to define a method that takes an element 's index of the sequence and returns the value ( 0 or 1 ) of this element ? Maybe there 's need to use recursion ? I would be grateful for any ideas ! | public Element getValue ( int index ) { } | Algorithm to find element value of sequence |
Java | In Concurrency Interest link , there is a code which is like this : -What is the meaning of ( ) - > ? I checked in eclipse , it does not allow . But what was the intention of the thread-writer ? | exec.schedule ( ( ) - > System.out.println ( `` done '' ) , 1 , TimeUnit.SECONDS ) ; | What is the meaning of ( ) - > System.out.println ( `` done '' ) ? |
Java | The syntax for Java 's format strings can get complicated , for example : It would seem to be ripe for someone to create a fluent DSL to aid with the construction of these format strings ( similar to what Jooq does for SQL ) .Does such a thing exist ? | `` | % 1 $ -10s| % 2 $ -10s| % 3 $ -20s|\n '' | Does any library exist which provides a fluent way to construct Java format strings ? |
Java | With my Tile Editor that I created I get an Array like this : So it prints out a 2 dimensional array.The problem is that I have hundreds of these in one class and what to organize them to be able to do like : Levels.getlevelCount ; So I figured out that I could do a 3 dimensional Array : int [ ] [ ] [ ] AllLevels = new... | int [ ] [ ] Level02 = new int [ ] [ ] { { 11 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , -1 , 12 } , { 11 , -1 , -1 , -1 , -1 ,... | Initialize Array in an array |
Java | Guava 's ImmutableCollection has sub-classes like ImmutableList that are ( non-extendable ) abstract classes rather than interfaces . The documentation says this is to prevent external subtyping . On the other hand , the documentation also says they should be thought of as interfaces in every important senseBut is n't ... | public ImmutableList < String > getNames ( ) ; public List < String > getNames ( ) ; | Why are n't Guava ImmutableCollections interfaces ? |
Java | I 'm learning Java and write the simple code below : The result : 10 . Well done ! It run successfully and have no error . Can anyone please explain why I can assign a static variable before declaring it ? | public class Test { private int a = b ; private final static int b = 10 ; public int getA ( ) { return a ; } } public class Hello { public static void main ( String [ ] args ) { Test test = new Test ( ) ; System.out.println ( test.getA ( ) ) ; } } | Assign a static variable before declaring |
Java | I 'd a code snippet : I 'm not getting why the output is so ? the Output is : a & b Both are equalc & d are not equalI 'm using jdk1.7 | public class Test { public static void main ( String args [ ] ) { Integer a = 100 ; Integer b = 100 ; Integer c = 5000 ; Integer d = 5000 ; System.out.println ( a ) ; System.out.println ( b ) ; System.out.println ( c ) ; System.out.println ( d ) ; if ( a == b ) System.out.println ( `` a & b Both are Equal '' ) ; else S... | Integer class object |
Java | I have the following Java program that I was expecting to not compile , but it did : Why does javac allow calling a non-parameterized method in this way ? My Java compiler version is : javac 1.7.0_75 | class Test { public static void f ( ) { } void m ( ) { Test. < String > f ( ) ; } } | Why is it not an error to call a non-parameterized method with type arguments ? |
Java | The following code works , fine , but i wonder .. conceptually , is it correct ? Start the threads , wait for them to join . Should ThreadPool be used instead ? If possible , please comment | List < Thread > threads = new ArrayList < Thread > ( ) ; for ( Test test : testsToBeExecuted ) { Thread t = new Thread ( test ) ; threads.add ( t ) ; t.start ( ) ; } for ( Thread thread : threads ) { thread.join ( ) ; } | How to start and manage Java threads ? |
Java | Please explain this loop : I am a beginner and I am confused how do such loops work ? Please emphasize on use of a [ j ] in loop . | for ( p=0 ; p < a [ j ] ; p++ ) | Use array element as termination in for loop |
Java | Before java 8 an inner class could access outer objects only if they were declared final.However now when I run example code ( from below ) on javaSE 1.8 there is no compilation error and program runs fine.Why did they change that and how does It work now ? Example code from java 7 tutorial : | public class MOuter { private int m = ( int ) ( Math.random ( ) * 100 ) ; public static void main ( String [ ] args ) { MOuter that = new MOuter ( ) ; that.go ( ( int ) ( Math.random ( ) * 100 ) , ( int ) ( Math.random ( ) * 100 ) ) ; } public void go ( int x , final int y ) { int a = x + y ; final int b = x - y ; clas... | Anonymous classes can access non-final outer objects in java 8 ? |
Java | Below is a trivial java program . It has a counter called `` cnt '' that is incremented and then added to a List called `` monitor '' . `` cnt '' is incremented by multiple threads , and values are added to `` monitor '' by multiple threads.At the end of the method `` go ( ) '' , cnt and monitor.size ( ) should have th... | public class ThreadTester { private List < Integer > monitor = new ArrayList < Integer > ( ) ; private Integer cnt = 0 ; private static final int NUM_EVENTS = 2313 ; private final int THREAD_COUNT = 13 ; public ThreadTester ( ) { } public void go ( ) { Runnable r = new Runnable ( ) { @ Override public void run ( ) { fo... | Concurrency in Java using synchronized blocks not giving expected results |
Java | Mastering Lambdas by Maurice Naftalin , Ch6 - Stream Performance.There is explanation about the different characteristics of streams at the different stages of execution ( intermediate & terminal ) .For eg.What was confusing to me was explanation of SORTED characteristics : `` Stream elements may have been sorted in ot... | Stream.of ( 8,3,5,6,7,4 ) //ORDERED , SIZED.filer ( i- > i % 2==0 ) // ORDERED.sorted ( ) // ORDERED , SORTED.distinct ( ) // DISTINCT , ORDERED , SORTED.map ( i- > i+1 ) // ORDERED.unordered ( ) ; //none | Stream characteristics for the streams generated for SortedMap may not be SORTED if created with custom Comparator |
Java | Stacktrace from my NPE starts with : Line number 141 in this file is : Where store is not null and store.getAvailablePieces ( ) is null . I do not understand why I get exception in here.Any ideas ? | Caused by : java.lang.NullPointerException at pl.yourvision.crm.web.servlets.listExport.ProductListExport.writeCells ( ProductListExport.java:141 ) Double availablePieces = store ! = null ? store.getAvailablePieces ( ) : 0.0 ; | Odd NullPointerException |
Java | Understanding the difference between ++i and i++ , the below example still feels counter-intuitive.Could someone please explain the order of operations and assignments in the following example ? Namely on line two , why is i not incremented after the assignment ? | int i = 0 ; i = i++ ; System.out.println ( i ) ; // 0 | Order of operations in i=i++ ; |
Java | I have been working with the following class named City and tried to convert it to a record called CityRecord asBut moving to such a representation , one of our unit tests starts failing . The tests internally deal with a list of cities read from a JSON file and mapped to an object further counting the cities while gro... | @ ToString @ AllArgsConstructorpublic class City { Integer id ; String name ; } record CityRecord ( Integer id , String name ) { } // much cleaner ! List < City > cities = List.of ( new City ( 1 , `` one '' ) , new City ( 2 , `` two '' ) , new City ( 3 , `` three '' ) , new City ( 2 , `` two '' ) ) ; Map < City , Long ... | Compatibility issues while converting Classes to Records |
Java | There are many tutorials or questions related to custom title bar with JavaFXI created a custom title bar like this : I can move the windows but now ( because the windows is UNDECORATED I ca n't apply any native Windows feature like the Aero shake ( if you shake a window , all other app are reduced ) Is there any solut... | @ Overridepublic void start ( Stage primaryStage ) throws Exception { setPrimaryStage ( primaryStage ) ; prStage = primaryStage ; Parent root = FXMLLoader.load ( getClass ( ) .getResource ( `` ../gui/main.fxml '' ) ) ; prStage.initStyle ( StageStyle.UNDECORATED ) ; //prStage.setOpacity ( 0.75 ) ; Scene scene = new Scen... | Manage Windows Aero shake feature with custom title bar |
Java | Below is the Javadoc comment for String.intern ( ) method : *Returns a canonical representation for the string object . A pool of strings , initially empty , is maintained privately by the class String . When the intern method is invoked , if the pool already contains a string equal to this String object as determined ... | public class Test1 { public static void main ( String [ ] args ) { String s1 = new String ( new char [ ] { ' J ' , ' a ' , ' v ' , ' a ' } ) ; String s2 = s1.intern ( ) ; System.out.println ( s1 == s2 ) ; } } public class Test2 { public static void main ( String [ ] args ) { String s3 = new String ( new char [ ] { ' U ... | Is String Pool really empty initially as mentioned in the Javadoc of String.intern ( ) method ? |
Java | I am unable to understand how Double.toString ( ) works in Java/JVM.My understanding is that in general fraction numbers can not be represented precisely in floating point types such as Double and Float . For example , the binary representation of 206.64 would be 206.6399999999999863575794734060764312744140625 . Then h... | @ Testfun testBigDecimalToString ( ) { val value = 206.64 val expected = `` 206.64 '' val bigDecimal = BigDecimal ( value ) assertEquals ( expected , value.toString ( ) ) // success assertEquals ( expected , bigDecimal.toString ( ) ) // failed . Actual : 206.6399999999999863575794734060764312744140625 } | How does Double.toString ( ) work if a fraction number can not be precisely represented in binary ? |
Java | I have one number , for example `` 1256 '' , how can I convert it into an Array ? Actually , I use a constructor of class where I stock it.Is there any fine/ adequate solution that may use Java 8 Stream ? | public SecretBlock ( int numbersToArray ) { this.arrayOfNumbers = new int [ AMOUNT ] ; for ( int i = AMOUNT - 1 ; i > = 0 ; i -- ) { this.arrayOfNumbers [ i ] = numbersToArray % 10 ; numbersToArray /= 10 ; } } | How convert an int into an Array number by number |
Java | I have an ArrayList < String > in Java . Now I want to sort it with some requirements.I have these items in the ArrayList for example : And I want to push back the ones with _locked at the end and keep the order , to make this : What is the best way to do this ? Would I have to iterate through the List remove the Strin... | xyzbcdabc_lockedcdeefg_lockedfgh xyzbcdcdefghabc_lockedefg_locked | Java , special sort an ArrayList with longer entries at the end |
Java | I 'm having an application that creates lots of rows which reference two other entities , i.e . there are two foreign key references in the row which realize ManyToOne relationships.These are the two entities being referenced : This is the entity which references a and b : a , b , and x are mapped to the classes A , B ... | CREATE TABLE a ( ` id ` INT NOT NULL auto_increment , -- lots of other attributes , PRIMARY KEY ( id ) ) CREATE TABLE b ( ` id ` INT NOT NULL auto_increment , -- lots of other attributes , PRIMARY KEY ( id ) ) CREATE TABLE x ( ` id ` INT NOT NULL auto_increment , ` f_a ` INT NOT NULL , ` f_b ` INT NOT NULL , CONSTRAINT... | Is it necessary to fetch an entity in order to reference it , using JPA and MySQL ? |
Java | I need the size of the black part of this image : I 've done some research about how to find it in normal math , and I was pointed to this website : WebsiteThe final answer on getting it was ( from MathWorld - A Wolfram Web Resource : wolfram.com ) where r is the radius of the first circle , R the radius of the second ... | float r = getRadius1 ( ) ; float R = e.getRadius1 ( ) ; float deltaX = Math.abs ( ( getX ( ) + getRadius ( ) ) - ( e.getX ( ) + e.getRadius ( ) ) ) ; float deltaY = Math.abs ( ( getY ( ) + getRadius ( ) ) - ( e.getY ( ) + e.getRadius ( ) ) ) ; float d = ( float ) Math.sqrt ( Math.pow ( deltaX , 2 ) + Math.pow ( deltaY ... | How to get the size of the intersecting part in a circle in Java |
Java | So , I 'm new to programming , and I was trying to make a basic mole ( chemistry ) calculator just for fun . I did n't find this question . If it was answered please send me the link.This is the formula : n = N / Na where n = mole and Na = 6.022E23The first part of the code throws an error . Just trying to get one , di... | Scanner in = new Scanner ( System.in ) ; double Na = 6.022 ; System.out.print ( `` What do you want to know ? Mol ( 0 ) or N ( 1 ) ? `` ) ; int first = in.nextInt ( ) ; if ( first == 0 ) { System.out.print ( `` Insert N : `` ) ; double N = in.nextDouble ( ) ; double mol = N/Na ; System.out.print ( `` There are `` + mol... | Getting 1000 as an answer instead of 1 when dividing ( 6.022/6.022=1000 ) Java |
Java | I want to show the notifications in the specified time . Like I have a start time from when I want to see the notifications and the end time till when I want to see the notifications i.e the list of strings which should be displayed in a given time slot.Also the list can be of any number specified by the user . How can... | List < String > times = new ArrayList < > ( ) ; try { SimpleDateFormat dateFormat = new SimpleDateFormat ( `` HH : mm '' , Locale.ENGLISH ) ; Date start = dateFormat.parse ( startTime ) ; Date end = dateFormat.parse ( endTime ) ; long minutes = ( ( end.getTime ( ) - start.getTime ( ) ) / 1000 / 60 ) / howMany ; for ( i... | How to show list of strings in notification in a given time slot ? |
Java | It seems intuitively clear that in Java , instance variable intitializers are executed in the order in which they appear in the class declaration.This certainly appears to be the case in the JDK I am using . For example , the following : prints 42 0 42 ( in other words , y picks up the default value of z ) .Is this ord... | public class Clazz { int x = 42 ; int y = this.z ; int z = this.x ; void print ( ) { System.out.printf ( `` % d % d % d\n '' , x , y , z ) ; } public static void main ( String [ ] args ) { new Clazz ( ) .print ( ) ; } } | Ordering of instance variable initializers |
Java | Consider the following code in Java 11 : The first line creates a StringBuilder that uses the Latin1 coder ( one byte per character ) . Then the second line causes the StringBuilder to realise that it needs to use the UTF16 coder instead , so it copies its current contents into a new array before appending the new UTF-... | StringBuilder sb = new StringBuilder ( `` one '' ) ; sb.append ( `` δύο '' ) ; // `` two '' | Initializing StringBuilder to use UTF-16 coder |
Java | This is a problem I have always heard about in school but never had a reason to mess with until I was asked for an interview.Prompt : Using 2 threads print `` Thread i : The number is ' j ' '' in order where j = 1:100 and i is the thread number . Thread 1 can only print odd j 's and Thread 2 can only print even j's.EDI... | import java.util.concurrent.Semaphore ; public class ThreadSynchronization implements Runnable { private int start ; private Semaphore semaphore ; private ThreadSynchronization ( int start , Semaphore semaphore ) { this.start = start ; this.semaphore = semaphore ; } public static void main ( String [ ] args ) { Semapho... | How to properly synchronize two threads |
Java | I use the following lambda expression to iterate over PDF files.This part .forEach ( Start : :modify ) ; executes the static method modify from the same class where the lambda expression is located . Is there a possibility to add something like else clause when no PDF file is found ? | public static void run ( String arg ) { Path rootDir = Paths.get ( arg ) ; PathMatcher matcher = FileSystems.getDefault ( ) .getPathMatcher ( `` glob : **.pdf '' ) ; Files.walk ( rootDir ) .filter ( matcher : :matches ) .forEach ( Start : :modify ) ; } private static void modify ( Path p ) { System.out.println ( p.toSt... | Else clause in lambda expression |
Java | can you explain me which is the difference between : andI have always used the second one , but is there any difference with an static initializer block ? | public class Test { public static final Person p ; static { p = new Person ( ) ; p.setName ( `` Josh '' ) ; } } public class Test { public static final Person p = initPerson ( ) ; private static Person initPerson ( ) { Person p = new Person ( ) ; p.setName ( `` Josh '' ) ; return p ; } } | Java : Static initialization |
Java | I know that overloading uses static binding and overriding uses dynamic binding.But what if they are mixed ? According to this tutorial , to resolve method calls , static binding uses type information while dynamic binding uses actual Object information.So , does static binding happens in the following example to deter... | public class TestStaticAndDynamicBinding { @ SuppressWarnings ( `` rawtypes '' ) public static void main ( String [ ] args ) { Parent p = new Child ( ) ; Collection c = new HashSet ( ) ; p.sort ( c ) ; } } public class Parent { public void sort ( Collection c ) { System.out.println ( `` Parent # sort ( Collection c ) i... | case : static binding ? dynamic binding ? |
Java | I keep getting told it is bad practice to not terminate a Stream via methods such as collect and findFirst but no real feedback as to why not much said about it in blogs . Looking at following example , instead of using a massive nested if check , I went with Optional to get back a List value . As you can see my last s... | import lombok.Getter ; import lombok.Setter ; import java.util . * ; public class Main { public static void main ( String [ ] args ) { RequestBean requestBean = new RequestBean ( ) ; // if I uncomment this I will get the list values printed as expected// FruitBean fruitBean = new FruitBean ( ) ; // AnotherBean anotherB... | Why ca n't I use filter as my last step in a stream |
Java | Happy New Year for everyone ! : ) I have a JTable inside JScrollPane ( fillsViewportHeight is true ) and want to enable row selection from the end when drag starts outside the table ( as shown on the pic ) SSCCE : How can I do that ? UPD : The default behavior of JTable is to select all rows from start to current one ,... | public class SimpleTableDemo extends JPanel { public SimpleTableDemo ( ) { super ( new BorderLayout ( 0 , 0 ) ) ; String [ ] columnNames = { `` First Name '' , `` Last Name '' , `` Sport '' , `` # of Years '' , `` Vegetarian '' } ; Object [ ] [ ] data = { { `` Kathy '' , `` Smith '' , `` Snowboarding '' , new Integer (... | JTable row selection from the end |
Java | When I was seeing the declaration of ArrayListwhich implements List interface even though ArrayList 's superclass AbstractList implements the same List interface.Similar declarations can be found on HashMap , LinkedHashMap declarations also.In the declaration of LinkedHashMap , it implements Map interface only and not ... | class ArrayList < E > extends AbstractList < E > implements List < E > , RandomAccess , Cloneable , java.io.Serializable abstract class AbstractList < E > extends AbstractCollection < E > implements List < E > | Is there any benefit in implementing a interface in a subclass even though the superclass implements the same interface |
Java | I thought this was going to be relatively easy , but alas , it seems it isn't.I am currently writing Unit-Tests for a Facade-like structure in my Project using Java EE 6.For the Tests I use Junit 4.11 , with Eclipse Kepler as IDE.From what I can see , there seems to be something `` wrong '' with double brace initializa... | package com.example-company.util.converters ; import java.util.HashMap ; import java.util.Map ; import com.example-company.model.Location ; import com.example-company.model.Right ; public final class ModelConverters { private static final Map < Class < ? > , ModelConverter < ? , String > > modelConverterBacking = new H... | Double Brace initialization Type Confusion |
Java | The following code creates a Collector that produces an UnmodifiableSortedSet : The codes compiles under the ecj compiler : Under javac however : If I change the offending line to the following , the code compiles under both compilers : Is this a bug in ecj , javac or an underspecification that allows for both behaviou... | package com.stackoverflow ; import java.util.Collections ; import java.util.SortedSet ; import java.util.TreeSet ; import java.util.stream.Collector ; import java.util.stream.Collectors ; public class SOExample { public static < T extends Comparable < T > > Collector < T , ? , SortedSet < T > > toSortedSet ( ) { return... | This code compiles using ecj but not javac . Is this a bug in ecj , javac or neither ? |
Java | I 'm comparing the various ways of storing a String in java by breaking a String down into its constituent parts . I have this code snippet : This is using sizeof to measure the size of the objects . The results of the above show : Given that a byte is 8 bits and a char is 16 bits why are the results not 10 bytes and 2... | final String message = `` ABCDEFGHIJ '' ; System.out.println ( `` As String `` + RamUsageEstimator.humanSizeOf ( message ) ) ; System.out.println ( `` As byte [ ] `` + RamUsageEstimator.humanSizeOf ( message.getBytes ( ) ) ) ; System.out.println ( `` As char [ ] `` + RamUsageEstimator.humanSizeOf ( message.toCharArray ... | Differing sizes of String representation in Java |
Java | While I was working on a project of mine , I tried to print out an integer from an array using the following code : I accidentally forgot to state which integer I wanted to print out from the array of integers which lead to it printing out this line of code : I have already fixed the issue by changing the 3rd line into... | Random dice = new Random ( ) ; int wolfhealth [ ] = new int [ ] { dice.nextInt ( 15 ) +9 } ; System.out.println ( wolfhealth ) ; [ I @ 75b84c92 System.out.println ( wolfhealth [ 0 ] ) ; | Printing an array without stating which one leads leads to a String of random code |
Java | I know how to random number using java Random class.This will random a number between 0-13 13 times ; Question-I would like to random a number between 0-13 for 13 times-If the first random number is e.g ( 5 ) , then my second random number will random any number from 0-13 again EXCLUDING 5 ; If the second random number... | public static void main ( String [ ] args ) { int ctr = 13 ; int randomNum = 0 ; while ( ctr ! = 0 ) { Random r = new Random ( ) ; randomNum = r.nextInt ( 13 ) ; ctr -- ; System.out.println ( ctr + '' : `` + randomNum ) ; } } | do n't random number that are being random before |
Java | In my Spring Boot project , I 've created a custom annotation with validator extending ConstraintValidator to validate some fields in RequestBody . The annotation works fine for non-nested fields but validator is not called for nested ones.My annotation looks like : My validator class : It works fine in cases like this... | @ Target ( AnnotationTarget.FIELD ) @ Retention ( AnnotationRetention.RUNTIME ) @ Constraint ( validatedBy = [ CustomValidator : :class ] ) @ Suppress ( `` unused '' ) @ MustBeDocumentedannotation class CustomValidation ( val message : String = `` validation failed '' , val groups : Array < KClass < * > > = [ ] , val p... | Custom Spring annotation not called |
Java | I 'm playing with a simple android app using the emmulator running android-7 ( 2.1 ) and a moto-defy running android-8 ( 2.2 ) .I ran into an interesting problem whereby a CSV parsing application failed on the emmulator , but succeeded on the defy and in regular java apps ( using sun java ) .I tracked the problem down ... | /** * Skips { @ code amount } characters in the source string . Subsequent calls of * { @ code read } methods will not return these characters unless { @ code * reset ( ) } is used . * * @ param ns * the maximum number of characters to skip . * @ return the number of characters actually skipped or 0 if { @ code ns < 0 ... | android java implementation flaws .. are they documented ? |
Java | OutputAs per Oracle tutorials , `` The Java compiler copies initializer blocks into every constructor . Therefore , this approach can be used to share a block of code between multiple constructors . `` So why initializer blocks of class B is not executed twice as constructor is executing twice ? | class B { { System.out.println ( `` IIB B '' ) ; } B ( int i ) { System.out.println ( `` Cons B int '' ) ; } public B ( ) { this ( 10 ) ; System.out.println ( `` Cons B '' ) ; } } public class C extends B { { System.out.println ( `` IIB C '' ) ; } public C ( ) { System.out.println ( `` Cons C '' ) ; } public static voi... | Why instance initiazer block in java executed only once ? |
Java | I have problem with understand why String [ ] args variable has no forEach method ? I can not find any information that this type is not Serializable or Collection because forEach methos implements Serializable.For example , I have simple main Java class . If I want to use forEach method , I have to first import Arrays... | import java.util.Arrays ; public class MyClass { public static void main ( String [ ] args ) { Arrays.stream ( args ) .forEach ( System.out : :println ) ; } } args.forEach ( System.out : :println ) ; | Why list of String has no forEach method ? |
Java | Eclipse showing Compile time error on Line 4 only why ? My understanding compiler reads top to bottom . so it should say compile time error on line number 1. but How is the priority goes to Line number 4.Kindly clarify . Thanks | public static void main ( String [ ] args ) { char a=true ; //Line 1 char b=null ; //Line 2 char c='\n ' ; //Line 3 char d='Hell ' ; //Line 4 } | java coding : : Eclipse showing Compile time error on Line 4 only why ? |
Java | I was told by a Professor that explicit constructor invocation using this was `` poor coding practice '' and penalized for it . However , I have n't been able to find anything in any java style guide that I 've looked through that comments on it one way or another . On top of that , it seems to be done in quite a bit o... | public class SomeClass { private int a ; private int b ; public SomeClass ( ) { this ( 0 ) ; } public SomeClass ( int a ) { this ( a , 0 ) ; } public SomeClass ( int a , int b ) { this.a = a ; this.b = b ; } } public class Employee { private String name ; private int monthlySalary ; // Default constructor public Employ... | Explicit Constructor Invocation using 'this ' as poor coding practice ? |
Java | I 'm having a horrible time coming up with a good question Title ... sorry/please edit if your brain is less shot than mine.I am having some issues handling my game 's maps client side . My game is tile based using 32x32 pixel tiles . My first game map was 1750 x 1750 tiles . I had a bunch of layers client side , but m... | private void checkIfWithinAndPossiblyReloadChunkMap ( ) { if ( Math.abs ( MyClient.characterX - MyClient.chunkX ) + 10 > ( MyClient.chunkWidth / 5 ) ) { //arbitrary number away ( 10 ) Runnable myRunnable = new Runnable ( ) { public void run ( ) { logger.info ( `` FillMapChunkBuffer started . `` ) ; short chunkXBuffer =... | map chunking strategy , rechunk lag issue |
Java | Below is a small extract of a very large file . I 'm looking for a way to get each name and value ( on the Name ( x ) and Value ( x ) lines ) into an element of a Array or List type with an `` = '' between the two.i.e to get each element to look like `` 'name ' = 'value ' `` .So far I can get the names and values . My ... | [ Device|EEP_FEATUREKOI_HFS_Max|Kostia ] -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- Name ( 1 ) = partHeader_A01Value ( 1 ) = 0x10Desc ( 1 ) = ( Address 0x000 ) Article No . / P.C.B No Byte 1Name ( 2 ) = partHeader_A02Value ( 2 ) = 0x9Desc ( 2 ) = ( Address 0x001 ) Article No . / P.C.B No Byte 2Name ( 3 ) = partHea... | Sorting multiple strings into an element |
Java | I am using fragment layout in my app , this app contains a listview . Clicking on items will do some job . works fine when in landscape mode but getting crashed if items are clicked when in portait mode . What can be the problem ? Here is my code : MainAcitivity.javaMenuFragment.java // showing the list viewTextFragmen... | package com.example.newfragment ; import android.content.res.Configuration ; import android.os.Bundle ; import android.support.v4.app.FragmentActivity ; import android.widget.Toast ; public class MainActivity extends FragmentActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( ... | Listview crashes in portrait mode when clicked on items ( using fragments ) |
Java | After I save the note in my Android app , the note ( or the ListView ) of the note/s does n't appear in the MainActivity . The MainActivity class of my app is : The activity_main ( xml/layout file ) of my app is : The Second class of my app is : The NotesDataSource class of my app is : The DB class of my app is : A scr... | package com.twitter.i_droidi.mynotes ; import android.app.AlertDialog ; import android.content.DialogInterface ; import android.content.Intent ; import android.support.v7.app.ActionBarActivity ; import android.os.Bundle ; import android.view.ContextMenu ; import android.view.Menu ; import android.view.MenuInflater ; im... | ListView does n't appear in the MainActivty of my app ( An image attached ) |
Java | How can I get a day number from a given date using Calendar API.Example :02/01/2016 is the first saturday in 2016 ( result 1 ) 10/01/2015 is the second saturday in 2015 ( result 2 ) I thought I can use the week numberBut it does not work when we have a precedent year of 53 weeksExample : 09/01/2016 will return 1 when i... | int week = calendar.get ( Calendar.WEEK_OF_YEAR ) ; | Specific day number using java Calendar API |
Java | From Oracle 's documentation of Type Inference Type inference is a Java compiler 's ability to look at each method invocation and corresponding declaration to determine the type argument ( or arguments ) that make the invocation applicable . The inference algorithm determines the types of the arguments and , if availab... | static < T > T pick ( T a1 , T a2 ) { return a2 ; } Serializable s = pick ( `` d '' , new ArrayList < String > ( ) ) ; | Why the type inference algorithm tries to find the most specific type ? |
Java | I have a Portfolio class that also has linkedlist of Investment class ( example - Google is an instance of Investment ) , each investment has a trade history ( another linked list ) with data for each trade . When the user want to make a trade ( buy google stocks for 5K ) I need to find if the investment ( in google ) ... | public class Portfolio { private LinkedList < Investment > investmentsList ; public Portfolio ( ) { investmentsList = new LinkedList < Investment > ( ) ; } public void addInvestment ( String symbol , double money ) { Investment invest = findInvestment ( symbol ) ; if ( invest == null ) { System.out.println ( `` symbol ... | Java - return a reference to a specific place in a linkedlist with list iterator |
Java | A friend of mine asked me if I could help him find out the reason behind an error he is getting on a piece of code and most importantly why the error disappears when he add some piece of code . I 've looked into the docs about the classes and could n't find out the reason too.Here is the code : As you can see , the onl... | import java.util.Arrays ; import java.util.List ; import javax.swing.JComponent ; import javax.swing.JPanel ; import javax.swing.JTabbedPane ; public class Test { public static void main ( String [ ] args ) { /** * This line shows this compilation error in eclipse : * Type mismatch : can not convert from * List < Class... | Strange error on list initialization |
Java | If there 's 3 classes . A , B and C. class B extends A and class C extends B.class A has equals method : class B has equals method : and class C has euals method : And the main has these code lines : I ca n't understand why the equals method of class A is being executed.I know that overloaded methods are bonded using s... | public boolean equals ( A other ) { ... } public boolean equals ( B other ) { ... } public boolean equals ( Object other ) { ... } A a = new A ( ) ; C c = new C ( ) ; a=c ; System.out.println ( a.equals ( c ) ) ; | java polymorphism aliasing issue |
Java | I have a rest Api with spring boot : but when I use postmanAnd In service function I have nothing when using code below.So what happen with parameter begin by `` # '' symbol . How to solve it ? | PageableResult < List < T > > search ( HttpServletRequest request , HttpServletResponse response ) { Map < String , String [ ] > params = request.getParameterMap ( ) ; log.info ( `` params : { } '' , params ) ; return getService ( ) .search ( params ) ; } String resultat = params.get ( `` resultat '' ) ; // I have noth... | Failed to pass parameter begin with # ? |
Java | I 've got this class : It seems to me that the compareTo method complies with the Comparator contract , even if it is not consistent with equals ( on purpose ) - that should not be a problem according to the javadoc : It is generally the case , but not strictly required that ( compare ( x , y ) ==0 ) == ( x.equals ( y ... | class Column implements Comparable < Column > { private final float startX ; private final float endX ; public Column ( float startX , float endX ) { this.startX = startX ; this.endX = endX ; } public boolean isSameColumn ( Column c ) { return c.startX < = this.startX & & this.startX < c.endX || this.startX < = c.start... | Another Comparison method that violates its contract |
Java | I 've just started to learn the Spring framework and I found some tutorial at javatpoint.com.I 've got this code ( nothing special , only prints some questions and answers ) : My question is : Why is he using that empty constructor and the keyword super ( ) ? The app works without them and I do n't get what are they go... | private int id ; private String name ; private Map < Answer , User > answers ; public Question ( ) { } public Question ( int id , String name , Map < Answer , User > answers ) { super ( ) ; this.id = id ; this.name = name ; this.answers = answers ; } | Java - use of super ( ) in the given example |
Java | I am not a Java programmer . I read the documentation on `` final '' , and understand it to mean `` a variable 's value may be set once and only once . `` I am translating some Java to C # . The code does not execute as expected . I tried to figure out why , and found some uses of final that do n't make sense.Code snip... | final int [ ] PRED = { 0 , 0 , 0 } ; ... PRED [ 1 ] = 3 ; final int [ ] PRED = new int [ this.Nf ] ; for ( int nComponent = 0 ; nComponent < this.Nf ; nComponent++ ) { PRED [ nComponent ] = 0 ; } ... PRED [ 1 ] = 3 ; | Understanding Java 's `` final '' for translation to C # |
Java | I have seen two different ways of declaring array of String but I do n't undrestand the difference . Can anyone explain what is the difference between String args [ ] and | String [ ] args | Differentiate between String args [ ] and String [ ] args |
Java | Consider this class : I have a List < User > and I would like to reduce on languages . Input : Expected output : I can achieve this using following code : But I do n't want to create two stream , can this be achieved using a single stream ? | @ Data @ AllArgsConstructor @ NoArgsConstructorclass User { String name ; String languages ; } List < User > list = new ArrayList < > ( ) ; list.add ( new User ( `` sam '' , `` java '' ) ) ; list.add ( new User ( `` sam '' , `` js '' ) ) ; list.add ( new User ( `` apollo '' , `` html '' ) ) ; [ User ( name=apollo , lan... | Collectors.reducing to List |
Java | The code below is supposed to work a little like the Multi-Document Interface ( MDI ) you might see in a browser like FF , IE or Chrome . It presents 'documents ' ( a black buffered image as spacer ) in a tabbed pane such that they can be dragged from the pane into a new ( or existing ) window by user choice.But it has... | import java.awt . * ; import java.awt.event . * ; import java.awt.image.BufferedImage ; import javax.swing . * ; import javax.swing.border.EmptyBorder ; public class DragTabFrame extends JFrame { private JTabbedPane tabbedPane = new JTabbedPane ( ) ; private final static DragTabManager dragTabManager = new DragTabManag... | DragTabFrame closing inconsistently |
Java | I want to define a value in my Scala code and treat this value as constant ( used in annotation ) within my Java code ( which is calling scala ) .For example : However when I 'm trying to use this value within Java annotation it gives me an error : java : attribute value must be constantCalling it like this does n't wo... | object MyValues { val a = 5 } @ Target ( ElementType.TYPE ) @ Retention ( RetentionPolicy.RUNTIME ) public @ interface MyJavaAnnotation { int aValue ( ) default MyValues.a ( ) ; // < -- Error } | Is there a way to treat scala value as constant from java |
Java | I need some help with a homework question I am working on.I need to create a `` Library '' class that contains an array of Song objects . ( capacity of 10 ) .Then make a method addSong.Here 's what I have so far : My question is : Is there another way to fill the array ? i will later need to search for a song based on ... | public class Library { Song [ ] arr = new Song [ 10 ] ; public void addSong ( Song s ) { for ( int i=0 ; i < 10 ; i++ ) arr [ i ] = s ; } } | Filling an array with objects |
Java | Consider a request-response protocol.We spawn a thread to perform a select ( ) loop for reads and writes on an accepted non-blocking SocketChannel . That might look something likewhere Context is just a container for the corresponding SocketChannel , a buffer and logic to read into it and write from it . The readReques... | while ( ! isStopped ( ) ) { selector.select ( ) ; Iterator < SelectionKey > selectedKeys = selector.selectedKeys ( ) .iterator ( ) ; while ( selectedKeys.hasNext ( ) ) { SelectionKey selectedKey = selectedKeys.next ( ) ; selectedKeys.remove ( ) ; Context context = ( Context ) selectedKey.attachment ( ) ; if ( selectedK... | How to establish a happens-before relationship between a request handling thread and a SocketChannel selector thread ? |
Java | I have a TableView in SelectionMode.MULTIPLE . Using a ListChangeListener I 'm able to catch the selection of multiple rows ( by pressing Shift ) .However my solution only works if the items are being selected in the same column OR in the area without columns . Gif for illustration with 4 examples : OK : Selecting 3 it... | ObservableList < DataRowModel > dataRows = FXCollections.observableArrayList ( ) ; dataRows.addAll ( dataSetModel.getRows ( ) ) ; tableDataRow.setItems ( dataRows ) ; tableDataRowStateColumn.setCellValueFactory ( f - > f.getValue ( ) .getState ( ) ) ; tableDataRow.getSelectionModel ( ) .setSelectionMode ( SelectionMode... | SelectedItems empty if multiple rows selected using different columns |
Java | I need to write a program that prints the product of all integer numbers from a to b ( a < b ) .Include a and exclude b from the product.Sample Input 1:1 2Sample Output 1:1Your code output:2Here is my code : What I 'm doing wrong ? Please a hint : ) UPDATE : It did n't help either.Test input:1 2Correct output:1Your cod... | import java.util.Scanner ; class Main { public static void main ( String [ ] args ) { Scanner scanner = new Scanner ( System.in ) ; long a = scanner.nextLong ( ) ; long b = scanner.nextLong ( ) ; long multiply = 0 ; for ( long i = a ; i < b ; i++ ) { multiply = i * ( i+1 ) ; } System.out.println ( multiply ) ; } } impo... | The for-loop The product of numbers from a to b |
Java | I 'm building CRUD interface for ArangoDB as Java service.My ArangoDB service has dynamic IP , but static URL . Thus I want to specify URL instead of IP and port.But when I set it in arangodb.properties file I get the following exception : How can I do it ? UpdateI have figured out that I have to connect to https serve... | Caused by : org.springframework.beans.BeanInstantiationException : Failed to instantiate [ com.netcracker.unm.activeinventory.services.ArangoService ] : Constructor threw exception ; nested exception is com.arangodb.ArangoDBException : Could not load property-value arangodb.hosts=127.0.0.1:8538,127.0.0.1:8529 , http : ... | Specify https host as arangodb host in properties |
Java | Lets say I have the following three arrays : All arrays will have same length.I want to convert them into an array of objects of type Color : Where each index will contain the r , g , b from the same index from the 3 arrays . For example , lets say for Color [ 1 ] = new Color ( r [ 1 ] , g [ 1 ] , b [ 1 ] ) ; How do I ... | int r [ ] = { 255,255,255 } ; int g [ ] = { 0,0,0 } ; int b [ ] = { 255,255,255 } ; public class Color { int r , g , b ; public Color ( int r , int g , int b ) { this.r = r ; this.g = g ; this.b = b ; } } Color [ ] arr = new Color [ 3 ] ; Color arr [ ] = new Color [ r.length ] ; for ( int i=0 ; i < r.length ; i++ ) { C... | Convert 3 arrays into 1 object array using Streams |
Java | I have an application that performs various analysis algorithms on graphs of nodes and edges G ( N , E ) . The attributes of the nodes and edges vary with the application and form an inheritance hierarchy based on the type of graph and nature of the attributes . For example the root of the Node hierarchy could represen... | import java.util.ArrayList ; import java.util.List ; public class NcgNode { private List < NcgNode > nodeList_ = null ; private List < ? extends NcgNode > nodeListSrc_ = null ; private List < ? super NcgNode > nodeListSink_ = null ; public < N extends NcgNode > void addNode ( N node ) { if ( nodeList_ == null ) { nodeL... | Inheritance and generics |
Java | I am trying to understand the features of Spliterator and came across these 2 methods estimatedSize and getExactSizeIfKnown I could figure out what is estimatedSize but not sure exactly what doesgetExactSizeIfKnowndo . Can someone please give an example explaining the difference between the two.EDIT : I tried the follo... | public static void main ( String [ ] args ) { List < Integer > l = new ArrayList < > ( ) ; l.add ( 1 ) ; l.add ( 2 ) ; l.add ( 3 ) ; Spliterator < Integer > s= ( Spliterator < Integer > ) l.spliterator ( ) ; Spliterator < Integer > s1=s.trySplit ( ) ; while ( s.tryAdvance ( n - > { System.out.print ( n+ '' `` ) ; Syste... | Difference between estimatedSize and getExactSizeIfKnown in Spliterator |
Java | I know in java Collections class , there is a static method sort : The second argument in sort should be an object which implements Comparator interface and it 's compare method.But when I learn lambda 's method reference , I see this example : } This is an example of method reference for instance method.the compareWor... | sort ( List < T > list , Comparator < ? super T > c** ) public class Test { public static void main ( String [ ] args ) { new Test ( ) .sortWord ( ) ; } public void sortWord ( ) { List < String > lst = new ArrayList < > ( ) ; lst.add ( `` hello '' ) ; lst.add ( `` world '' ) ; lst.add ( `` apple '' ) ; lst.add ( `` zip... | Java , why collections.sort ( ) still works with non-comparator typed argument ? |
Java | Is it possible to determine which aspects hook into a given class and to gain access to their instances ? Something like : | Foo foo = new Foo ( ) ; List < Object > aspects = getAllAspectsOf ( foo ) ; | Determine which aspects hook into a given class |
Java | 1 ) Why is the following assignment not allowed : but this assignment is allowed : Both types are signed , and I would expect b and i were -1.2 ) Why does n't the Integer MIN_VALUE have a sign ? but the Byte MIN_VALUE does have a sign ? | byte b = 0b11111111 ; // 8 bits or 1 byte int i = 0b11111111111111111111111111111111 ; //32 bits or 4 bytes public static final int MIN_VALUE = 0x80000000 ; public static final byte MIN_VALUE = -128 ; | Understanding Java data types |
Java | Could someone please explain why these two pieces of Java codes are behaving differently ? First one correctly counts number of bits but the second one just displays 1 or 0 for non-zero numbers . I do n't understand whats happening . | public static void printNumUnitBits ( int n ) { int num=0 ; for ( int i=0 ; i < 32 ; i++ ) { int x=n & 1 ; num=num+x ; n=n > > > 1 ; } System.out.println ( `` Number of one bits : '' +num ) ; } public static void printNumUnitBits ( int n ) { int num=0 ; for ( int i=0 ; i < 32 ; i++ ) { num=num+n & 1 ; n=n > > > 1 ; } S... | Using bitwise & operator and + in Java giving inconsistent results |
Java | I have following two methods : Do you have an elegant solution ( other than using type casting and Object ) that will avoid the duplicate code above and will use a single method name ? | public static double calculateMeanInt ( List < Integer > numbers ) { double sum = 0.0 ; for ( Integer number : numbers ) sum += number ; return sum/numbers.size ( ) ; } public static double calculateMeanDouble ( List < Double > numbers ) { double sum = 0.0 ; for ( Double number : numbers ) sum += number ; return sum/nu... | Method Overloading and Arguments with Generics in Java |
Java | I have an old code base that I need to refactor using Java 8 , so I have an interface , which tells whether my current site supports the platform.and I have multiple classes implementing it and each class supports a different platform.A few of the implementing classes are : Another implementation : At runtime in my fil... | public interface PlatformSupportHandler { public abstract boolean isPaltformSupported ( String platform ) ; } @ Component ( `` bsafePlatformSupportHandler '' ) public class BsafePlatoformSupportHandler implements PlatformSupportHandler { String [ ] supportedPlatform = { `` iPad '' , `` Android '' , `` iPhone '' } ; Set... | Refactor polymorphism using Java 8 |
Java | I 'm trying to sort a set of strings written in Macedonian alphabet . I know how to do it , but the end result is n't what I expected . Here is my test program : The letters in ALPHABET_ARRAY are in the correct alphabetical order , but the program prints абвгѓдежзѕијкќлљмнњопрстуфхцчџшBut it should have been : абвгдѓеж... | public class Main { private static final char [ ] ALPHABET_ARRAY = { ' а ' , ' б ' , ' в ' , ' г ' , ' д ' , ' ѓ ' , ' е ' , ' ж ' , ' з ' , ' ѕ ' , ' и ' , ' ј ' , ' к ' , ' л ' , ' љ ' , ' м ' , ' н ' , ' њ ' , ' о ' , ' п ' , ' р ' , ' с ' , ' т ' , ' ќ ' , ' у ' , ' ф ' , ' х ' , ' ц ' , ' ч ' , ' џ ' , ' ш ' } ; p... | Sort Macedonian alphabet using collation |
Java | Since Strings are immutable in Java , why would I want to use the argument-less String constructor and create an object ? How is the variable s useful to me after I do : | String s = new String ( ) ; | In Java , is String s = new String ( ) any use at all ? |
Java | According to this table , ++ has right to left associativity . So , I run this code : and expect the expression to be 50 ( as 8 + 7 * 6 , increment starts from right to left ) . But the expression is evaluated from left to right ( 6 + 7 * 8 ) by Eclipse , and gives result as 62 . I am new to this associativity in Java ... | int a = 5 ; ++a + ++a * ++a | How to explain this operator associativity ? |
Java | I 'm converting a project from Java to C # . I 've tried to search this , but all I come across is questions about enums . There is a Hashtable htPlaylist , and the loop uses Enumeration to go through the keys . How would I convert this code to C # , but using a Dictionary instead of a Hashtable ? | // My C # Dictionary , formerly a Java Hashtable.Dictionary < int , SongInfo > htPlaylist = MySongs.getSongs ( ) ; // Original Java code trying to convert to C # using a Dictionary.for ( Enumeration < Integer > e = htPlaylist.keys ( ) ; e.hasMoreElements ( ) ; { // What would nextElement ( ) be in a Dictonary ? SongInf... | Converting Enumeration < Integer > for loop from Java to C # ? What exactly is an Enumeration < Integer > in C # ? |
Java | For this experimental project based on the spring-boot-starter-data-jpa dependency and H2 in-memory database , I defined a User entity with two fields ( id and firstName ) and declared a UsersRepository by extending the CrudRepository interface.Now , consider a simple controller which provides two endpoints : /print-us... | @ RestController @ RequestMappingpublic class UsersController { private final UsersRepository usersRepository ; @ Autowired public UsersController ( UsersRepository usersRepository ) { this.usersRepository = usersRepository ; } @ GetMapping ( `` /print-user '' ) @ ResponseStatus ( HttpStatus.OK ) @ Transactional ( isol... | Why does @ Transactional isolation level have no effect when updating entities with Spring Data JPA ? |
Java | quick question.I 'm basically working on a program where we have an Entity cross across a grid . Every time it finishes a `` step '' ( ie , goes from ( 0 , 0 ) to ( 1 , 0 ) ) , I need to fire off an event . The entity 's movement per frame is calculated by : and then added onto the entity 's X co-ordinate . I elected t... | frameMovement = entitySpeed * ( frameDeltaMs / 1000 ) return Math.floor ( x ) % x == 0 ; x = 0f ; System.out.println ( Math.floor ( x ) % x ) ; > NaN x = 1f ; // Or any number with 1sd > 0System.out.println ( Math.floor ( x ) % x ) ; > 1f System.out.println ( `` x equals `` + x + `` . Math.floor ( x ) % x==Math.floor (... | Floor ( X ) modulo X equals X ? |
Java | Why does this result in a compile error : whereas the following does not ? : | Optional < Optional < Integer > > a = Optional.of ( Optional.of ( 1 ) ) ; Optional < Optional < ? extends Number > > b = a ; Optional < Optional < Integer > > a = Optional.of ( Optional.of ( 1 ) ) ; Optional < Optional < ? extends Number > > c = a.map ( x- > x ) ; | Nested generic with type bound results in compile error |
Java | So , I just read this blog post , and I was confused by the `` ternary-operator is left-associative '' part , so I ran the example code there-in in an interpreter : and indeed , it returns horse which is the counter-intuitiveness that was the point in the blog post.Out of curiosity , I then tried to `` make this work '... | $ arg = 'T ' ; $ vehicle = ( ( $ arg == ' B ' ) ? 'bus ' : ( $ arg == ' A ' ) ? 'airplane ' : ( $ arg == 'T ' ) ? 'train ' : ( $ arg == ' C ' ) ? 'car ' : ( $ arg == ' H ' ) ? 'horse ' : 'feet ' ) ; echo $ vehicle ; $ arg = 'T ' ; $ vehicle = ( ( $ arg ! = ' B ' ) ? ( $ arg ! = ' A ' ) ? ( $ arg ! = 'T ' ) ? ( $ arg ! ... | Nested Ternary-operator Associativity in php vs java |
Java | From answering this question , I ran into a peculiar feature . The following code works as I assumed it would ( the first two values within the existing array would be overridden ) : Output : However , attempting this with a sequential stream throws an IllegalStateException : Output : I 'm curious as to why the sequent... | Integer [ ] newArray = Stream.of ( 7 , 8 ) .parallel ( ) .toArray ( i - > new Integer [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ) ; System.out.println ( Arrays.toString ( newArray ) ) ; [ 7 , 8 , 3 , 4 , 5 , 6 ] Integer [ ] newArray = Stream.of ( 7 , 8 ) .toArray ( i - > new Integer [ ] { 1 , 2 , 3 , 4 , 5 , 6 } ) ; System.out.pri... | Why can I collect a parallel stream to an arbitrarily large array but not a sequential stream ? |
Java | ProblemWhen experimenting with the JNI interface , I was wondering if I could take a JObject and transmute it into an equivalent struct to manipulate the fields . However , when I tried I was surprised to see that this did not work . Ignoring how horrible this idea might be , why did n't it work ? My ApproachJava Test ... | public class Point { public final double x ; public final double y ; // As well as some random methods } C : \Users\home\IdeaProjects\test-project > java -cp jol-cli-0.9-full.jar ; out\production\java-test org.openjdk.jol.Main internals Point # Running 64-bit HotSpot VM. # Using compressed oop with 3-bit shift. # Using... | JNI Object Pointers |
Java | What would be the cleanest way to do this ? I have The maps all have the exact same keys , and no duplicate values . I want to append the Lists of map2 and map3 to the end of the list of map1 , for each key . This is how I am currently trying to do it : | Map < String , List < String > > map1 = ... ; Map < String , List < String > > map2 = ... ; Map < String , List < String > > map3 = ... ; Map < String , List < String > > conversions = new HashMap < String , List < String > > ( ) ; List < String > histList = new ArrayList < String > ( ) ; for ( String key : map1.keySet... | Combine multiple Map < String , List > structs by joining lists with keys of the same name |
Java | Sorry I couldnt think of a more concise title.My question is why does the following piece of code work : when it will not work making the Object array a generic as so : When the availableObjects [ i ] = new RenderElement ( ) ; line is executed in this latter example I get a ClassCastException . I understand why it work... | public abstract class TObjectPool < T > { protected Object [ ] availableObjects ; TObjectPool ( int size ) { availableObjects = new Object [ size ] ; } protected class RenderElementPool extends TObjectPool < RenderElement > { @ Override public void fill ( ) { for ( int i = 0 ; i < capacity ; i++ ) { availableObjects [ ... | Generics problem and arrays |
Java | I need a Collector that 's nearly identical to Collectors.toSet ( ) , but with a custom finisher . I 'd love to be able to do something like : and be done , but that does n't seem possible . The only alternative I can see is it essentially recreate Collectors.toSet ( ) using Collector.of ( ) , which is not very DRY.Is ... | myCollector = Collectors.toSet ( ) ; myCollector.setFinisher ( myCustomFinisher ) ; Collector < T , ? , Set < T > > toSet = Collectors.toSet ( ) ; return Collector.of ( toSet.supplier ( ) , toSet.accumulator ( ) , toSet.combiner ( ) , yourFinisher , toSet.characteristics ( ) ) ; | Extend an existing stream collector instance |
Java | I have a simple spring boot application and a controller class.A simple method inside my controller : I am calling this method from Postman , I can see the time it takes to complete this method is different in every call.For example 28ms , 70ms , 15ms ... It is ok if we talk about milliseconds but I have noticed that t... | @ GetMapping ( `` /heartbeat '' ) public ResponseEntity < String > heartbeat ( ) { return new ResponseEntity < > ( `` success '' , HttpStatus.OK ) } | Why Spring RESTful web services take different time to complete each time |
Java | I wanted to know if the allOf method of CompletableFuture does polling or goes into a wait state till all the CompletableFutures passed into the method complete their execution.I looked at the code of the allOf method in IntelliJ and it is doing some sort of binary search.Please help me to find out what the allOf metho... | public static CompletableFuture < Void > allOf ( CompletableFuture < ? > ... cfs ) { return andTree ( cfs , 0 , cfs.length - 1 ) ; } /** Recursively constructs a tree of completions . */static CompletableFuture < Void > andTree ( CompletableFuture < ? > [ ] cfs , int lo , int hi ) { CompletableFuture < Void > d = new C... | Why does the CompletableFuture allOf method do a binary search ? |
Java | I am a newbie at programming and Java and this is my first null , I am a little bit confused because I do not know what happened is that kind of errors in coding ? Or any thing else ? Kindly needs your explanation in this situation and about null at overall in a simple wayOutput is : | public static void main ( String [ ] args ) { Scanner input = new Scanner ( System.in ) ; System.out.println ( `` Enter grades size : '' ) ; int Size = input.nextInt ( ) ; String [ ] y = new String [ Size ] ; int [ ] x = new int [ Size ] ; int Max = 0 ; int Min = x [ 0 ] ; String Max_studen = y [ 0 ] ; String Min_stude... | Null issue needs an explanation |
Java | I 'm trying to create a custom BodyPublisher that would deserialize my JSON object . I could just deserialize the JSON when I 'm creating the request and use the ofByteArray method of BodyPublishers but I would rather use a custom publisher.This implementation works , but only if subscriptions request method gets calle... | public class CustomPublisher implements HttpRequest.BodyPublisher { private byte [ ] bytes ; public CustomPublisher ( ObjectNode jsonData ) { ... // Deserialize jsonData to bytes ... } @ Override public long contentLength ( ) { if ( bytes == null ) return 0 ; return bytes.length } @ Override public void subscribe ( Flo... | How to create a custom BodyPublisher for Java 11 HttpRequest |
Java | For studying purpose , I am trying to migrate this Java Command Pattern example to PHP : https : //codereview.stackexchange.com/questions/52110/command-pattern-implementationAs @ simon commented , using method reference operator , would modernize quite a bit the code : And then you could create commands like this : My ... | class MyCommand implements Order { private final Runnable action ; public MyCommand ( Runnable action ) { this.action = action ; } @ Override public void execute ( ) { action.run ( ) ; } } MyCommand bsc = new MyCommand ( stock : :buy ) ; MyCommand ssc = new MyCommand ( stock : :sell ) ; | How to migrate a java command pattern using runnable to PHP 7.4 ? |
Java | It is well known , that generic types do n't survive the compiling process . They are replaced by class casts.But nevertheless , the type information is present in the class file and can be seen using reflection : When executed , this will print java.lang.String.Can a JIT use this for some kind of optimization ? Or is ... | public class Demo { private List < String > list ; public Demo ( ) throws SecurityException , NoSuchFieldException { System.out.println ( ( ( Class < ? > ) ( ( ParameterizedType ) getClass ( ) .getDeclaredField ( `` list '' ) .getGenericType ( ) ) .getActualTypeArguments ( ) [ 0 ] ) .getName ( ) ) ; } public static voi... | Can a JIT take a benefit from Generics ? |
Java | I 'm currently studying a book for the AP CS A exam , specifically the Barron 's book for test preparation.One section of the book refers to two classes , Student and GradStudent , where GradStudent extends Student.GradStudent has the method getId ( ) while Student does not.If I were to run the following code : The boo... | Student s = new GradStudent ( ) s.getId ( ) Student s = new GradStudent ( ) GradStudent g = new GradStudent ( ) Student s = ( new GradStudent ( ) .setId ( 1 ) ) | Inheritance in Java and Object Types |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.