lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I 've got such an interface : And there is a list of listeners/observers : How can I easily inform all listeners , that A , B , C occurred via Listener.onA ( ) , Listener.onB ( ) , Listener.onC ( ) ? Do I have to copy-paste iteration over all listeners at least three times ? In C++ I would create such a function : And ... | public interface Listener { void onA ( ) ; void onB ( ) ; void onC ( ) ; } List < Listener > listeners = new ArrayList < Listener > ( ) ; void Notify ( const std : :function < void ( Listener *listener ) > & command ) { for ( auto & listener : listeners ) { command ( listener ) ; } } Notify ( [ ] ( Listener *listener )... | Java execute method on all objects in a List |
Java | To my surprise this code works fine : But the String reference should never be declared ? Could it be that all variables under every case always are declared no matter what , or how is this resolved ? | int i = 2 ; switch ( i ) { case 1 : String myString = `` foo '' ; break ; case 2 : myString = `` poo '' ; System.out.println ( myString ) ; } | When are references declared in a switch statement ? |
Java | Looking at the documentation of Font # loadFont I came across this remark : This method does not close the input stream . Unfortunately , this is not explained or expanded upon . So my question is : What are possible reasons the API wo n't close the input stream ? Is it likely you would like to re-use the stream ? I mo... | Font.loadFont ( getClass ( ) .getResourceAsStream ( `` path/to/font '' ) , 13.0 ) ; | Why does n't ` loadFont ` close input stream ? Should I close it ? |
Java | I found out yesterday that you can make a Java for-loop that looks like thisThis looks really unusual to me . When is coding like this acceptable/useful ? | for ( int j = 0 ; j < myArray.length ; System.out.println ( j ) , j++ ) { /* code */ } | In what cases would it be useful to put a command within a Java for-loop update statement ? |
Java | Why ca n't I do this in Java : As I understand , this will always be an instance of some class that extends TestClass , so why the code above is not allowed by compiler ? Even if I will extend the TestClass then type of this will fit extends TestClass anyway . I get the following error : Error : ( 4 , 16 ) java : incom... | public class TestClass { public < T extends TestClass > T test ( ) { return this ; // error here } } | return this from a generic method generalized with < T extends TestClass > |
Java | In AP Computer Science class today , I had this code : And this is valid . It prints 1 ( or -1 , I forget which ) , but it is possible to compare them . I understand that interface variables refer to an object of a class that implements that interface , but what makes no sense to me is how an interface variable can be ... | Comparable x = 45 ; Comparable y = 56 ; System.out.println ( x.compareTo ( y ) ) ; | Why is it possible to call method on Java interface method ? [ Comparable ] |
Java | I have been told by my Teacher that this is is the one and only code for Bubble SortBut I ran the program with a different outer loop-The Outputs are-1st Case-2nd case-So now I am being told that my code is wrong , even if my output comes correct.Please , tell me am I entirely wrong ? ? | int a [ ] = { 2,3,7,9,8,1,4,5,10,6 } ; for ( int i=0 ; i < a.length ; i++ ) { for ( int j=0 ; j < a.length-i-1 ; j++ ) { if ( a [ j ] > a [ j+1 ] ) { int t=a [ j ] ; a [ j ] =a [ j+1 ] ; a [ j+1 ] =t ; } } } for ( int i=0 ; i < a.length ; i++ ) { System.out.print ( a [ i ] + '' \t '' ) ; } int b [ ] = { 2,3,7,9,8,1,4,5... | Practical difference between two Bubble Sort loops |
Java | I feel embarrassed that I am stuck on this but I am trying to pull the List of Strings ( List < String > ) from the Map < MyEnum , String > given then List of enum keys List < MyEnum > . The List < MyEnum > may or may not contain entries.Edit : But I am looking for a Java 8 way to do this . Such as ... | List < String > toReturn = new ArrayList < > ( ) ; for ( MyEnum field : fields ) { String value = null ; if ( ( value = map.get ( field ) ) ! = null ) { toReturn.add ( value ) ; } } return toReturn ; map.stream ( ) .map ( e- > ? ? ? ? ? ) | Pulling a List of Values from a Map given a List of Keys on Java 8 |
Java | I want to count how often an element from ArrayList `` list1 '' occurs in the other ArrayList `` list2 '' .I want this output : I get this output : Coud you please help me to do this ? Thank you ! | A 2B 0C 1D 2 A 0B 0C 0D 69 enter code here HashMap < Character , Integer > map = new HashMap < Character , Integer > ( ) ; ArrayList < Character > list1 = new ArrayList < Character > ( ) ; ArrayList < Character > list2 = new ArrayList < Character > ( ) ; Collections.addAll ( list1 , ' A ' , ' B ' , ' C ' , 'D ' ) ; Col... | How can I count how often an element from an ArrayList occurs in the another ArrayList ? |
Java | Say I have a class with some members , and the members have a less restrictive access modifier than the class itself.A concrete example could be : To my understanding a class access modifier that is more restrictive than the member access modifier , will override the less restrictive member access modifiers . So a less... | package apples ; class A { // package private public int foo ( ) { // public ( = > less restrictive than *package private* ) return 42 ; } } package apples ; import java.util.function.IntSupplier ; public class B { public IntSupplier getReferenceToAFoo ( ) { A aInstance = new A ( ) ; return aInstance : :foo ; } } packa... | Whats the use of less restrictive member access modifiers than the class access modifier ? |
Java | Note : I 'm using a 3rd party app that uses regex for searches which has its own flavor but almost always works like java 's flavor of regex . Of course this may not matter.After searching for many different ways of this same question ( phrased many ways ) , I did not see any tutorials , examples , or even mentions of ... | [ \w^\s < > . ! ? ] { 2 } [ \w|^\s < > . ! ? ] { 2 } | with regex , is using both `` is '' and `` is not '' range definitons within the same range possible ? |
Java | I simply want to have my own annotation to clean up the annotation mass and to be able to change them easily when I want ; Wish I couldnullable = false , length = 32 are the default params.Java or Kotlin solutions are welcome . | import javax.persistence.Columnimport javax.validation.constraints.Sizeclass Foo ( ) { @ Column ( name= '' bar_ '' , nullable = false , length = 32 ) @ Size ( min = 32 , max = 32 ) String bar ; @ Column ( nullable = false , length = 32 ) @ Size ( min = 32 , max = 32 ) String bas ; @ Column ( nullable = false , length =... | How to wrap @ Column annotation with my own annotation in Java or Kotlin |
Java | I am trying to understand the following code . Line number 2 outputs null while line 3 throws NullPointerException . What am I missing ? Theoretically it should work . | public static void main ( String [ ] args ) { 1 Object [ ] obj = { null } ; 2 System.out.println ( ( Integer ) obj [ 0 ] ) ; //Output null 3 Integer n = obj [ 0 ] == null ? ( Integer ) obj [ 0 ] : 1 ; //NullPointerException 4 System.out.println ( n ) ; } | Casting Null Object into Integer |
Java | I have a question concerning Java 's Type system.I have four classes A , B , AStar and BStar . AStar extends A and Bstar extends B.On top of that I have another class that has the followingmethods : The implementation that is executed is the first one.From my understanding , Java considers the static types of the argum... | public static void main ( String [ ] args ) { AStar a = new AStar ( ) ; BStar b = new BStar ( ) ; someMethod ( a , b ) ; } public static void someMethod ( A a , BStar b ) { System.out.println ( `` first '' ) ; } public static void someMethod ( AStar a , B b ) { System.out.println ( `` second '' ) ; } | Determining which method will be executed ( Type system ) |
Java | Running this code , I would expect it to increment the test variable for 5 seconds and then finish.However when I run it the program does n't end ( I assume , I have given it a reasonable amount of time ) . However if I change the while loop toThe program finishes in the expected amount of time ( and prints out a lot o... | import java.util.Timer ; import java.util.TimerTask ; public class Test { private static boolean running ; public static void main ( String [ ] args ) { long time = 5 * 1000 ; // converts time to milliseconds long test = Long.MIN_VALUE ; running = true ; // Uses an anonymous class to set the running variable to false T... | Timed while loop not terminating |
Java | I came across this question recently where I am suppose to find the deadlock in the code present below . I have no experience with Java or multithreading , that 's why I am here to understand the problem better.I have this above piece of code . I want to find where a deadlock could occur in the above code . I think onl... | public class BankAccount { private final int customerId ; private int balance ; public BankAccount ( int customerId , int openingBalance ) { this.customerId = customerId ; this.balance = openingBalance ; } public void withdraw ( int amount ) throws OverdrawnException { if ( amount > balance ) { throw new OverdrawnExcep... | Troubleshooting and fixing deadlock |
Java | The code below generates the output : In long . If I change the parameter from ( int ... x ) to ( int x ) , it will print It is int instead . Why is that ? | public class Sub { void probe ( int ... x ) { System.out.println ( `` It is int '' ) ; } void probe ( long x ) { System.out.println ( `` In long '' ) ; } public static void main ( String [ ] args ) { int b = 4 ; new Sub ( ) .probe ( b ) ; } } | Why an int ... variable wrapped into long when both methods present in the same class |
Java | I 'm trying to check if the last node of a linked list points to the head . This code seems to give a positive result for the problem , but also gives a false positive for a list that contains a node pointing to a non-head node.I 've been trying different things such as checking if the slow node is equal to the head at... | public boolean isLinkedToStart ( Node head ) { if ( head == null ) { return false ; } Node fast = head.next ; Node slow = head ; while ( fast ! = null & & fast.next ! = null ) { if ( fast.next.next == slow ) { return true ; } fast = fast.next.next ; slow = slow.next ; } return false ; } | Checking if Linked List joins back to start |
Java | I 've found a rather strange thing for me while working with Java . Maybe it 's an ordinary thing , but i do n't understand why it works this way.I have a code like this : It works fine and the output is `` true '' .Then I change the english B to slavic B ( Б ) : Now the output is `` false '' . How come ? By the way , ... | Character x = ' B ' ; Object o = x ; System.out.println ( o == ' B ' ) ; Character x = ' Б ' ; Object o = x ; System.out.println ( o == ' Б ' ) ; | Java . Why does it work differently with english and slavic characters ? |
Java | Given two Lists of Objects , I 'd be able to tell which items are not in their intersect based on one of their attributes . Let 's look at the following example : I have a class Foo that has two attributes : boo and placeholder Now I am creating two Lists from that ( let 's say this is my input ) And now I 'd like to s... | class Foo { private int boo ; private int placeholder = 1 ; public Foo ( int boo ) { this.boo = boo ; } public int getBoo ( ) { return boo ; } } List < Foo > list1 = new ArrayList < Foo > ( ) ; list1.add ( new Foo ( 1 ) ) ; list1.add ( new Foo ( 2 ) ) ; list1.add ( new Foo ( 3 ) ) ; List < Foo > list2 = new ArrayList <... | Java : Proper way of creating a list containing all not-in-intersect elements from two given lists based on a specific attribute ? |
Java | Say I have a class foo : If I have a list of foo 's , is there a way for me to create a new list/array/whatever of foo 's with essentially the someString and someList values remapped ? For example : Would becomeRight now , I have a nested loop that iterates over each element of someList for each foo and compiles them i... | class foo { String someString ; List < String > someList ; } arr1 : [ foo { someString : 'test1 ' , someList : [ ' a ' , ' b ' ] } , foo { someString : 'test2 ' , someList : [ ' b ' , ' c ' ] } ] arr2 : [ foo { someString : ' a ' , someList : [ 'test1 ' ] } , foo { someString : ' b ' , someList : [ 'test1 ' , 'test2 ' ... | Switch direction of association between objects |
Java | Q : Is there a case where clear ( ) never gets executed ? I personally feel that there are no cases where clear ( ) will not be executed . | try { if ( check ) { while ( true ) ; } else { System.exit ( 1 ) ; } } finally { clear ( ) ; } | case where code never gets to clear ( ) |
Java | I shall rewrite C code into Java . The core of original C code is a HW wrapper . In C we were using lots of unions for each HW register eg : then we used it like imagine there is plenty of those registers . Let say 40 . How to implement it into java not having 40 class files ? I was thinking to create one class likethe... | typedef union RegIntStatus { u8 reg ; struct { u8 bit0_abc:1 ; u8 bit1_cde:1 ; u8 bit2_xyz:1 ; u8 bit3_7_rsvd:5 ; } bits ; } regABC ; regABC r ; r.reg=0r.bits.bit0_abc=1 ; call ( r.reg ) univerasl_reg < T > { // where T will be some `` enum '' public byte b ; public byte set ( T bit_mask , bool val ) { // here is compi... | how to write lots of small unions from C into Java |
Java | I am running with COMPSs the Increment application shown in the COMPSs Sample Application Manual . I have added the -m flag to enable the monitoring feature : The application runs and finishes properly ( no error shown in the std output/error and the runtime.log inside the .COMPSs folder has n't got any stack trace ) .... | $ runcompss -m -- debug increment.Increment 5 1 2 3 $ /etc/init.d/compss-monitor start* Starting COMPSs Monitor* Checking JAVA Installation ... Success* Checking IT_HOME ... WARNING : IT_HOME not defined . Trying default location /opt/COMPSs/ Success* Checking IT_MONITOR ... IT_MONITOR=/root/.COMPSs/ Success* Checking ... | COMPSs Monitor does n't show any application |
Java | I am having a scenario where two functions are identically similar but the Class object used in the two differ , similar like this , And similarly other function like , How can I use the generic class for the master object in above object ? I have n't used generics yet . | public int function1 ( inputObject input ) { LeadMaster lead= input.getLeadMaster ( ) ; PropertyUtils.setProperty ( lead , input.getKey ( ) , input.getValue ( ) ) ; return 0 ; } public int function2 ( inputObject input ) { DealMaster deal= input.getDealMaster ( ) ; PropertyUtils.setProperty ( deal , input.getKey ( ) , ... | Using Generic Type for same functionality |
Java | So my questions is : Why is it not a compile error to do anInt += aDouble ? | int anInt = 1 ; double aDouble = 2.5 ; anInt = anInt + aDouble ; // Error - need to cast double to intanInt += aDouble ; // This is ok. Why ? anInt = aDouble ; // This is also an error.anInt = 1 + aDouble ; // This is also an error . | Java Puzzler - casting a double to int |
Java | Is there a way to simplify filter using stream ? Or for it to be shorter or optimized ? I 'm not quite sure if using a for loop would be better to use in this scenario.I 'm just trying to separate the failed and the success messages using the failedIds.Here is my code Thank you ! | List < Message > successMessages = messageList.stream ( ) .filter ( message - > ! failedMessageIds.contains ( message.getId ( ) ) ) .collect ( Collectors.toList ( ) ) ; List < Message > failedMessages = messageList.stream ( ) .filter ( message - > failedMessageIds.contains ( message.getId ( ) ) ) .collect ( Collectors.... | Better approach for stream filter in Java |
Java | I have noticed that initializing 2D array like this case 1 : - taking more time than initializing it like this case 2 : -in case 1 it toke time around 4000ms but in case 2 it does not exceed 100ms why there is this big gap ? | int ar [ ] [ ] = new int [ 10000001 ] [ 10 ] ; int ar [ ] [ ] = new int [ 10 ] [ 10000001 ] ; | why is java taking long time initializing two dimensional arrays starting with the first dimension having a big size number ? |
Java | I try to dive deeply into the Java Generics and I 've come across a problem described by the following sample code.The output of the sample isAll the types are obviously known at compile time . As far as I understand , Java holds only a single compiled copy of each method ( unlike C++ ) and because no other constraints... | public static void test ( Object o ) { System.out.println ( `` Hello Object ! `` ) ; } public static void test ( Integer i ) { System.out.println ( `` Hello Integer ! `` ) ; } public static < T > void test ( Collection < T > col ) { for ( T item : col ) { System.out.println ( item.getClass ( ) .getSimpleName ( ) ) ; te... | Java Generics - calling specific methods from generic-typed ones |
Java | I 'm using an external library that provides tightly related classes ( generated from some template ) , but unfortunately without a shared interface , e.g.Given I have no influence over the external library , what 's the idiomatic way to write logic common to a group of classes that share the same method signatures ( a... | public class A { public UUID id ( ) ; public Long version ( ) ; public String foo ( ) ; public String bar ( ) ; } public class B { public UUID id ( ) ; public Long version ( ) ; public String foo ( ) ; public String bar ( ) ; } public class C { public UUID id ( ) ; public Long version ( ) ; public String foo ( ) ; publ... | What is the idiomatic way to write common code for a group of classes with identical methods , but not implementing the same interface ? |
Java | I 've tried two ways to iterate char-by-char over java.lang.String and found them confusing . The benchmark summarizes it : Intuitively the approach described in toCharArray ( ) seems to be less effective as it allocates a copy of underlying char [ ] as of Java 8 and encodes byte [ ] into char [ ] as of Java 9 and newe... | @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ Fork ( jvmArgsAppend = { `` -Xms2g '' , `` -Xmx2g '' } ) public class CharByCharIterationBenchmark { @ Benchmark public void toCharArray ( Data data , Blackhole b ) { char [ ] chars = data.string.toCharArray ( ) ; for ( char ch : chars ) {... | Could one explain significant performance difference in char-by-char iteration over j.l.String ? |
Java | Lately I 've been doing a lot with reflection and implemented this little utility method . I was surprised to find that the first version does not compile , but the latter does.Does not compile : Compiles and works just fine : Two questions : what 's wrong with it ? is there a better way of doing this ? Here 's the com... | public static < T > Class < T [ ] > getArrayClassOfType ( Class < T > componentType ) { return Array.newInstance ( componentType , 0 ) .getClass ( ) ; } public static < T > Class < T [ ] > getArrayClassOfType ( Class < T > componentType ) { Class c = Array.newInstance ( componentType , 0 ) .getClass ( ) ; return c ; } ... | surprising compilation error getting the array class of a class |
Java | In JLS Sec 8.4.3.6 , synchronized methods , it says : has exactly the same effect as : This looks odd to me , not to mention over-complicated : why use Class.forName ( `` BumpTest '' ) , not BumpTest.class ? It 's not possible that BumpTest is n't loaded , because it 's executing code from that class , after all . And ... | class BumpTest { // ... static synchronized void classBump ( ) { classCount++ ; } } class BumpTest { // ... static void classBump ( ) { try { synchronized ( Class.forName ( `` BumpTest '' ) ) { classCount++ ; } } catch ( ClassNotFoundException e ) { } } } | Why Class.forName ( `` BumpTest '' ) , not BumpTest.class ? |
Java | I 'm trying to reason about how the JIT of Hotspot reasons . I 'm mostly interested in the latest compilation stage ( C2 compiler ) . Does the JIT in Java rely on assertions for optimisations ? If that was the case , I could imagine that there are examples where code could run faster with assertions enabled.For example... | static int getSumOfFirstThree ( int [ ] array ) { assert ( array.length > = 3 ) ; return array [ 0 ] + array [ 1 ] + array [ 2 ] ; } | Java , Assertions and the JIT |
Java | I 'm trying to use the page object model for my tests and I 'm trying to structure my page classes to be able to do a `` builder pattern-like '' structure ( I 've not seen it very often so I do n't know if it has a name or if it is even a thing ) like in this example : And then use it like : So this is how I would mana... | public class Page1 implements Page { public static Page1 goOn ( ) { return new Page1 ( ) ; } public Page1 action1 ( ) { return this ; } public Page2 gotoPage2 ( ) { return new Page2 ( ) ; } } public class Page2 implements Page { public Page2 action2 ( ) { return this ; } public Page2 gotoPage1 ( ) { return new Page2 ( ... | How to handle page navigation using Page Object Model |
Java | I am looking for something akin to this syntax even though it does n't exist.I want to have a method act on a collection , and for the lifetime of the method , ensure that the collection is n't messed with.So that could look like : but instead , I am afraid the only way to do this would be : Is that the best way to do ... | private void synchronized ( collectionX ) doSomethingWithCollectionX ( ) { // do something with collection x here , method acquires and releases lock on // collectionX automatically before and after the method is called } private void doSomethingWithTheCollectionX ( List < ? > collectionX ) { synchronized ( collectionX... | Synchronizing on an object in Java |
Java | Assume I have a method with the following signature : The method accepts a map of functions ( with string keys ) and creates a Comparator < T > as a result ( it is n't important how ) . Map values are instances of Function < ? super T , ? extends U > , so that they can be directly passed to Comparator.comparing ( ) .Ho... | < T , U extends Comparable < ? super U > > Comparator < T > method ( Map < String , Function < ? super T , ? extends U > > comparatorFunctionMap ) Map < String , Function < ? super Person , ? extends Comparable > > map1 = new HashMap < > ( ) ; map1.put ( `` name '' , Person : :getName ) ; method ( map1 ) ; Map < String... | Type-safely create instance of Function to be passed to Comparator.comparing ( ) |
Java | I have a LinkedList of 1,000,000 items . I measured the retrieval of an item first at index 100,000 and then at index 900,000 . In both cases , the LinkedList goes through 100,000 operations to get to the desired index . So why is the retrieval from the end so much slower than from the start ? Measurements taken with J... | @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.MILLISECONDS ) @ Warmup ( iterations = 10 ) @ Measurement ( iterations = 10 ) public class ComparationGet { static int val1 = 100_000 ; static int val2 = 500_000 ; static int val3 = 900_000 ; @ Benchmark public void testGet1LinkedListFromStart ( Blackhole... | Why is getting a value from the end of a LinkedList much slower than from the start ? |
Java | I want to get the pair of every two distinct element in set . I think that if using for-each loop I have to iterate with complexity of O ( n^2 ) . If using iterator , I can have two iterators where the second one points to the next of the first one , which means for the second loop I do n't have to loop from the start ... | public static void main ( String [ ] args ) { Set < String > s = new HashSet < String > ( ) ; s.add ( `` A '' ) ; s.add ( `` B '' ) ; s.add ( `` C '' ) ; s.add ( `` D '' ) ; Iterator < String > itr1 = s.iterator ( ) ; while ( itr1.hasNext ( ) ) { Iterator < String > itr2 = itr1 ; String s1 = itr1.next ( ) ; while ( itr... | Iterate two distinct elements in set ? |
Java | I have a beginners question . I searched a lot for the answer but ca n't seem to find the exact answer so maybe somebody of more experienced developers can help me with this one.So , let 's say you have a following situation in code ( this is simplified version of the situation ) : now I heard from several people sayin... | SomeObject a1 = new SomeObject ( ) ; a1 = someMethod ( a1 ) ; public SomeObject someMethod ( SomeObject a1 ) { a1.changeVariable ( ) ; return a1 ; } | Calling a method and passing an object reference and catching the return with same reference |
Java | Let 's say I have a Vector v that contains 100 objects of class Scenario which is composed of 10 different types of objects.In order to permanently delete Scenario and all its objects at index 5 of Vector v , which one of the following is correct way.OR : OR : | 1. v.removeElementAt ( 5 ) ; 2 . Scenario s= ( Scenario ) v.elementAt ( 5 ) ; v.removeElementAt ( 5 ) ; s=null ; 3 . Scenario s= ( Scenario ) v.elementAt ( 5 ) ; s.makeAllObjectsNull ( ) ; //explicitly assign null to 10 objects inside Scenario e.g . object1=null object2=null and so on v.removeElementAt ( 5 ) ; s=null ; | Should object be explicitly deleted after removing it from a Vector ? |
Java | I 'm trying to create a function to sum up the rows of 2D arrays . I already have the code , but the return value does not seem to be working . Just need your thoughts as I need this finished in 24 hours : DThanks ! | int sumRows ( int ArrayR [ ] [ ] ) { int row=3 ; int col=3 ; int sumR = ArrayR [ 0 ] [ 0 ] ; //int [ ] sumR = new int [ row ] ; for ( int i = 0 ; i < row ; i++ ) { for ( int j = 0 ; j < col ; j++ ) { sumR+=ArrayR [ i ] [ i ] ; } } return sumR ; } | add rows of 2D arrays in processing |
Java | Consider the following scenario : Say that you created an interface Foo : And say that there is an old class SomeOldClass in a certain library that you want to use . It already has the bar ( ) method , but does not explicitly implement Foo.You have written the following code for all classed that implement Foo : And now... | public interface Foo { public void bar ( ) ; } public < T extends Foo > T callBarOnThird ( List < T > fooList ) { return fooList.get ( 2 ) .bar ( ) ; } | Does java support `` Soft '' interfaces ? |
Java | Java 11 ( may be irrelevant ) : Surprising output : Why does Java statically choose different methods ? | public static String toString ( Object obj ) { return ReflectionToStringBuilder.toString ( obj , ToStringStyle.SHORT_PREFIX_STYLE ) ; } public static String toString ( Collection < Object > collection ) { return collection.stream ( ) .map ( SaLogUtils : :toString ) .collect ( Collectors.joining ( `` , `` , `` [ `` , ``... | Java static polymorphism ( overloading ) and inheritance between generics |
Java | CountLatch is a thread control mechanism whereby a thread ( or many threads ) can block by calling await ( ) on a CountLatch object , which will release when its countDown ( ) method has been called some number of times.Since I 'm familiar with the concept of thread control with wait ( ) and notify ( ) , there is a ( t... | private volatile int count ; // initialised in constructorpublic synchronized void countDown ( ) { count -- ; if ( count < = 0 ) { notifyAll ( ) ; } } public synchronized void await ( ) throws InterruptedException { while ( count > 0 ) { wait ( ) ; } } private static final class Sync extends AbstractQueuedSynchronizer ... | What is the advantage of using a QueudSynchronizer to implement CountLatch |
Java | Since StringBuffer is thread safe it can safely be published . Consider the public constructor of StringBuffer ( sources ) : where super ( 16 ) designates this one : where value declared as QUESTION : How to publish StringBuffer safely ? I 've got the following class : Can it be considered as safe-publication ? I think... | public StringBuffer ( ) { super ( 16 ) ; } AbstractStringBuilder ( int capacity ) { value = new char [ capacity ] ; } char [ ] value ; public class Holder { public final StringBuffer sb = new StringBuffer ( ) ; } | How to publish StringBuffer safely ? |
Java | I am trying to learn how to use the lambda functions for sleeker code but struggling to make this work.I have two lists . The `` old '' list is always shorter or the same length as the `` updated list '' .I want to take the objects from the `` updated list '' and overwrite the `` stale objects '' in the shorter `` old ... | List < MyObject > updatedList ; List < MyObject > oldList ; updatedList.forEach ( MyObject - > { String id = MyObject.getId ( ) ; if ( oldList.stream ( ) .anyMatcher ( MyObject - > MyObject.getId ( ) .matches ( id ) ) { //Do the replacement here ? If so ... how ? } } | Updating a subsection of a list with an `` id '' field |
Java | When we declare a static final , the Java compiler ( or pre-compiler ? ) seems smart enough to detect out-of-range numbers : The code above proves that for int , short , and char values , the compiler only complains when the value is out-of-range for the type of the assigned variable.However for long values , the compi... | public class Test { // setup variables : public static final int i_max_byte = 127 ; public static final int i_max_byte_add1 = 128 ; public static final int i_max_short = 32767 ; public static final int i_max_short_add1 = 32768 ; public static final int i_max_char = 65535 ; public static final int i_max_char_add1 = 6553... | Why are in-range narrowed long values not implicitly converted ? |
Java | I have a hashmap which is the following : How would I get the keys which have the 3 highest values ? So it would return : Thanks . | HashMap < String , Integer > hm = new HashMap < String , Integer > ; hm.put ( `` a '' , 1 ) ; hm.put ( `` b '' , 12 ) ; hm.put ( `` c '' , 53 ) ; hm.put ( `` d '' , 2 ) ; hm.put ( `` e '' , 17 ) ; hm.put ( `` f '' , 8 ) ; hm.put ( `` g '' , 8 ) ; `` c '' , `` e '' , `` b '' | How to get the 3 highest values in a HashMap ? |
Java | I want to transform the string AABSSSD into 2AB3SD ( someone called it encryption ) .This is how I tried to resolve it : But the output is : This result is not exactly what I want . Please help me transform `` AABSSSD '' into `` 2AB3SD '' . | public class TransformString { public static void main ( String [ ] args ) { String str = `` AABSSSD '' ; StringBuilder newStr = new StringBuilder ( `` '' ) ; char temp = str.charAt ( 0 ) ; int count = 0 ; for ( int i = 0 ; i < str.length ( ) ; i++ ) { if ( temp == str.charAt ( i ) ) { count++ ; } else { newStr.append ... | How to transform the string `` AABSSSD '' into `` 2AB3SD '' ? |
Java | Here I have an example : When running this program , we 'll get output with `` The object has been collected . '' after a while , which means the object will be gc-ed . However , there is still a strong reference named `` obj '' linked to the object , how can it be reclaimed ? Because JVM found there is no strong refer... | import java.lang.ref.WeakReference ; public class WeakRefTest { public static void main ( String [ ] args ) { Object obj = new Object ( ) ; WeakReference < Object > weakRef = new WeakReference < Object > ( obj ) ; int i = 0 ; while ( true ) { if ( weakRef.get ( ) ! = null ) { i++ ; System.out.println ( `` The object is... | Java object is gc-ed when it 's still linked with a strong reference and a weaked reference |
Java | Here 's a very basic test program : But I do n't understand why its output is : Since static members are not serialized and hence get default values I was expecting another output : How did the deserialized object acquire the right static field value ? I 've made this test application because I need to serialize a few ... | public class Body implements Serializable { static int bod = 5 ; int dis = -1 ; public void show ( ) { System.out.println ( `` Result : `` + bod + `` & `` + dis ) ; } } public class Testing { public static void main ( String [ ] args ) { Body theBody = new Body ( ) ; theBody.show ( ) ; try { ObjectOutputStream out = ne... | Does deserialized object preserve static values ? |
Java | Consider the following codeIt prints map . Why is T deduced to be Map instead of SortedMap in public < T extends Map < String , String > > Test ( T t ) ? Is there a way to change this behaviour in order to use the most concrete constructor for MyClass ? | class MyClass { public MyClass ( Map < String , String > m ) { System.out.println ( `` map '' ) ; } public MyClass ( SortedMap < String , String > m ) { System.out.println ( `` sortedmap '' ) ; } } public class Test { public < T extends Map < String , String > > Test ( T t ) { new MyClass ( t ) ; } public static void m... | Java generic method . Why is T deduced to be Map ? |
Java | Why the instance of A can cast to List but can not cast to String ? | class A { } ... A a = new A ( ) ; List list = ( List ) a ; //passString s = ( String ) a ; //compile error | Java Customs class instance ca n't cast to String . Why ? |
Java | In JavaScript , it 's possible to do something along these lines : This would assign returnValue to qwerty . Is there any way to do something similar in Java ? Something like : I understand that I could write out a separate method , but I 'd like to do it in a way similar to above as it looks neater and cleaner in the ... | var qwerty = ( function ( ) { //some code return returnValue ; } int num = { public int method ( ) { //some code return val ; } } | Is it possible to directly assign the return value of a method to a variable ? |
Java | I am wondering if there is any reason to use an Executor instead of an ExecutorService.As far as I know there is no implementation of the Executor interface in the JDK which is not also an ExecutorService which means you have to shut the service down so that there are no memory leaks . You can not shut an Executor down... | private final Executor _executor = Executors.newCachedThreadPool ( ) ; | Is there any scenario for Executor instead of ExecutorService . Intention behind Executor interface ? |
Java | Basically , if I have an ArrayList < Integer > containing < 0 , 1 , 5 , 5 , 4 , 2 > , I need to create a separate ArrayList of < 2 , 3 > for the indexes.I understand how to get the index for the first appearance of the largest number , but I do n't know how to get all of them at the same time.I was originally thinking ... | int highest = 0 ; for ( int b = 0 ; b < arrlst.size ( ) ; b++ ) { int p = arrlst.get ( b ) ; if ( highest < = p ) { highest = p ; highestindex.add ( b ) ; } } | How to find all occurences of the highest number in a list ? |
Java | The following code snippet throws the error : `` Generic array creation '' despite not having any generic instances within the Node class . However , if i declare the private class Node as static , the error goes away . Why is the static keyword important here ? | public class SeperateChainingST < Key , Value > { private int M =97 ; private Node [ ] st = new Node [ M ] ; private class Node { Object key ; Object val ; Node next ; } } | Why do I need to declare a private class static to avoid the `` Generic Array Creation '' error ? |
Java | Initially I have a deck Image and a text `` Deck '' just below the image which looks fine But after I add my gridLayout panel , my whole GUI design has been messed up . As you can see my deck image is not aligned properly with the first row of my gridLayoutand my text `` deck '' has been separated by a few wide space.W... | public class GuiTut extends JPanel { private GridBagConstraints c = new GridBagConstraints ( ) ; private JLabel deckLabel = new JLabel ( ) ; public GuiTut ( ) { setLayout ( new GridBagLayout ( ) ) ; try { deck = ImageIO.read ( new File ( `` resources/images/deck.jpg '' ) ) ; } catch ( Exception e ) { } c.gridx = 0 ; c.... | GridBagLayout not aligning images properly |
Java | So , I ran a test and the results make no sense to me . Lets consider the following code : With the Runnable as follows : Only one instance of counter is shared between threads . It takes less time for another thread to start then even one increment to be made on the counter.doProceed should , as I understand never be ... | ThreadStuffCounter counter_1 = new ThreadStuffCounter ( 1 ) ; while ( counter_1.doProceed ) { Thread.sleep ( 500 ) ; Thread thread = new Thread ( counter_1 ) ; thread.start ( ) ; } package test ; public class ThreadStuffCounter implements Runnable { public volatile boolean doProceed = true ; private int id = -1 ; publi... | How can this loop ever exit ? |
Java | I 'm writing a regex for a simple username validation for practice . While I am sure there may be other issues with this pattern , I would like it if someone could explain this seemingly odd behavior I am getting . When I input : the compiler should return : but instead , it returns Why does it discriminate between the... | import java.io . * ; import java.util . * ; import java.text . * ; import java.math . * ; import java.util.regex . * ; public class userRegex { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; int testCases = Integer.parseInt ( in.nextLine ( ) ) ; while ( testCases > 0 ) { String u... | Regex pattern discriminating between letters when it should n't ? |
Java | This question has answer in C++.Is there any way to do the same or to invoke the code from Java/Android side ? Combining two YV12 image buffers into a single side-by-side imageWhat is this code analogues in java/kotlin ? This memcpy function ( taken from c++ reference memcopy ) has any analogues ? | BYTE* source = buffer ; BYTE* destination = convertBuffer3D ; void * memcpy ( void * destination , const void * source , size_t num ) ; | Combining two YV12 image buffers into a single side-by-side image Java/Android |
Java | I have Exception in thread `` main '' java.lang.NoClassDefFoundError : A ( wrong name : a ) and I dont't have any idea what this can caused byEdit : in online compiler https : //www.onlinegdb.com/online_java_compiler it compiles | public class Test { public static void main ( String [ ] args ) { new B ( ) ; } } interface a { } class A implements a { } class B extends A { } | Strange exception when implementing interface |
Java | I have two large ( 1000+ object ) ArrayLists that I need to compare and manipulate . I essentially need to take a value from ArrayList A , look for a matching object in ArrayList B , then manipulate the object from B. I need to do this in all objects for A. I need to do this frequently in the application . Order is not... | ( pseudocode ) ArrayList < myObject > AArrayList < myObject > B ( pseudocode ) for ( each object in A ) { loop through all of B and find it } ( pseudocode ) convert B to HashMap < myObject.myValue , myObject > Cfor ( each object in A ) { look up the value in C } convert C back to an ArrayList | Performance : Loop through ArrayList hundreds of times vs converting Arraylist to HashMap and Back ? |
Java | I have a very basic JAX-RS service ( the BookService class below ) which allows for the creation of entities of type Book ( also below ) . POSTing the payloadsuccessfully persists the Book and returns 201 CREATED . However , including an id attribute with whichever non-null value on the payload triggers an org.hibernat... | { `` acquisitionDate '' : 1418849700000 , `` name '' : `` Funny Title '' , `` numberOfPages '' : 100 } @ Stateless @ Path ( `` /books '' ) public class BookService { @ Inject private BookRepo bookRepo ; @ Context UriInfo uriInfo ; @ Consumes ( MediaType.APPLICATION_JSON ) @ Path ( `` / '' ) @ POST @ Produces ( MediaTyp... | Preventing 'PersistentObjectException ' |
Java | How come javac does n't emit error on this code ? Surely , compute ( 0 ) will throw NullPointerException . I would expect the java compiler to prevent this by doing some basic static code analysis , just like it would prevent | private static int compute ( int v ) { return v == 0 ? null : v ; } private static int compute ( int v ) { if ( v == 0 ) return null ; else return v ; } | Why does java allow NPE |
Java | I was looking at one of the open source project on github and I found following line of code in Java , here we know that 1 < < 11 is nothing but 2048 , so I can directly initialize array by giving its length = 2048 as follow , static byte [ ] byteArray = new byte [ 2048 ] ; then why it is written like 1 < < 11 instead ... | static byte [ ] byteArray = new byte [ 1 < < 11 ] ; | Concern regarding piece of code |
Java | It is necessary to describe the structure of this classtried the solution : Byte-buddy : generate classes with cyclic typesbut it will lead to an errorjava.lang.ExceptionInInitializerError Caused by : java.lang.IllegalStateException : Can not resolve declared type of alatent type description : ... | class A { private List < A > listA ; } | Byte Buddy - how can make a field self type ? |
Java | i want to use ids value in other class that inherit from this classi tried to make a get method so the code will bebut i 'm getting errors Exception in thread `` AWT-EventQueue-0 '' java.lang.Error : Unresolved compilation problems : Syntax error on token ( s ) , misplaced construct ( s ) Syntax error , insert `` ; '' ... | if ( title.equals ( `` *** '' ) ) { String ids = driver.findElement ( By.name ( `` Idsession '' ) ) .getAttribute ( `` value '' ) ; } if ( title.equals ( `` *** '' ) ) { String ids = driver.findElement ( By.name ( `` Idsession '' ) ) .getAttribute ( `` value '' ) ; public String getID ( ) { return ids ; } } import java... | How i can make get method in if statment without errors |
Java | I have the following model to make controllers in my application . Obviously , the full model is more complex but I will focus on the only part that is causing me problems : Now I would like to extend the Parent object and have a controller for the son , it would look like this : The problem is that the method getType ... | public abstract AbstractController < T > { abstract protected Class < T > getType ( ) ; } public ParentController extends AbstractController < Parent > { @ Override protected Class < Parent > getType ( ) { return Parent.class ; } } public SonController extends ParentController { @ Override protected Class < Son > getTy... | Limitation extending generics in java , any way to get around it ? |
Java | I 'm working with someone 's Java code where a key data structure is a m x n x p array , float [ ] [ ] [ ] . I need to get it into Python ; currently my approach is to save the array to a text file using Arrays.deepToString and then parse that text file from Python.I am stuck on how to write a regular expression that w... | float_pat = r'\d\.\d* ( ? : E-\d+ ) ? ' list_of_floats_pat = r'\ [ ( ? : \d\.\d* ( ? : E-\d+ ) ? ) , ) +\ ] ' [ [ [ 0.6453525160688715 , 0.15620941152962334 , 0.1874313118193626 , 9.991008092716556E-5 , 9.991008092716556E-5 , 9.991008092716556E-5 , 9.991008092716556E-5 , 0.01050721017750691 , 9.991008092716556E-5 ] , [... | Use Python regex to parse string of floats output by Java Arrays.deepToString |
Java | Sorry for the title gore , I did not know how to describe the problem in one line . If you have suggestions , I 'm open.Suppose you have the following class : Why is the memberRunnable able to access itself from inside run ( ) , while varRunnable is not ? AFAICS it 's the exact same construct.You can obviously use this... | public class SomeClass { // does n't even need to be final , which is freaky Runnable memberRunnable = new Runnable ( ) { public void run ( ) { SomeOtherClass.someMethod ( memberRunnable ) ; // this works } } public void someMethod ( ) { final Runnable varRunnable = new Runnable ( ) { public void run ( ) { SomeOtherCla... | Why does referencing an anonymous inner class by its name work when it 's a member , but not a variable ? |
Java | I know that specifying an additional bound when the first bound is a type parameter is not possible in Java ; however , I was wondering if anybody knows an alternate way to do something similar and to keep it safe at compile time ? I 've provided an example below.In the following code what I 'm referring to is this : <... | public class ExampleClass < T , U > { [ ... ] public < E extends T & Comparable < T > > ExampleClass ( Function < U , E > function ) { this.function = function ; this.comparator = ( E a , E b ) - > a.compareTo ( b ) ; } public ExampleClass ( Function < U , T > function , Comparator < U > comparator ) { this.function = ... | Is there an alternate way to specify an additional bound when first bound is a type parameter ? |
Java | ... how can I restrict an implementation of A to use a certain implementation of B in the method signature ? Use CaseHere is a Unit interface and two enums that implement it : Which is used by the Property interface : Here I want to be able to enforce that : Force uses only ForceUnit in the setUnit signatureMass uses o... | public interface Unit { ... } public enum ForceUnit implements Unit { ... } public enum MassUnit implements Unit { ... } public interface Property { public void setUnit ( Unit unit ) ; // for example } public class Force implements Property { ... } public class Mass implements Property { ... } | When Interface A defines Interface B in its method signature |
Java | How can I typecast an object inside the nested list 's Object - : As the code mentioned above , Following is the descriptions- : List < expenseLineItemList > is the master List for which I am invoking the stream API , then I am streaming on the List < Controls > .Now , the data getObject ( ) in the Controls class is th... | C c = GenericScreenDataBean fieldObjx = this.expenseLineItemList.stream ( ) .flatMap ( a - > a.getSectionModel ( ) .getControls ( ) .stream ( ) ) .filter ( b - > b.getData ( ) instanceof GenericScreenDataBean ) .map ( GenericScreenDataBean.class : :cast ) .filter ( c- > c.getFieldKey ( ) .equals ( `` IncurredAmount '' ... | How to typecast an object in the java Stream API ? |
Java | This might be a dumb question but I 'm teaching myself from a book and I noticed that a lot of examples have the print statement inside a method other than main . I was wondering if it makes a difference where you put it so I pasted the program I was working on when the question occurred to me . Would it be more effici... | private static Scanner in ; private static double s ; private static double a ; public static void main ( String [ ] args ) { in = new Scanner ( System.in ) ; DecimalFormat two = new DecimalFormat ( `` # . # # '' ) ; System.out.println ( `` Enter the length from center to vertex : `` ) ; double r = in.nextDouble ( ) ; ... | Is it more efficient to have a print statement in a method besides main or does it matter ? |
Java | The assignments of one , two and three may be reordered , as long as they all happen before the volatile write . Similarly , the x , y , and z statements may be reordered as the volatile write happens before all of them . The volatile operation is often called a memory barrier . The happens before guarantee ensures tha... | public class ReOrdering implements Runnable { int one , two , three , four , five , six ; volatile int volaTile ; @ Override public void run ( ) { one = 1 ; two = 2 ; three = 3 ; volaTile = 92 ; int x = four ; int y = five ; int z = six ; } } public class Reordering { private int x ; private volatile int y ; public voi... | About reordering : Why this code throws RuntimeException despite using the volatile ? |
Java | Sometimes , I encounter situations where all I need to test is whether the program 's execution reaches a certain point without any exceptions being thrown or the program being interrupted or getting caught in an infinite loop or something . What I do n't understand is how to write a unit test for that . For instance ,... | @ Testpublic void testProgramExecution ( ) { Program program = new Program ( ) ; program.executeStep1 ( ) ; program.executeStep2 ( ) ; program.executeStep3 ( ) ; // if execution reaches this point , that means the program ran successfully . // But what is the best practice ? // If I leave it like this , the test will `... | How to write a unit test in situations where it is obvious by `` looking '' that the test passed ? |
Java | I have this simple code in Java 8 : and I was pretty much expecting to see very large numbers getting printed . All I see in the console is : I said maybe I am not able to see others for whatever reason and modified the code as below : and now nothing gets printed.What am I missing here ? | class ThreadTest { void threadTest ( ) { new Thread ( this : :threadTest ) .start ( ) ; System.out.println ( Thread.activeCount ( ) ) ; } public static void main ( String [ ] args ) { new ThreadTest ( ) .threadTest ( ) ; } } 444444444 class ThreadTest { void threadTest ( ) { new Thread ( this : :threadTest ) .start ( )... | Why is this my attempt of spawning endless Threads stopping at 4 ? |
Java | I need help making a mirrored triangle like this : I can get each one seperatly , but I ca n't combine them . | * *** ***** *********** public static void main ( String [ ] args ) { for ( int i = 1 ; i < = 5 ; i++ ) { for ( int j = 0 ; j < i ; j++ ) { System.out.print ( `` * '' ) ; } System.out.println ( ) ; } for ( int i = 0 ; i < 6 ; i++ ) { for ( int j = 5 ; j > 0 ; j -- ) { if ( i < j ) System.out.print ( `` `` ) ; else Syst... | Creating a double mirrored triangle |
Java | As i know its better practice to have as less code duplication as possible , So i decided to declare only one scanner throughout the class , but where shall I close the scanner object or is it not necessarily to close it , what does closing the scanner do . | private Scanner scanner ; /** * Constructor for objects of class Scanner */public Ssss ( ) { // initialise instance variables scanner = new Scanner ( System.in ) ; } public void enterYourName ( ) { System.out.println ( `` Enter your Name '' ) ; String name = scanner.nextLine ( ) ; System.out.println ( `` Your name is :... | where to close the scanner used more then once in the class |
Java | I have the following code : A class that models the mapping between a ValueContainer < P > and an Entity E. ( Eg . a checkbox ( ValueContainer ) and something that has a Boolean value ) : An interface ValueContainer < P > : A custom Checkbox : And some code that unexpectedly does n't work : The code does not compile . ... | public abstract class ObjValContainerMapper < E , P > { private ValueContainer < P > provider ; public ObjValContainerMapper ( ValueContainer < P > provider ) { this.provider = provider ; } public abstract P getValue ( E entity ) ; public abstract void setValue ( E entity , P value ) ; ... } public interface ValueConta... | Java Generics Unexpected Behaviour for Constructor < X , Y > ( C < Y > ) and Interface C < Y > |
Java | I found this Java code from this site . I do n't understand how it compiles without ambiguous error.Output : | package swain.test ; public class Test { public static void JavaTest ( Object obj ) { System.out.println ( `` Object '' ) ; } public static void JavaTest ( String arg ) { System.out.println ( `` String '' ) ; } public static void main ( String [ ] args ) { JavaTest ( null ) ; } } String | Why can null be passed to an overloaded Java method ? |
Java | In the source code of java.util.Collection there is function called shuffle : The comment in the code says , `` instead of using a raw type here , it 's possible to capture the wildcard but it will require a call to a supplementary private method . `` What does that mean ? How could this be written without raw types ? | @ SuppressWarnings ( { `` rawtypes '' , `` unchecked '' } ) public static void shuffle ( List < ? > list , Random rnd ) { int size = list.size ( ) ; if ( size < SHUFFLE_THRESHOLD || list instanceof RandomAccess ) { for ( int i=size ; i > 1 ; i -- ) swap ( list , i-1 , rnd.nextInt ( i ) ) ; } else { Object arr [ ] = lis... | How would a `` supplementary private method '' help avoid raw types ? |
Java | I 've called this method multiple times in many places : now I want to add toUpperCase ability to this method without creating another method and I need the caller to determine which one to go with using a boolean as an arguement.in this case I 've to add a true/false parameter to every call I 've made.but when I use v... | private String changeFirstCharCase ( String word ) { return Character.toLowerCase ( word.charAt ( 0 ) ) + word.substring ( 1 ) ; } private static String changeFirstCharCase ( String word , boolean toUpperCase ) { return toUpperCase ? Character.toUpperCase ( word.charAt ( 0 ) ) + word.substring ( 1 ) : Character.toLower... | Is this approach standard to use varags.length instead of booleans ? |
Java | We can do this in C # : To call : As you can see we declare T as in method signature and inside the method , it replaced with EmployeeModel in CallApi < T > and new TypeToken < T > and it will return EmployeeModel object as the result.In Java ( Android ) when I want to use this generic , I have : But it returns me a Li... | private T getData < T > ( Context context , String url , PostModel postModel ) throws ApiException , IOException , ConnectionException { Response response = new CallApi < T > ( Connection.getApiUrl ( context ) ) .Post ( url , postModel ) ; if ( response.code ( ) ! = 200 ) throw new ApiException ( context , response ) ;... | How use generic T inside a method in java ? |
Java | I am reading Java Concurrency in Practice and encounter the following code snippet.timedRun method is used to run task r within a time range . This feature can be implemented by taskThread.join ( unit.toMillis ( timeout ) ) ; . So , why do we need scheduled taskThread.interrupt ( ) ; ? | public static void timedRun ( final Runnable r , long timeout , TimeUnit unit ) throws InterruptedException { class RethrowableTask implements Runnable { private volatile Throwable t ; public void run ( ) { try { r.run ( ) ; } catch ( Throwable t ) { this.t = t ; } } void rethrow ( ) { if ( t ! = null ) throw launderTh... | Java Concurrency in Practice “ Listing 7.9 . Interrupting a task in a dedicated thread. ” . What is the purpose of scheduled taskThread.interrupt ( ) ? |
Java | In my javafx program is a popup which lets user press keys and then it sets label accordingly . My problem is with key combinations that are shortcuts for underlying OS for example if user presses Win+R then Run.exe starts but my program should just set the label to `` Win+R '' . My question is how to stop keyevents fr... | public void showInput ( ) { Set codes = new HashSet ( ) ; Stage inputWindow = new Stage ( ) ; GridPane pane = new GridPane ( ) ; Scene scene = new Scene ( pane ) ; Label label = new Label ( `` Here comes the pressed keys '' ) ; scene.setOnKeyPressed ( e - > { e.consume ( ) ; int code = e.getCode ( ) .ordinal ( ) ; if (... | Stop Win+R from opening run tool |
Java | I have my code for `` Find the missing integer '' in CodilityThis code works for all except Performance tests - large_1.It gives me an error `` got 233 expected 40000 '' .When i replace this code : withorthen there are no errors . ( I got 100/100 score when i replace that line ) Is there anyone who can give some explan... | public static int solution ( int [ ] A ) { ArrayList < Integer > a = new ArrayList < Integer > ( ) ; for ( int i=0 ; i < A.length ; i++ ) if ( A [ i ] > = 0 ) a.add ( A [ i ] ) ; if ( a.isEmpty ( ) ) { return 1 ; } a.sort ( null ) ; if ( a.get ( 0 ) > 1 ) { return 1 ; } for ( int i=0 ; i < a.size ( ) -1 ; i++ ) { if ( ... | What is the difference between code examples ? |
Java | I just started learning Java Streams , and I have a question . Something that confuses me a lot is the following : I just checked out the AutoCloseable interface and it holds the close ( ) method.The BaseStream interface extends the AutoCloseable interface , and the rule of inheritance supplies , meaning that the close... | List < String > stringList = new ArrayList < > ( ) ; Stream < String > stringStream = stringList.stream ( ) ; stringStream.close ( ) ; | How can a close ( ) method invoked from Stream point to the implementation of the close ( ) method in the AbstractPipeline abstract class ? |
Java | I am currently working on a small for-loop pattern and I stumbled upon a road block in my project . Basically , what I want is to make a for loop pattern from my .java file that reads the source char by char and replace the asterisks in my current for-loop pattern : Into something like thisHere 's the current code that... | for ( i = 1 ; i < = 5 ; ++i , z = 0 ) { // first line for ( int space = 1 ; space < = segments - i ; ++space ) { System.out.print ( `` `` ) ; } while ( z ! = 2 * i - 1 ) { System.out.print ( `` * `` ) ; z++ ; } System.out.println ( ) ; } for ( i = 1 ; i < = 10 ; ++i , z = 0 ) { // second line for ( int space = 1 ; spac... | Reading a File character by character then putting them into a for loop pattern in java |
Java | My question is : Why does this piece of code correctly set the constructor parameter property port : As of my understanding , @ Value ( `` $ { cache.port } '' ) is resolved by a BeanPostProcessor called AutowiredAnnotationBeanPostProcessor . Spring bean lifecycle works in a way that the constructor method is called bef... | private final RedisServer redisServer ; public RedisTestConfiguration ( @ Value ( `` $ { cache.port } '' ) final int port ) { this.redisServer = new RedisServer ( port ) ; } | Why does @ Value as parameter of constructor fill the property correctly ? |
Java | wrote java8 program with lambda expression , its not getting executed instead its getting terminated at the lambda expression , no exceptions expected is it will print the string in list | import java.util.ArrayList ; import java.util.List ; import java.util.function.BiConsumer ; public class BiConsumerTest { public static void main ( String [ ] args ) { try { List < String > list1 = new ArrayList < String > ( ) ; list1.add ( `` A '' ) ; list1.add ( `` B '' ) ; list1.add ( `` V '' ) ; List < String > lis... | Lambda Expression is not working , getting terminated |
Java | I am not sure how to word the title of this question in a concise way . There are a few related questions I have found , for instance this one , but none of them seem to answer the question I have explicitly.But essentially what I am asking is this : Consider the following codeAs is , this code does not compile . The c... | static < A , B > Class < ? extends A > getLeftClass ( Pair < A , B > tuple ) { A left = tuple.getLeft ( ) ; return left.getClass ( ) ; } static < A , B > Class < ? extends A > getLeftClass ( Pair < A , B > tuple ) { A left = tuple.getLeft ( ) ; return ( Class < ? extends A > ) left.getClass ( ) ; } | Is casting the class returned by getClass ( ) of a generic instance type always safe in Java ? |
Java | I have java POJO User which contains firstName of the user . There is a map which contains the list of users mapped against the school name . Something like the belowAs mentioned above in the toString ( ) method , I wanted to print the list school name and the number of students in the school . How can I do that in Jav... | class User { String name ; } class UserMap { Map < String , List < User > userMapOfSchool ; public String toString ( ) { //return `` schoolName has noOfStudents '' for each key in the map } } | Printing the size of list items in map for each key |
Java | Call A : Call B : If this were in a for loop and being called many times over and over would there be a performance loss for calling an object within an object or is it worth noting about ? | double Value = Object.Object.Object.Object.DoubleValue ; double Value : Object.DoubleValue ; | Is there a performance implication of calling multiple objects in a row ? |
Java | Given the following two class definitions : And the following type declaration : Intuitively it feels the declared type a should be valid , but this is not the way JDK-8u45 behaves . Instead we get something like the following output : ( Edit : I was being a dingus here , this part has been answered : C2 < ? > does not... | class C1 < T extends C1 < T > > { } class C2 < U > extends C1 < C2 < U > > { } C1 < C2 < ? > > a ; Test.java:3 : error : type argument C2 < ? > is not within bounds of type-variable T C1 < C2 < ? > > a ; ^ where T is a type-variable : T extends C1 < T > declared in class C11 error class C3 < T extends C3 < ? > > { } cl... | Parameterization Well Formedness and Capture Conversion in Java |
Java | I 've built a converter in android studio and the distance part ( activity ) is crashing every time when I press the convert button . The application says that specific activity has stopped working and the app goes back to the Main activity . It is not showing any errors in android studio and I think my problem may be ... | protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main4 ) ; spinnerFrom = ( Spinner ) findViewById ( R.id.spinner1 ) ; ArrayAdapter < CharSequence > adapterFrom = ArrayAdapter.createFromResource ( this , R.array.distance_array , android.R.... | Android converter application crashes on convert |
Java | I am trying to make two classes with each classes has an instantiation of another class , but havaing a java.lang.StackOverFlowError . The first class looks like belowAnd the other class looks like thisI made it like this because i need to use the methods from the class ReverseGPA to be used in class GPpredictor ( I ne... | public class ReverseGPA { GPpredictor gp_predictor = new GPpredictor ( ) ; //This is the line that causes error double CURRENT_CREDITS ; double FUTURE_CREDITS ; double CUM_GPA ; double DESIRED_GPA ; double NEW_GRADE_POINT ; int ROUNDED_GRADE_POINT ; double NEW_GPS ; } public class GPpredictor { ReverseGPA rev_gpa = new... | StackOverFlow Error on classes |
Java | The ProblemI 'm trying to create an application where an object class can implement some operations from the total pool of available operations . The end goal is to not have any code duplication and to abide by the laws of OOP as much as possible.In more detail , I 'm trying to make a search engine using Lucene . Lucen... | public abstract class Index { public Index ( String indexPath ) { // Constructor using the information provided by the subclass } public void phraseSearch ( ... ) { // Do the operation } public void termSearch ( ... ) { // Do the operation } public void categorySearch ( ... ) { // Do the operation } } public class Revi... | Is there a specific way to give a certain subclass some functions of the superclass ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.