lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | Can someone explain the behavior of o2 ? Is it due to compiler optimization ? Is it documented somewhere in the JLS ? The output produced is true [ UPDATE ] After some productive and useful discussion I think I can understand the behavior ( please post comments if my assumption is wrong ) .First off , thanks to @ user2... | public class Test { public static void main ( String [ ] args ) { Object o1 = new Object ( ) { String getSomething ( ) { return `` AAA '' ; } } ; // o1.getSomething ( ) ; // FAILS String methods1 = Arrays.toString ( o1.getClass ( ) .getMethods ( ) ) ; var o2 = new Object ( ) { String getSomething ( ) { return `` AAA ''... | Why do Object and var variables behave differently ? |
Java | Let 's say I have the following code : How can I reference getIterable of the outer class from the inner class with the same name ? MyStream.this should point to the inner class here , right ? How to show an outer class with the same name ? | abstract class MyStream { public abstract Iterable < Integer > getIterable ( ) ; public MyStream append ( final int i ) { return new MyStream ( ) { @ Override public Iterable < Integer > getIterable ( ) { return cons ( /*outer class's*/getIterable ( ) , i ) ; } } ; } public static Iterable < Integer > cons ( Iterable <... | How to make ` this ` point to the outer class where the inner class has the same method name |
Java | I am having an issue initializing a class with type parameter . It seems to be a shortcoming of Java 's type inference and I would like to know if there 's a way around this or a better way of achieving this.Compile-time error is in BusinessLogic : :someLogic ( ) : The constructor Service < ChildModel , ArrayList < Chi... | public class ParentModel { } public class ChildModel extends ParentModel { } public class Service < E extends ParentModel , T extends Collection < E > > { private Class < T > classOfT ; private Class < E > classOfE ; public Service ( Class < E > classOfE , Class < T > classOfT ) { this.classOfE = classOfE ; this.classO... | Java - issue initializing class with type parameters |
Java | I have a program that runs simultaneously and I have this problem where I want to stop the thread but the for loop/while loop does n't get cancelled once I once I click enterIf I take the for loop out of the while loop , the program actually responds to the enter and shuts down.Why does the for loop cause the program t... | class MyNumber extends Thread { private volatile boolean processing = true ; public void run ( ) { while ( processing ) { // Once I take this for loop out ( put // beside it like right now ) , the enter key to stop the program then does work . //for ( int i = 1 ; i < 27 ; i++ ) { System.out.println ( `` Letter `` + `` ... | For and While Loop |
Java | Is it possible to write a regex pattern in Java that will match , for example , 2 out of 3 ( or 3 out of 4 etc ) groups ? For example , I have the following regex : which will only allow patterns that match all three groups - i.e . it must contain a number AND a lowercase character AND an uppercase character . I 'd lik... | ( ( ? =.*\d ) ( ? =.* [ a-z ] ) ( ? = . * [ A-Z ] ) ) | Match x out of y groups in Java regex |
Java | I was under the assumption that when eclipse suggests methods , it 's in the formAnd it seems to be true for all the methods ( but clone ( ) ) in the posted picture also.But for clone ( ) , eclipse says the method comes from the type of the array ( byte in this case ) .It 's the same for all arrays of primitive types a... | < methodName > ( < any parameters > ) : < retunType > - < actual class the method will be invoked from > | Eclipse reporting an array 's clone ( ) method is from it 's corresponding type ( including primitives ) ? |
Java | Deadlock with 2 Threads ? Thanks for the answers ! | public void function ( object a , object b ) { synchronized ( a ) { synchronized ( b ) { a.performAction ( b ) ; b.performAction ( a ) ; } } } | Is a deadlock possible in this method ? How can I prevent it ? |
Java | I was wondering if there is any clojure code or macros that does not work when embedded within a clojure proxy for java code , eg : Or , can I only embed calls to Java functions within the proxy ? | ( proxy [ Some Java Interface ] [ ] ( some Java Method [ args ] ... Clojure code ... ) ) | Does all clojure code work within a java proxy ? |
Java | Heavy CPU bound task could block the thread and delay other tasks waiting execution . That 's because JVM ca n't interrupt running thread and require help from programmer and manual interruption.So writing CPU bound tasks in Java/Kotlin requires manual intervention to make things run smoothly , like using Sequence in K... | fun simple ( ) : Sequence < Int > = sequence { // sequence builder for ( i in 1..3 ) { Thread.sleep ( 100 ) // pretend we are computing it yield ( i ) // yield next value } } fun main ( ) { simple ( ) .forEach { value - > println ( value ) } } | Why Kotlin/Java does n't have an option for preemptive scheduler ? |
Java | If I create a static block and create an Object there , say of some other class , will the object be created on the heap or on the stack ? | class Hello { static { Abc abcObject=new Abc ( ) ; } // Other Code ... } | Where in memory are objects located when they are created within a static block ? |
Java | I have a modified version of ItemRequestForm.java that previously worked in version 5x . In item-view.xsl , I created a link that when clicked , will redirect the user to this modified form . The URL pattern of this link is http : //example.com/documentdelivery/123456789/1234 . When I upgrade my DSpace version to 6x , ... | String handle=parameters.getParameter ( `` handle '' , '' unknown '' ) ; DSpaceObject dso = HandleManager.resolveToObject ( context , handle ) ; if ( ! ( dso instanceof Item ) ) { return ; } Request request = ObjectModelHelper.getRequest ( objectModel ) ; boolean firstVisit=Boolean.valueOf ( request.getParameter ( `` f... | Getting a modified version of ItemRequestForm.java to work in DSpace version 6x |
Java | I 'd like to know what the first < T > represents in the following line of Java code . I 've read several tutorials on generics but none of the examples have 2 generics before the method name . Thanks . | public < T > Provider < T > scope ( Key < T > key , Provider < T > unscoped ) ; | What 's the meaning of this usage of Java generics ? |
Java | I am using Java to insert data into mongodb cluster.Can I have more than 1 mongos instance so that I have a backup when 1 of my mongos is down ? Here is my java code to connect to mongos.How can I specify my second mongos instance in my Java code ? ( If possible ) .Thanks in advance . | MongoClient mongoClient = new MongoClient ( `` 10.4.0.121 '' ,6001 ) ; DB db = mongoClient.getDB ( `` qbClientDB '' ) ; DBCollection collection = db.getCollection ( `` clientInfo '' ) ; | Can I have more than 1 'mongos ' instance ? |
Java | This question has bogged me quite a while . During programming there is regularly the question whether there is something in an object or not . For this reason was the isEmpty method invented . Great , but in practice we use it like ! isEmpty almost all the time.As a consequence , notEmpty would be a much more apprecia... | ! metadata.isEmpty ( ) == metadata.notEmpty ( ) | Why is there always isEmpty whereas I use ! isEmpty 99 % of the time |
Java | Create a third array list by summing up data related to same element if present in both lists , else insert the new dataI created two maps from the two array lists with Id as key and then created a set by combining keys from both maps . Making use of the values in set , i queried both the lists and arrived at the sum .... | public class Stock { private int stockCode ; private int stockQuantity ; private int stockValue ; public int getStockCode ( ) { return stockCode ; } public int getStockQuantity ( ) { return stockQuantity ; } public int getStockValue ( ) { return stockValue ; } public Stock ( int stockCode , int stockQuantity , int stoc... | Sum values in two arrays lists and return a third list |
Java | The following code is from the book `` Cracking the coding interview '' . The code prints all permutations of a string.Question : What is the time complexity of the code below.My Understanding : I am able to derive the time complexity to : n * n ! .I am sure I am missing the time complexity of the blue , green and yell... | void permutation ( String str ) { permutation ( str , `` '' ) ; } private void permutation ( String str , String prefix ) { if ( str.length ( ) == 0 ) { System.out.println ( prefix ) ; } else { for ( int i = 0 ; i < str.length ( ) ; i++ ) { String rem = str.substring ( 0 , i ) + str.substring ( i + 1 ) ; permutation ( ... | Time complexity : Getting incorrect result |
Java | My colleague just asked me a really interesting question and I can not give him an answer.Let 's assume that we have got the following class : Now , we are creating the objects : The question was : Do we keep information about the available methods in each single object ? If we create a new object p9 , will the JVM cre... | public class Person { String name ; public Person ( String name ) { this.name = name ; } public void print ( ) { System.out.println ( `` xxx '' ) ; } } Person p1 = new Person ( `` a '' ) ; Person p2 = new Person ( `` b '' ) ; Person p3 = new Person ( `` c '' ) ; Person p4 = new Person ( `` d '' ) ; Person p5 = new Pers... | Where is information about methods of Java objects kept ? |
Java | In Java , how expensive is to do a cast : versus : assuming `` int i = N '' preceding it.EDIT : Disregard my direct comparison with ( i++ ) for a second , if you would please . Let me rephrase this in more general terms : how expensive is casting in general ? Choose your reference operation better than my naive `` i++ ... | ( MyObject ) IObject ; i++ ; | How expensive is it to perform a cast operation Vs i++ ? |
Java | So I 've some sample code I 'm playing with to try and figure out this logic below . It 's just one large main method and two POJOs , but it 'll run . I 'm debugging to get values at the point of termination.POJO1 : POJO2 : As you can see , I 'm streaming and filtering out any objs that do n't match on carId . My next ... | public class Main { public static void main ( String [ ] args ) { obj1 obj1 = new obj1 ( ) ; obj1 obj12 = new obj1 ( ) ; obj2 obj2 = new obj2 ( ) ; obj2 obj22 = new obj2 ( ) ; obj1.id = 123L ; obj1.carId = 1234L ; obj12.id = 123L ; obj12.carId = 1234L ; obj2.carId = 1234L ; obj22.carId = 12345L ; ArrayList < obj1 > obj... | filter and set ( ) in one stream |
Java | I just updated to IntelliJ 2020.2 and while some things are good some thing are bad..When using the Java var feature IntelliJ now shows the type of it right next to the variable name which is completely useless to me and the only reason one uses var at all , because the type is already obvious.Displays in IntelliJ 2020... | var a = `` hello world '' .split ( `` `` ) ; var a ( : String [ ] ) = `` hello world '' .split ( `` `` ) ; | Hide `` var '' type preview in new IntelliJ 2020.2 |
Java | Currently , I am struggling with the problem of catching numbers with REGEX by using Java The string which I am trying to catch the numbers in this string value using REGEX is this..My wish is to catch the numbers which are located in [ ] . Would this be possible with Java ? I could easily take the number by splitting ... | [ TEST ] [ 64894 ] HelloWorld [ KGMObilians ] | Use Regular Expression to extract numbers in brackets |
Java | I 've taken this code from the book `` Introduction to Programming with Java '' by Sedgewick on their online website . I just have a question as to whether a or b could possibly be above 6 if by chance Math.random ( ) is 1.0 ? Or am I wrong on this ? 1.0 * 6 + 1 = 7 ? | public class SumOfTwoDice { public static void main ( String [ ] args ) { int SIDES = 6 ; int a = 1 + ( int ) ( Math.random ( ) * SIDES ) ; int b = 1 + ( int ) ( Math.random ( ) * SIDES ) ; int sum = a + b ; System.out.println ( sum ) ; } } | Java Sum Of Two Dice - Will This Code Give Above A 6 ? |
Java | I am trying to understand the string constant pool , how string literal objects are managed in constant pool , i am not able to understand why I am getting false from below code where s2 == s4 | public static void main ( String [ ] args ) { String s1 = `` abc '' ; String s2 = `` abcd '' ; String s3 = `` abc '' + '' d '' ; String s4 = s1 + `` d '' ; System.out.println ( s2 == s3 ) ; // OP : true System.out.println ( s2 == s4 ) ; // OP : false } | How string literals are created ? |
Java | In my program , I want the user to : pick/open a database ( like Access ) on their ownpick a table from the databaseselect column ( s ) from the tableIn my code , I have a class that does something like this : And this results to a very big block of code . Is there a cleaner , simpler way to do this ? | mntmOpenDatabase.addActionListener ( new ActionListener ( ) { public void actionPerformed ( ActionEvent e ) { //open the database //display tables as buttons tableButton.addActionListener ( new ActionListener ( ) { // select a table public void actionPerformed ( ActionEvent e ) { //display the columns of the table sele... | How to avoid nested ActionListeners ? |
Java | I am new to Java and am currently writing a program that takes use-entered arguments for delimiters of a text file containing sentences , and then determines the number of sentences within that text file based on the provided delimiters . When running my Main.java I want the user to be able to do the following ( where ... | if ( word.endsWith ( `` . '' ) || word.endsWith ( `` ! '' ) || word.endsWith ( `` ? '' ) ) { sentenceCount++ } if ( word.endsWith ( delimitersStringorArray.contains ( ) ) { sentenceCount++ } | Java - If word ends with user-entered delimiters , then do x |
Java | I 've tried the following source code on my laptop ( Oracle HotSpot JVM , JDK 1.8 , 64 bits ) : Then I decompiled the source code in IntelliJ IDEA Community 2019.1 to get following content : And I 've got answers : I already know that integer assignment from a primitive number to the corresponding reference number will... | Long l ; Long l1 = 100L ; Long l2 = 100L ; System.out.println ( Long.valueOf ( 100L ) == Long.valueOf ( 100L ) ) ; System.out.println ( ( l = 100L ) == Long.valueOf ( 100L ) ) ; System.out.println ( l1 == l2 ) ; System.out.println ( Long.valueOf ( 128L ) == Long.valueOf ( 128L ) ) ; System.out.println ( Long.valueOf ( ... | How does Java handle a long comparison between a primitive number and a reference number ? |
Java | I have two interfaces in Java ( version 8 ) which are very similar.I can not change the interfaces and can not change the classes which implement them.Now I have a function that its implementation fits both interfaces ( almost ) .I want it to do something like that : I do n't want to use inspection because this functio... | public interface A { int get ( ) ; } public interface B { int get ( ) ; int somethingelse ( ) ; } public int foo ( ( A | B ) p ) { int ret = 0 ; if ( p instanceof B ) { ret = p.somthingelse ( ) ; } return ret + p.get ( ) ; } | Can a Java function 's parameter require optional interfaces ? |
Java | Can someone explain why setting x to 150_000 or 4_000_000 or even 2_000_000_000 does n't change execution time of this loop ? | public class Test { public static void main ( String [ ] args ) { int x = 150_000 ; long start = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < x ; i++ ) { f1 ( i ) ; } long end = System.currentTimeMillis ( ) ; System.out.println ( ( end - start ) / 1000.0 ) ; } private static long f1 ( int n ) { long x = 1 ; for... | Why is my for loop execution time not changing ? |
Java | I understand that the main purpose of labels is to use them with break and continue to alter the usual behaviour of the loop . But it 's possible to label every statement that is not a declaration.Is there any purpose to labels like LABEL1 since it 's not allowed to break LABEL1 ? | int j = 0 ; LABEL1 : j++ ; LABEL2 : for ( int i = 0 ; i < 4 ; i++ ) { if ( i == 3 ) break LABEL2 ; } | Why is it allowed to label almost every statement in Java ? |
Java | I am looking for simple way to connect information about requirement/release and source code.The case is that developer should be able to find any artifacts created given release or CR in easy way.The idea I have is to introduce some new annotation to mark any new class ( I am not sure if it is good for any new method ... | @ ArtifactInfo ( release= '' 1.2 '' cr= '' cr123 '' ) | Connection between requirements and code in code |
Java | Benchmarks are run under intel core i5 , UbuntuI 'm comparing performance of Collectors.counting and Collectors.summingLong ( x - > 1L ) . Here is the benchmark : I got the result that Collectors.counting 3 times slower Collectors.summingLong.So I ran it with -prof perfnorm with 25 forks . Here is the result : What I n... | java version `` 1.8.0_144 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_144-b01 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.144-b01 , mixed mode ) public List < Integer > ints = new ArrayList < > ( ) ; Collector < Integer , ? , Long > counting = Collectors.counting ( ) ; Collector < Integer , ? , Long > sum... | Comparing performance of Collectors.summingLong and Collectors.counting |
Java | I have a network associated storage where around 5 million txt files are there related to around 3 million transactions . Size of the total data is around 3.5 TB . I have to search in that location to find if the transaction related file is available or not and have to make two separate reports as CSV file of `` availa... | File searchFile ( File location , String fileName ) { if ( location.isDirectory ( ) ) { File [ ] arr = location.listFiles ( ) ; for ( File f : arr ) { File found = searchFile ( f , fileName ) ; if ( found ! = null ) return found ; } } else { if ( location.getName ( ) .equals ( fileName ) ) { return location ; } } retur... | Performance optimization searching data in file system |
Java | The question pretty much states what i 'm asking for.I have an algorithm and I was wandering what is the better approach to achieve ah 'Big-Oh ' running time - through a graph and plotting the number of input against the running time , or through asymptotic analysis ? For my graph I 'm currently using : What 's the dif... | private int startTime = System.currentTimeMillis ( ) ; //At start of algorithmprivate int endTime = System.currentTimeMillis ( ) ; //At the end of algorithmint runningTime = endTime - startTime ; | Difference between graphs and asymptotic analysis to compare running times of an algorithm |
Java | I have the following classThat way I can detect any attempt to modify myAttr . Well , almost any . It does not work when someone modifies myAttr using Field.set ( ) method . How can I trap Java reflection usage ? | public class MyClass { private int myAttr ; public void setAttr ( int a ) { myAttr = a ; Thread.dumpStack ( ) ; } } | How to detect when an attribute is modified by calling reflection methods |
Java | I have been making a hangman game to teach myself Java . I 've got in the main body of the frame.I 've got : And I 'm using : ... throughout the project each time the frame is updated , new letter guessed , incorrect guess , new game.When the application first runs JOptionPane.showMessageDialog ( null , `` Repainting '... | this.add ( new PaintSurface ( ) , BorderLayout.CENTER ) ; private class PaintSurface extends JComponent { Shape found = null ; public PaintSurface ( ) { JOptionPane.showMessageDialog ( null , `` Repainting '' ) ; Shape s ; msgbox ( `` LL : `` + intLivesLost ) ; switch ( intLivesLost ) { //draw the Hanged man case 10 : ... | Java hangman game repaint ( ) not working |
Java | In Java this is the case : What I 'm wondering is this : Is the fact that x is limited to the scope of the if-statement just a feature of the Java compiler , or is x actually removed from the stack after the if-statement ? | public void method ( ) { if ( condition ) { Object x = ... . ; } System.out.println ( x ) ; // Error : x unavailable } | Are subcontexts in Java separate rows on the stack ? |
Java | The question is easy but I 'm not sure it 's possible to do it ... if we have a class like we can see that it 's just simply a class with a private member and a setter/getter.The interesting thing is , to allow method chaining , the setter is returning this.So we can do things like this : The problem here is when I try... | class A { private int foo ; public A ( int bar ) { this.foo = bar ; } public A setFoo ( int bar ) { this.foo = bar ; return this ; } public int getFoo ( ) { return this.foo ; } public void doSomething ( ) { this.foo++ ; } } A a = new A ( 0 ) ; a.setFoo ( 1 ) .doSomething ( ) ; class B extends A implements I { public B ... | How to extend a class that is returning this in their methods |
Java | I just stumbled over a phenomenon in my code which comes down to this : I have an OSGi Declarative Service providing two service interfaces configured as follows : In my code , I have two different threads which both open a ServiceTracker to get the service instance , but via different interfaces : So one thread uses I... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < scr : component xmlns : scr= '' http : //www.osgi.org/xmlns/scr/v1.1.0 '' activate= '' init '' deactivate= '' dispose '' enabled= '' true '' name= '' redacted.redactedstore '' > < implementation class= '' redacted.RedactedStore '' / > < service > < provide interfac... | OSGi Declarative Services in Eclipse , multiple service interfaces , and Thread Safety |
Java | The below Java code prints two arguments when I pass ! clear as input as shown below.Output : UPDATEUsing any linux command in place of clear produces the same result . I am aware that this has got something to do with history expansion in bash and I can escape the ! character to solve this issue . However , I am curio... | class Test { public static void main ( final String ... arguments ) { for ( String argument : arguments ) { System.out.println ( argument ) ; } } } $ java Test ! clearjava Test clearclear $ java Test ! pwdjava Test pwdpwd $ java Test ! lsjava Test lsls | Why does this Java code print two arguments ? |
Java | I have this piece of code : So basically , this is a time-out function and the time-out is refreshed by another condition . My issue is that the x > = RaftNode.limit condition keeps triggering even though it is false ( through the print statements ) .My console outputs : So x is indeed the current time , but even thoug... | void timerCountDown ( ) { while ( RaftNode.getTimeoutVar ( ) ) { long x = System.currentTimeMillis ( ) ; if ( x > = RaftNode.limit ) { System.out.println ( x ) ; System.out.println ( RaftNode.limit + `` THIS SHOULD BE LESS THAN '' ) ; System.out.println ( System.currentTimeMillis ( ) + `` THIS '' ) ; System.out.println... | Java 7 : IF condition triggered when false |
Java | If a class has two synchronized methods : Will invoking these two methods in one line cause a deadlock ? | public class A { public synchronized int do1 ( ) { ... } public synchronized void do2 ( int i ) { ... } } A a = new A ( ) ; a.do2 ( a.do1 ( ) ) ; | Will invoking two synchronized methods in one line cause a deadlock ? |
Java | I have the following model:1 RepositoryDTO can have many ResourceDTOs , and in each ResourceDTO is exacly one TeamDTO.So to get the TeamDTOs from the RepositoryDTO , I am doing the following : I 'm just wondering is there a better idiom for doing this , maybe using Google Guava ? | RepositoryDTO repoDTO = ... List < TeamDTO > teamsLinkedToRepo = getTeamsLinkedTo ( repoDTO ) ; private List < TeamDTO > getTeamsLinkedTo ( final RepositoryDTO repository ) { final List < TeamDTO > teamsLinkedToRepository = new ArrayList < TeamDTO > ( ) ; for ( final ResourceDTO resourceDTO : repository.getResources ( ... | Better idiom for listing inner items of a 1-to-N-to-1 relationship ? |
Java | In my program I need to track list of opened connections to some HTTP server - in order to disconnect them at once if needed.I faced the following problem . If I connect to HTTP server everything works perfect , but if to HTTPS , then connections are not removed from the list . It leads to memory leak.Example : If URL ... | package test ; import java.net.URL ; import java.net.URLConnection ; import java.util.ArrayList ; public class Main { public static void main ( String [ ] args ) { try { ArrayList < URLConnection > al = new ArrayList < URLConnection > ( ) ; URL url = new URL ( `` http : //www.example.com '' ) ; URLConnection conn = url... | Removing URLConnection object from ArrayList < URLConnection > |
Java | I was just exploring java reflection API and i encountered following code snippetOutput : I read the documentation of the set method which states that it sets value of the field for the given object . But i am not able to understand the output of the code because it should print 42 in all the cases.Can anyone please gi... | public class Main { public static void main ( String [ ] args ) throws IllegalAccessException , NoSuchFieldException { Field value=Integer.class.getDeclaredField ( `` value '' ) ; value.setAccessible ( true ) ; value.set ( 42 , 43 ) ; System.out.printf ( `` six times seven % d % n '' ,6*7 ) ; System.out.printf ( `` six... | Java Reflection Snippet output |
Java | User Detail model : I 've a ArrayList of user informationI 'm trying to iterate through the array and find out if there are any duplicate entries based on userName , from the above list I 've two records with same user name `` Robert '' , in this case I want to add up the userSalary and remove one record from the List.... | private String userName ; private int userSalary ; List < UserDetail > userDetails = new ArrayList < > ( ) ; UserDetail user1 = new UserDetail ( `` Robert '' , 100 ) ; UserDetail user2 = new UserDetail ( `` John '' , 100 ) ; UserDetail user3 = new UserDetail ( `` Robert '' , 55 ) ; userdetails.add ( user1 ) ; userdetai... | How do I add up and remove repeated objects from ArrayList ? |
Java | I have a library which parse URLs and extract some data . There is one class per URL . To know which class should handle the URL provided by the user , I have the code below . } The problem is users are requesting more URL to be parsed , which means my switch statement is growing . Every time someone comes up with a pa... | public class HostExtractorFactory { private HostExtractorFactory ( ) { } public static HostExtractor getHostExtractor ( URL url ) throws URLNotSupportedException { String host = url.getHost ( ) ; switch ( host ) { case HostExtractorABC.HOST_NAME : return HostExtractorAbc.getInstance ( ) ; case HostExtractorDEF.HOST_NAM... | Dynamically invoke the correct implementation in a factory |
Java | I have the following code , it is a toy code but makes possible to reproduce the problem : When I run this code over and over again , it will usually run without any exceptions and will print some number.. However from time time ( 1 out of 10 tries approximately ) I will get an exception akin to : I am pretty certain i... | import java.util . * ; import java.util.concurrent.ConcurrentHashMap ; import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; import java.util.concurrent.TimeUnit ; import java.util.stream.Collectors ; import static java.util.Arrays.stream ; import static java.util.stream.Collectors.toLis... | How does computeIfAbsent fail ConcurrentHashMap randomly ? |
Java | I have a JPanel which includes a JComboBox . I am trying to take a screenshot of this panel when JComboBox is open . But I could n't do it . Any idea ? If you run this code then press Alt-P when combo is open , you will see the problem . | public class ScreenShotDemo { /** * @ param args */ public static void main ( String [ ] args ) { final JPanel JMainPanel = new JPanel ( new BorderLayout ( ) ) ; JPanel jp = new JPanel ( ) ; jp.add ( new JComboBox < String > ( new String [ ] { `` Item1 '' , `` Item2 '' , `` Item3 '' } ) ) ; final JPanel jImage = new JP... | Screenshot of a panel with opened comboboxes |
Java | When following code is run it prints `` X.Q '' instead of `` A < T > .X.Q '' as required by the language specification . Can some one help me understand what will be the output of this program , as per my understanding it should be `` A < T > .X.Q '' instead of `` X.Q '' , Please correct me if i am mistaken some where | class A < T > { static class X { static class Q { public static void main ( ) { System.out.println ( `` A < T > .X.Q '' ) ; } } } } class B extends A < B.Y.Q > { static class Y extends X { } // X here is inherited from A } class X { static class Q { public static void main ( ) { System.out.println ( `` X.Q '' ) ; } } }... | Multilevel static nested class producing wrong output |
Java | In java , I can initialize an array with predefined content either by : Or by : Essentially , is there any difference between these two ways ? Are they completely identical in Java ? Which way is better and why ? | int [ ] myArr = new int [ ] { 1,2,3 } ; int [ ] myArr = { 1,2,3 } ; | difference between these 2 ways of initializing an simple array |
Java | I know this is n't a good question to ask and I might get cursed to ask it but I can not find any place to get help on this questionBelow is a Generic class that appeared in my interview question ( which I have already failed ) . The question was to tell what this Class declaration is doing and in what circumstances th... | public abstract class SimpleGenericClass < T extends SimpleGenericClass < ? > > { } | what could this generic class declaration could mean ? |
Java | I was messing around with stuff in my eclipse when , to my surprise , I found that this piece of code when run gets terminated without any error / exceptionwhile his piece of code keeps on executingEven though both ought to be infinite loops running for ever . Is there something I 'm missing as to why the first code sn... | public class Test { public static void main ( String [ ] args ) { for ( int i = 2 ; i > 0 ; i++ ) { int c = 0 ; } } } public class Test { public static void main ( String [ ] args ) { for ( int i = 2 ; i > 0 ; i++ ) { int c = 0 ; System.out.println ( c ) ; } } } | JAVA : Why does the following infinite loop terminate without any error / exception |
Java | Today I was making a Tetris clone in Java , and when time came to implement the block spawning mechanism , I wrote this switch statement that takes an enum . I 've been told to avoid switch statements when possible , but I 'm not sure if avoiding one here is possible unless I completely overhaul my original inheritance... | private void spawnBlock ( Type type ) { switch ( type ) { case I : currentBlock = new IBlock ( ) ; break ; case L : currentBlock = new LBlock ( ) ; break ; case J : currentBlock = new JBlock ( ) ; break ; case Z : currentBlock = new ZBlock ( ) ; break ; case S : currentBlock = new SBlock ( ) ; break ; case T : currentB... | Is a switch statement appropriate here , taking an enum ? |
Java | I try to save an entity with spring data mongodb repository . I have an EventListener that cascades saves.The problem is , that I need to save an entity to get its internal id and perform further state mutations and saving the entity afterwards.I have an index on a child collection of foo . It will not update children ... | @ Test void testUpdate ( ) { FooDto fooDto = getResource ( `` /json/foo.json '' , new TypeReference < FooDto > ( ) { } ) ; Foo foo = fooMapper.fromDTO ( fooDto ) ; foo = fooService.save ( foo ) ; log.info ( `` Saved foo : `` + foo ) ; foo.setState ( FooState.Bar ) ; foo = fooService.save ( foo ) ; log.info ( `` Updated... | spring data mongodb calling save twice leads to duplicate key exception |
Java | Using python 's ctypes , it 's possible to specify a pointer that takes a type : With JNR , it looks like this : However , is it possible to type the names field as a Pointer to a String ? | class METADATA ( Structure ) : _fields_ = [ ( `` classes '' , c_int ) , ( `` names '' , POINTER ( c_char_p ) ) ] public static class Metadata extends Struct { public Metadata ( jnr.ffi.Runtime rt ) { super ( rt ) ; } public final Struct.Unsigned32 classes = new Struct.Unsigned32 ( ) ; public final Struct.Pointer names ... | how to specify a JNR Pointer like that of python ctypes |
Java | If I add my lib to the project , and run command : why does com.github.kolyall : utils:1.0.4 lib get the com.android.support : appcompat-v7 lib ( and others ) with runtime scope in CompileClasspath ? If their scope is supposed to be runtime , why are they added to CompileClasspath ? Output is : Full output is : app.gra... | > gradlew -q app : dependencies -- configuration debugCompileClasspath > app_dependencies_compile.txt \ -- - com.github.kolyall : utils:1.0.4 + -- - net.danlew : android.joda:2.8.2 | \ -- - joda-time : joda-time:2.8.2 + -- - com.android.support : appcompat-v7:28.0.0-alpha3 - > 28.0.0 ( * ) + -- - com.android.support : ... | Why libs with runtime scope are added to debugCompileClasspath ? |
Java | I have seen this cod , why it works please ? It is compile in java , I think new is a reserved word | public void nеw ( ) { System.out.println ( `` ! ? `` ) ; } | Java reserved name compilation |
Java | I have this piece of code that I wanted to refactor to Java 8After refactoring this simple loop it seems like too much code ... am I using CompletableFutures correctly ? | List < String > menus = new ArrayList < String > ( ) ; for ( Menu menu : resto1.getMenu ( ) ) { MainIngredient mainIngredient = MainIngredient.getMainIngredient ( menu.getName ( ) ) ; if ( mainIngredient.getIngredient ( ) .indexOf ( `` Vegan '' ) ! =-1 ) { menus.add ( menu.getName ( ) ) ; } } ExecutorService executorSe... | CompletableFuture in Java8 |
Java | I am trying to write a program which should consume memory of a specific size . An issue I am wondering of is that I am getting outOfMemory exception when there is actually a free space in the heap.Here is the code : The command to start it : And the output : Well the difference between max memory and total memory is 7... | import java.util.Vector ; import java.lang . * ; public class MemoryEater1 { public static void main ( String [ ] args ) { try { long mb = Long.valueOf ( args [ 0 ] ) ; Vector v = new Vector ( ) ; Runtime rt = Runtime.getRuntime ( ) ; while ( true ) { if ( v.size ( ) > 0 ) { if ( ( ( long ) v.size ( ) ) *100 < mb ) { S... | Ca n't consume entire memory |
Java | I found the following code , which adds an item under certain circumstances ( if its not OLD ) to a list . This list get 's packed in a common controls list afterwards.I tried the following refactoring using java8 streams : The problem is the map method ... What can I do in the continue cases ? return null ? I could th... | List < ListDataContent > list = new ArrayList < > ( ) ; for ( KonditionValue kondition : konditions ) { if ( kondition.getStatusKz ( ) .equals ( StatusKz.OLD ) ) continue ; for ( TermKondValue tilg : kondition.getTermimKonditions ( ) ) { if ( tilg.getStatusKz ( ) .equals ( StatusKz.OLD ) ) continue ; TerminKondListCont... | Refactor creation of a list with java 8 streams |
Java | I am interested why boolean logical | is used here . Why not to use conditional short circuited || ? | public static long checkedAdd ( long a , long b ) { long result = a + b ; checkNoOverflow ( ( a ^ b ) < 0 | ( a ^ result ) > = 0 ) ; return result ; } | Strange implementation of Guava LongMath.checkedAdd |
Java | I need a Java stream operation to test if two sets have at least 3 common elements.Here is my Java 7 code that works fine : How can we do that with Java stream operations ? | @ Testpublic void testContainement ( ) { Set < Integer > setOne = IntStream.of ( 0,1,4,3 ) .boxed ( ) .collect ( Collectors.toCollection ( HashSet : :new ) ) ; Set < Integer > setTwo = IntStream.of ( 0,1,4,5 ) .boxed ( ) .collect ( Collectors.toCollection ( HashSet : :new ) ) ; Assertions.assertEquals ( true , testSets... | Test if two sets share 3 elements with Java streams |
Java | I use a Neo4J database with nearly 500k nodes . When I startup my Spring application and do the first query , it takes about 4-5 seconds . This happens just for the first query , so I thought I could do a warmup after spring is initialized to make all subsequent queries faster.This is my applicationContext.xml : I saw ... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < beans xmlns= '' http : //www.springframework.org/schema/beans '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xmlns : util= '' http : //www.springframework.org/schema/util '' xmlns : context= '' http : //www.springframework.org/schema/context '' x... | Warmup Neo4j database after spring initialization |
Java | I know it has to be a lot of effort to go through people 's code , especially mine since it 's so long and amateurish , so I did my best to comment out all my code to try to explain what I 'm thinking . The hangman game is pretty much refined , and I am just trying to have it print the blanks but with guessed letters f... | public class Hangman { public static void ttt ( String inputWord ) { //setting up the game and declaring the secret word to be the input int wordLength = inputWord.length ( ) ; //making new integer variable for length of word String blanks = `` '' ; //creating blanks string for ( int i = 0 ; i < wordLength ; i++ ) { //... | I 'm having trouble using a nested for-loop and a String replace function |
Java | I know arrays are faster at getting and setting , while LinkedLists are better at adding and removing elements , but what about when iterating ? A more `` traditional '' for ( i=0 ; i < intList.size ( ) ; i++ ) would definitely make LinkedLists slower since you 'd have to get the element at index i every time . But wha... | LinkedList < Integer > intList = new LinkedList ( ) ; /*populate list ... */for ( int i : intList ) { //do stuff } | Do array ( or ArrayList ) and LinkedList perform the same when iterating ? |
Java | I was wondering if it is possible to have something like this : so you can call the class likeWith Object 0 , 1 and 2 different types , like Integer , Float , String and so on . Is this possible , or would I have to write a class for each lenght of generic types ? If this would be possible , how would I handle the diff... | public class foo < T ... > Foo < Object0 > Foo < Object0 , Object1 > Foo < Object0 , Object1 , Object2 > | Is it possible to have a variable amount of Element types in a java generic class |
Java | I have a String which can either be of Double or Integer type or some other type . I first need to create a Double or Integer object and then send it over to a overloaded method . Here 's my code so far ; I 'd like to do this without if/else , with something like this ; The problem is 'theClass ' still ca n't be cast t... | public void doStuff1 ( object obj , String dataType ) { if ( `` Double '' .equalsIgnoreCase ( dataType ) ) { doStuff2 ( Double.valueOf ( obj.toString ( ) ) ) ; } else if ( `` Integer '' .equalsIgnoreCase ( dataType ) ) { doStuff2 ( Integer.valueOf ( obj.toString ( ) ) ) ; } } public void doStuff2 ( double d1 ) { //do s... | Create an object with a String and method overloading |
Java | I have a pretty basic PushNotification code that should open an activity when no URL is present , and open an URL when there is one . But it does n't open the URLs when the notification is received . Code belowAnd I am sending the notification like this : Inspired by other threads , I have : Tried to set Uri.parse ( ``... | public class MyFirebaseMessagingService extends com.google.firebase.messaging.FirebaseMessagingService { private static final String TAG = `` FirebaseMessagingServic '' ; public MyFirebaseMessagingService ( ) { } @ Override public void onMessageReceived ( RemoteMessage remoteMessage ) { if ( remoteMessage.getData ( ) .... | Push URL does n't open |
Java | I am using a Map < String , Optional < List < String > > > . I am getting an obvious NullPointerException because the result is null for that key.Is there any way to handle the null situation ? I am trying to avoid a if-else check for null by using Optional . | public Map < MyEnum , Optional < List < String > > > process ( Map < MyEnum , Optional < List < String > > > map ) { Map < MyEnum , Optional < List < String > > > resultMap = new HashMap < > ( ) ; // Getting NullPointerException here , since map.get ( MyEnum.ANIMAL ) is NULL resultMap.put ( MyEnum.ANIMAL , doSomething ... | Facing NullPointerException while using Optional |
Java | This is the implementation of map ( ) method : When I call map ( ) like this , what is the type of T and U ? What is the type of wildcard ( ? ) ? It is very confusing.Javadoc statement says : @ param < U > is the type of the value returned from the mapping function . Does `` mapping function '' mean map ( ) method or a... | public < U > Optional < U > map ( Function < ? super T , ? extends U > mapper ) { Objects.requireNonNull ( mapper ) ; if ( ! isPresent ( ) ) { return empty ( ) ; } else { return Optional.ofNullable ( mapper.apply ( value ) ) ; } } Optional < String > os1 = Optional.of ( `` Optional String '' ) ; Optional < String > os2... | Wildcard generics of map ( ) method |
Java | The following code prints `` String '' Why does that code compile ? Is n't null ambiguous ? For example , the following code will NOT compile because of an ambiguous signature.Can someone please explain why the first example can compile without having ambiguous errors ? | public class Riddle { public static void main ( String [ ] args ) { hello ( null ) ; } public static void hello ( Object o ) { System.out.println ( `` Object '' ) ; } public static void hello ( String s ) { System.out.println ( `` String '' ) ; } } public class Riddle { public static void main ( String [ ] args ) { hel... | Why and How Does This Java Code Compile ? |
Java | I 'm experimenting with parallel streams in Java and for that I 've the following code for calculating number of primes before n.Basically I 'm having 2 methodscalNumberOfPrimes ( long n ) - 4 different variantsisPrime ( long n ) - 2 different variantsActually I 'm having 2 different variants of each of the above metho... | // itself uses parallel stream and calls parallel variant isPrime private static long calNumberOfPrimesPP ( long n ) { return LongStream .rangeClosed ( 2 , n ) .parallel ( ) .filter ( i - > isPrimeParallel ( i ) ) .count ( ) ; } // itself uses parallel stream and calls non-parallel variant isPrime private static long c... | Proper usage of parallel streams in Java |
Java | The pattern works fine but how can I catch/get my groups ? At the moment I get only Strings . | public final Pattern PATTERN = Pattern.compile ( `` < abc : c\\sabc : name=\ '' ( \\S+ ) \ '' \\sabc : type=\ '' ( \\S+ ) \ '' > '' ) ; try ( Stream < String > stream = Files.lines ( template.getPath ( ) ) ) { stream.filter ( s - > PATTERN.matcher ( s ) .find ( ) ) .forEach ( System.out : :println ) ; } catch ( IOExcep... | Apply pattern on file stream |
Java | I 'm working on a project that has hosts and clients , and where hosts can send commands to clients ( via sockets ) .I 'm determined that using JSON to communicate works the best.For example : In this example , when this JSON string is sent to the client , it will be processed and a suitable method within the client wi... | { `` method '' : `` toasty '' , `` params '' : [ `` hello world '' , true ] } public abstract class ClientProcessor { public abstract void toasty ( String s , boolean bool ) ; public abstract void shutdown ( int timer ) ; private Method [ ] methods = getClass ( ) .getDeclaredMethods ( ) ; public void process ( String d... | What security issues come from calling methods with reflection ? |
Java | It 's hard to explain in words , but Java Generics are given me an unexpected result . I expected that if I say a list is of type ? extends Object , I could store anything in there . Therefore , if the list of of type Wrapper < ? extends Object > , I could store any kind of Wrapper in there . And so on . That makes sen... | private static class Wrapper < T > { public Wrapper ( T t ) { /**/ } } private static final List < Wrapper < Wrapper < ? extends Object > > > ls1 = new ArrayList < > ( ) ; public static < T > doit ( T t ) { Wrapper < Wrapper < T > > l1 = new Wrapper < > ( new Wrapper < > ( t ) ) ; ls1.add ( l1 ) ; // nok // add ( Wrapp... | Java generics weird behaviour |
Java | I came across a code snippet inside the androidx.lifecycle package and I was wondering what does this means.Where mActiveCount is an int , and mActive is a boolean.But , as I was writting this question , I think I came with the answer , so if I 'm not mistaken the `` += '' operator , is used as we normally use the `` =... | LiveData.this.mActiveCount += mActive ? 1 : -1 ; int intToAdd = mActive ? 1 : -1 ; activeCount += intToAdd ; | What does a `` += '' operator inside a ternary operator means ? |
Java | The following code : produces the output : 8In the javadocs , it is written that we can not put underscoresat the beginning of a number as in the example int x5 = 0x_52 ; , which produces the error illegal underscore.However , in this code , 0 is the prefix for octal numbers , as we can see that the output is 8 . But t... | int i = 0_10 ; System.out.println ( i ) ; | No error when underscore used between prefix and number |
Java | To speed up my debugging , I color certain messages for instant spotting , like this : It works , but viewing this source code over and over again , where the only justification for occupying 4 precious lines is one different character only ( Log.i vs. Log.v ) is an eyesore for me.Any suggestions for avoiding this eyes... | if ( isOK ) Log.i ( TAG , stringVarContentOfMessage ) ; else Log.v ( TAG , stringVarContentOfMessage ) ; isOK ? Log.i ( TAG , stringVarContentOfMessage ) : Log.v ( TAG , stringVarContentOfMessage ) ; | Terser Coloring of a LogCat Message ? |
Java | I was wondering why this piece of JAVA code produces a different output than the same code in C++.This produces the output : The JAVA code is : This code produces only Why is this output different in this case ? | # include `` stdafx.h '' # include < iostream > using namespace std ; class A { public : A ( ) { this- > Foo ( ) ; } virtual void Foo ( ) { cout < < `` A : :Foo ( ) '' < < endl ; } } ; class B : public A { public : B ( ) { this- > Foo ( ) ; } virtual void Foo ( ) { cout < < `` B : :Foo ( ) '' < < endl ; } } ; int main ... | Difference between these 2 codes ? |
Java | I 'm trying to refactor the following code : Naturally , I want to remove the repetition in this code to save myself from typing even more of the same lines when new properties are added , but I can not quite figure out how to do that.My first instinct was that it looks a lot like this code ( which , unfortunately , do... | class Base { private Object a , b , < ... > ; // there 's like 10 of these attributes of different type public Object a ( ) { return a ; } public Object b ( ) { return b ; } // more getters like the ones above } class RootNode extends Base { } class BranchNode extends Base { private RootNode root ; // passed via constr... | Create non-capturing method reference which will call superclass method |
Java | I have a regular expression to extract two tokens , delimiters [ ' ] and words between apostrophes like 'Stack Overflow ' . The question is , why this regular expression does n't work ? Regex : Here is a link to explain it : Regular ExpressionOnly works extracting apostrophes but , words between apostrophes no.NOTE : I... | ( [ ' ] ) | ' ( [ ^ ' ] * ) ' | Why this Regular Expression does n't work ? |
Java | I need a per-key locking mechanism for protecting key-bound critical sections.Although a ConcurrentMap < K , Semaphore > would suffice for concurrency , I also do n't want the map to accumulate old keys and grow indefinitely.Ideally , the data structure will eventually ( or straight after ) release the memory used for ... | private static final LoadingCache < K , Semaphore > KEY_MUTEX = CacheBuilder.newBuilder ( ) .weakValues ( ) .build ( new CacheLoader < K , Semaphore > ( ) { @ Override public Semaphore load ( K key ) throws Exception { return new Semaphore ( 1 ) ; } } ) ; | Would Guava 's Cache < K , Semaphore > with weakValues ( ) be thread safe ? |
Java | I need to get all possible combinations of 5 objects from set of 7 objects . Combinations without repetition ( the order of selection does not matter , that 's the same objects selected in different orders are regarded as the same combination ) .I have implementation , it works properly and produces the correct result ... | String [ ] vegetablesSet = { `` Pepper '' , `` Cabbage '' , `` Tomato '' , `` Carrot '' , `` Beans '' , `` Cucumber '' , `` Peas '' } ; final int SALAD_COMBINATION_SIZE = 5 ; // Example : { `` Tomato '' , `` Cabbage '' , `` Cucumber '' , `` Pepper '' , `` Carrot '' } Set < Set < String > > allSaladCombinations = new Ha... | How to generate combinations from a set of objects ? |
Java | I haveAndOutput : [ C @ c17164MustangOutput : Shelby'sI 'm not understanding why I get the weird output when I concatenate the char array with a string . What is the `` [ C @ c17164 '' ? The location in memory ? And why do I get that when I concatenate with a string , but I get what I would expect when I print it alone... | char c1 = 'S ' ; // S as a characterchar c2 = '\u0068 ' ; // h in Unicodechar c3 = 0x0065 ; // e in hexadecimalchar c4 = 0154 ; // l in octalchar c5 = ( char ) 131170 ; // b , casted ( 131170-131072=121 ) char c6 = ( char ) 131193 ; // y , casted ( 131193-131072=121 ) char c7 = '\ '' ; // ' apostrophe special character... | Java println ( charArray + String ) vs println ( charArray ) |
Java | I assumed that separating objects that implement different interfaces into several lists and iterating those lists afterwards would be faster than dumping all objects into a single list and then switching via instanceof . E.g . this : should be faster thanHowever it does n't seem to be the case : I added full source fo... | ArrayList < Visible > visibles = new ArrayList < > ( ) ; ArrayList < Highlightable > highlightables = new ArrayList < > ( ) ; ArrayList < Selectable > selectables = new ArrayList < > ( ) ; // populate the lists// Visible is an interface , Highlightable is also interface ( extends Visible ) , // Selectable extends Highl... | Why instanceof and iterating single list is faster than several specialized lists ? |
Java | I come here with a problem I would like to share , I hope anyone can help me to solve this . I 'll try to describe the problem as clear as possible . The problem is as follows.I have a program in java , with a method that receives a set of dates ( java.util.Date ) .In the example above , we have three dates , where the... | | start end || date1 date1| < -- -- -- -- -- -- -- - > | | start end | | || | date2 date2| | || < -- -- -- -- -- -- -- -- -- - > | || | start end || | date3 date3|| < -- -- -- -- -- -- -- -- -- - > | start end || date1 date1| < -- -- -- -- -- -- -- - > | | start end | | || | date2 date2| | || < -- -- -- -- -- -- -- -- ... | Find a space of time in a set of dates |
Java | I 'm quite inexperienced in making GUI 's with Swing and now I 'm wondering if its possible to use `` { `` and `` } '' just to subdivide my code a little bit e.g.I tested it and I do n't think it made any difference ... Am I wrong ? Thanks in advance | [ ... ] JFrame f = new JFrame ( ) ; JPanel p = new JPanel ( ) ; { JLabel a = new JLabel ( `` Hello '' ) ; p.add ( a ) ; JLabel b = new JLabel ( `` World ! `` ) ; p.add ( b ) ; } f.add ( p ) ; [ ... ] | Is it possible to use braces { } just to subdivide Java code ? |
Java | BackgroundI have a large data map ( HashMap ) , kept in memory , which is updated incrementally ( based on incoming messages ) , by the background thread : End users will then query it via the REST API : Updates are not applied immediately , but in batches , once a special control message is received , i.e.The architec... | < KEY > = > < VALUE > ... GET /lookup ? key= < KEY > MESSAGE : `` Add A '' A= < VALUE > //Not visible yetMESSAGE : `` Add B '' B= < VALUE > //Not visible yetMESSAGE : `` Commit '' //Updates are now visible to the end-usersA= < VALUE > B= < VALUE volatile Map passiveCopy = new HashMap ( ) ; volatile Map activeCopy = new... | Updating and swapping HashMaps with volatile |
Java | I am planning to get list of methods defined in one package ( CommonPackage ) called by a class defined in another package ( ServicePackage ) . For that , I need a to crawl a given method code and get the methods called outside of this class . I have researched the Java reflections and was not able to find any solution... | ClassA { private ClassB classB ; public methodA1 ( ) { classB.methodB1 ( ) ; } } ClassB { public methodB1 ( ) { // Some code } } | How to get list of methods defined in another class called from a given method in Java |
Java | I am trying to make a system for responding to events that happen in my application , similar to the Observer pattern . In my system , EventProducers trigger events and EventConsumers respond to those events , and the two are connected through a central hub : For the moment , I 'm going to ignore EventProducer and focu... | interface EventConsumer < E extends Event > { void respondToEvent ( E event ) ; } class EventHub { private HashMap < Class < /*event type*/ > , HashSet < EventConsumer < /*event type*/ > > > subscriptions ; public < E extends Event > void fireEvent ( E event ) { /* For every consumer in the set corresponding to the eve... | Need some help using Java Generics |
Java | My question is : Given a list of persons , return all students.Here are my classes : Person classStudent classMethodI 'm getting a compile error : incompatible types : inference variable T has incompatible boundsHow do I return all the students from the list using stream without getting this error . | public class Person { } public class Student extends Person { } public static List < Student > findStudents ( List < Person > list ) { return list.stream ( ) .filter ( person - > person instanceof Student ) .collect ( Collectors.toList ( ) ) ; } | How do I stream objects of incompatible types into a list ? |
Java | Lets say I have And I have a list of AnimalsUsing Guava FluentIterable I can filter and convert in one stepUsing Java8 I need to doThere is no way I can make the filter & map in one step , right ? | class Dog extends Animal { } class Cat extends Animal { } List < Cat > cats = FluentIterable.from ( animals ) .filter ( Cat.class ) .toList ( ) ; List < Cat > cats = animals.stream ( ) .filter ( c - > c instanceof Cat ) .map ( c - > ( Cat ) c ) .collect ( Collectors.toList ( ) ) ; | Can I filter a Stream < T > by element 's class an get a Stream < U > in one step ? |
Java | given this code snippetWhy is that num.add ( doub ) will not be allowed ? is n't List < List < Number > > a super type of List < List < Double > > ? | //Creates a list of List numbers List < List < Number > > num = new ArrayList < List < Number > > ( ) ; //Creates a list of List doubles List < List < Double > > doub = new ArrayList < List < Double > > ( ) ; //List of doubles List < Double > d = new ArrayList < Double > ( ) ; d.add ( 2.5 ) ; d.add ( 2.6 ) ; doub.add (... | Why is adding a subclass a of type in a collection is illegal ? |
Java | I 'm writing code to use Win32 API to detect a java 's version . E.g.Basically , I 'm following MSDN Creating a Child Process with Redirected Input and Outputhttps : //msdn.microsoft.com/en-us/library/ms682499 % 28VS.85 % 29.aspxThis is the pseudo client code : I can get the result as : However , the result is sent bac... | string GetJavaVersion ( string sJavaExePath ) { } ASSERT ( GetJavaVersion ( `` C : \Program Files ( x86 ) \Java\jdk1.7.0_17\bin\java.exe '' ) == `` 1.7.0_25 '' ) ; java version `` 1.7.0_25 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_25-b17 ) Java HotSpot ( TM ) Client VM ( build 23.25-b01 , mixed mode , sharing... | command line `` java -version '' will send result to stdOut or stdErr ? |
Java | Given is the following Java code example : Is it guaranteed by the Java Language Specification that getSomething ( ) is invoked after the somethingElse ( ) method or is a Java implementation allowed to reorder the execution ? | builder.something ( ) .somethingElse ( ) .somethingMore ( builder.getSomething ( ) ) ; | Java method invocation order with chained methods |
Java | I 'm looking at some notify/wait examples and came across this one . I understand a synchronized block essentially defines a critical section , but does n't this present a race condition ? Nothing specifies which synchronized block is entered first.Output per website : Waiting for b to complete ... Total is : 4950 | public class ThreadA { public static void main ( String [ ] args ) { ThreadB b = new ThreadB ( ) ; b.start ( ) ; synchronized ( b ) { try { System.out.println ( `` Waiting for b to complete ... '' ) ; b.wait ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; } System.out.println ( `` Total is : `` + b.t... | Is there a race condition in this example ? If so , how could it be avoided ? |
Java | First of all Sorry For this question . this is very old topic.Yes i did lots of search that java is pass by value.But by my program show that out put . i ca n't understand why ? My program is Output isOldDogNewDogNewDogbut i am expectingOldDogNewDogOldDogPlease anybody tell me where i am thinking wrong . | class Dog { static String dogName ; Dog ( String name ) { dogName=name ; } public void setName ( String newName ) { dogName=newName ; } public String getName ( ) { return dogName ; } } class JavaIsPassByValue { public static void main ( String arr [ ] ) { Dog dog1=new Dog ( `` OldDog '' ) ; new JavaIsPassByValue ( ) .d... | static , Java is pass by value . then why my program show that output ? |
Java | I would like to flatten a HashMap instance like in this example . Note that the data is not in JSON format , this is just a pseudo code : Unfortunately , I could n't find any reference implementation for that so I came up with my recursive solution shown below . Is there a better way ( in terms of not using recursion o... | nested = { `` one '' : { `` two '' : { `` 2a '' : `` x '' , `` 2b '' : `` y '' } } , `` side '' : `` value '' } // output : { `` one.two.2a '' : `` x '' , `` one.two.2b '' : `` y '' , `` side '' : `` value '' } public class Flat { public static void flatten ( Map < String , ? > target , Map < String , String > result ,... | Best way to flatten and unflatten a HashMap |
Java | I have a problem while creating a with a default value contained in my current object.The value is correctly set in the field , but when I submit the form , the default value is still there , even if the user chose another value in the list ... Here is my controller : And here is my JSP : For instance , if i choose `` ... | @ RequestMapping ( method = RequestMethod.GET ) public String createForm ( final ModelMap modelMap ) { User user ; user = new User ( ) ; user.setGroup ( `` HelpDesk '' ) ; user.setName ( `` John '' ) ; ArrayList < String > groupList = new ArrayList < > ( ) ; groupList.add ( `` Admin '' ) ; groupList.add ( `` HelpDesk '... | Default value in select still there after submit |
Java | I have a couple of questions about instances of the class Class1 ) Do I understand correctly that say for the class Dog there is only one instance of the class Class . In other words , given the following linesthere is only one instance of the class Class - Class < Dog > .If you compare these references with == , you g... | Dog dog1 = new Dog ( ) ; Dog dog2 = new Dog ( ) ; Class dog1Class = dog1.getClass ( ) ; Class dog2Class = dog2.getClass ( ) ; Class dogClass = Dog.class ; | instances of the class Class |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.