lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I was reading jls 8 and I got stuck on Example 8.1.2-1 , Mutually Recursive Type Variable Bounds I searched stackoverflow , and found a question what is a mutually recursive type ? but this was not in terms of Java.Example 8.1.2-1 . Mutually Recursive Type Variable BoundsQuestion : What does Recursive Type and Mutually... | interface ConvertibleTo < T > { T convert ( ) ; } class ReprChange < T extends ConvertibleTo < S > , S extends ConvertibleTo < T > > { T t ; void set ( S s ) { t = s.convert ( ) ; } S get ( ) { return t.convert ( ) ; } } | Example 8.1.2-1 Of Java Language Specification ( Mutually Recursive Type Variable Bounds ) |
Java | I used to use enums as indexes in C. ( each enum something like an alias for an int value ) Example : With enums as indexes , I can always be sure that I am updating the right cell . Furthermore , I need the simplicity of arrays as well.I would like to do the same in Java . But , I cant seem to find a simple replacemen... | typedef enum { DOG , CAT , MOUSE } ANIMALS ; int [ 3 ] age ; ... age [ DOG ] = 4 ; age [ CAT ] = 3 ; age [ MOUSE ] = 10 ; | Is there a replacement for Arrays with enums as indexes ? |
Java | I am using a simple random calculations for a small range with 4 elements.When I attach the debugger I see that for the first 2-3 times every time the result is 1.Is this the wrong method for a small range or I should implement another logic ( detecting previous random result ) ? NOTE : If this is just a coincidence , ... | indexOfNext = new Random ( ) .nextInt ( 4 ) ; //randomize 0 to 3 | Why random of 0 to 4 is 1 most of times ? |
Java | While I move my gaming mouse inside a javax.swing.JFrame , all animated GIFs ( javax.swing.ImageIcon inside a javax.swing.JLabel ) stops animating until the mouse stops moving.This only happens with a gaming mouse with a driver on macOS ( tested it with a Rocket-Kone XTD and a Razer gaming mouse on two computers ) . Wh... | import java.lang.reflect.InvocationTargetException ; import javax.swing.ImageIcon ; import javax.swing.JFrame ; import javax.swing.JLabel ; import javax.swing.SwingUtilities ; public class Mouse { public static void main ( String [ ] args ) { try { SwingUtilities.invokeAndWait ( new Runnable ( ) { public void run ( ) {... | GIF stops animating while gaming mouse is moving |
Java | Let 's consider the following example : Some languages allow us to specify \U $ 1 in place of $ 1 which converts matched groups with uppercase letters . How can I achieve the same using Java ? I know we can use Pattern class and get the group and convert it to uppercase , but that 's not what I am looking for . I want ... | String s = str.replaceAll ( `` regexp '' , `` $ 1 '' ) ; String s = str.replaceAll ( `` regexp '' , `` $ 1 '' .toUpperCase ( ) ) ; String s = str.replaceAll ( `` regexp '' , method ( `` $ 1 '' ) ) ; // method declared as method ( ) private static String method ( String s ) { System.out.println ( s ) ; // prints `` $ 1 ... | Regex replace the substitution string |
Java | Interfaces : Attempt to use intersection type : Attempt to compile with javac 1.8.0_60 : Why this intersection type is invalid for javac ? | interface PublicCloneable { Object clone ( ) ; } interface HasPosition { // does n't matter } @ SuppressWarnings ( `` unchecked '' ) < E extends PublicCloneable & HasPosition > E cloneAndIncrementPosition ( E elem ) { final E clone = ( E ) elem.clone ( ) ; // rest omitted } $ javac xx.javaxx.java:13 : error : clone ( )... | unable to use an intersection type when notional class requires access modification |
Java | [ EDIT ] The solution of @ antonio works . See the screeshots below for proof..I am trying to use JorgeCastilloPrz 's AndroidFillableLoaders Library and this is the first time i am using SVG ( or Path for that matter ) . So please bear with me if the question is too naive.Library Link : https : //github.com/JorgeCastil... | < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' android : id= '' @ +id/rl_root_splash_activity '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : background= '' @ color/spla... | JorgeCastilloPrz 's AndroidFillableLoaders Library - SVGPath issue |
Java | In the code belowThen I can call new B ( ) .v ( 1 , 2 , 3 ) ; //print Sub rather than Super which is ridiculous but does work well . If I change B to the call to new B ( ) .v ( 1 , 2 , 3 ) ; will be invalid . You have to call it as new B ( ) .v ( new int [ ] { 1 , 2 , 3 } ) ; , why ? | class A { public void v ( int ... vals ) { System.out.println ( `` Super '' ) ; } } class B extends A { @ Override public void v ( int [ ] vals ) { System.out.println ( `` Sub '' ) ; } } class B { public void v ( int [ ] vals ) { System.out.println ( `` Not extending A '' ) ; } } | method signature in inheritance |
Java | My Java source code : The output is : ee1e2e3e.Why ? | String result = `` B123 '' .replaceAll ( `` B* '' , '' e '' ) ; System.out.println ( result ) ; | What is the effect of `` * '' in regular expressions ? |
Java | I 've been banging my head around , trying to figure what 's wrong with the following mapping . I understand the following mapping is not ideal for ORM , but that 's how the database is and I can not change its structure . I 'm using JPA 2.1 and Hibernate 5.0.2.Final.Besides this structure , I also have a converter to ... | @ MappedSuperclass public abstract class BaseEntity < T extends Serializable > implements Serializable { protected T id ; @ Id public T getId ( ) { return id ; } protected void setId ( T id ) { this.id = id ; } } @ Table ( name = `` campaign '' ) @ AttributeOverride ( name = `` id '' , column = @ Column ( name = `` cam... | Wrong TypeDescriptor when using JoinColumns in a composite Key |
Java | This is a simple code My question is : How Java knows that the passed null is Bar and not Foo ? I know why the compiler chooses Bar and not Foo ( because there is a conversion from foo to bar and from bar to foo and not vice-versa ) .But how would the method know this null comes from Bar and not Foo ? does null contain... | class Foo { } class Bar extends Foo { } public class Main { public static void main ( String [ ] args ) throws Exception { fn ( null ) ; } static void fn ( Foo f ) { System.out.println ( f instanceof Foo ? `` Foo '' : `` Bar '' ) ; } } | Is a null reference an instance of a class ? |
Java | In java.util.stream.Stream interface , the combiner is a BiConsumer < R , R > , whereas in the combiner is a BinaryOperator < A > which is nothing but a BiFunction < A , A , A > .While the later form clearly defines what will be reference of the combined object after combining , the former form doesn't.So how does any ... | < R > R collect ( Supplier < R > supplier , BiConsumer < R , ? super T > accumulator , BiConsumer < R , R > combiner ) ; < R , A > R collect ( Collector < ? super T , A , R > collector ) ; | Out of the java.util.stream.Stream interfaces 's two collect methods , is one of them poorly constructed ? |
Java | I have a lambda that currently returns 1st row where date matches passed in date , by using RecordNumber.Here is my current code : Now , I have to add functionality for if ProEffectiveDate is null to simply return first row from the list.When ProEffectiveDate is null , how do I ignore this filter ? | ProList 1 RecordNumber 1 ProEffectiveDate NULLProList 2 RecordNumber 2 ProEffectiveDate 2019-03-01ProList 3 RecordNumber 3 ProEffectiveDate 2019-03-01 Predicate < ProList > filteredRow = it- > it.getProEffectiveDate ( ) ! =null & & it.getProEffectiveDate ( ) .equals ( passedInDate ) ; final ProList minFilteredRow = Pro... | Use lambda filter if element is not null otherwise ignore filter |
Java | If I write the Java methodthen I can call this method viaas well asand both calls are treated exactly the same . However , the two callsandare not treated the same . The section on evaluating arguments in the JLS states `` The final formal parameter of m necessarily has type T [ ] for some T '' so why is n't the `` fin... | public static void f ( int ... x ) { for ( int a : x ) { System.out.println ( a ) ; } } f ( 1 , 2 , 3 ) ; f ( new int [ ] { 1 , 2 , 3 } ) ; Arrays.asList ( 1 , 2 , 3 ) // ( a ) produces a three-element Integer list Arrays.asList ( new int [ ] { 1 , 2 , 3 } ) // ( b ) produces a one-element list of Integer arrays | How can one explain this seemingly inconsistent Java varargs behavior ? |
Java | The Java API documentations states that the combiner parameter of the collect method must be : an associative , non-interfering , stateless function for combining two values , which must be compatible with the accumulator functionA combiner is a BiConsumer < R , R > that receives two parameters of type R and returns vo... | List < String > res = LongStream .rangeClosed ( 1 , 1_000_000 ) .parallel ( ) .mapToObj ( n - > `` '' + n ) .collect ( ArrayList : :new , ArrayList : :add , ( m1 , m2 ) - > m1.addAll ( m2 ) ) ; | Where is defined the combination order of the combiner of collect ( supplier , accumulator , combiner ) ? |
Java | I understand that the argument of myMethod ( ) being an int literal , and the parameter b being of type byte , this code would generate a compile time error . ( which could be avoided by using an explicit byte cast for the argument : myMethod ( ( byte ) 12 ) ) After experiencing this , I expected that the above code to... | class MyClass { void myMethod ( byte b ) { System.out.print ( `` myMethod1 '' ) ; } public static void main ( String [ ] args ) { MyClass me = new MyClass ( ) ; me.myMethod ( 12 ) ; } } class MyClass { byte myMethod ( ) { return 12 ; } public static void main ( String [ ] args ) { MyClass me = new MyClass ( ) ; me.myMe... | Why is an explicit cast not needed here ? |
Java | We are designing a system for processing XML messages.The processing Java class needs to split out various attributes and values from a largish XML and pass these as parameters to individual handler classes for varied operations.We have thought of following options : A ) Pass the entire XML to each handler and let it e... | < IdAction > supplied < /IdAction > < RegId > true < /RegId > < DeRegId > false < /DeRegId > < SaveMessage > false < /SaveMessage > < ServiceName > abcRequest < /ServiceName > < timeToPerform > 3600 < /timeToPerform > < timeToReceipt/ > < SendToBES > true < /SendToBES > < BESQueueName > com.abc.gateway.JMSQueue.forAddR... | Java OO design for handling large XML |
Java | I have two classes A & B , where B is derived from A . Both the classes have a method with same signature . They are called in the following manner in Java & c # -- > In case of JAVA : This program generates the following output : -In case of C # : This program generates the following output : -Why does the output diff... | class A { public void print ( ) { System.out.println ( `` Inside Parent '' ) ; } } class B extends A { public void print ( ) { System.out.println ( `` Inside Child '' ) ; } } class test4 { public static void main ( String args [ ] ) { B b1=new B ( ) ; b1.print ( ) ; A a1=new B ( ) ; a1.print ( ) ; } } Inside ChildInsid... | Why this difference of handling method ambiguity in Java & c # ? |
Java | When I 'm using a JXTable to render and edit my data , some input into the CellEditors gets lost . If I click on the Resizing-Divider of the JXTable-ColumnHeader or change the width of the JFrame , the CellEditor gets terminated without commiting the value . The values are saved if I use the JTable . I want to use the ... | package table.columnresize ; import javax.swing.JFrame ; import javax.swing.JScrollPane ; import javax.swing.JTable ; import javax.swing.table.DefaultTableModel ; import org.jdesktop.swingx.JXTable ; /** * Demo of differing behaviour of JXTable and JTable . JXTable loses input in a TableCell where JTable persists * it ... | Why is JXTable losing input where JTable is not ? |
Java | I am having trouble comprehending why parallel stream and stream are giving a different result for the exact same statement.ResultParallel : 1 , 2 , 3Result : 1 2 3Can somebody explain why this is happening and how I get the non-parallel version to give the same result as the parallel version ? | List < String > list = Arrays.asList ( `` 1 '' , `` 2 '' , `` 3 '' ) ; String resultParallel = list.parallelStream ( ) .collect ( StringBuilder : :new , ( response , element ) - > response.append ( `` `` ) .append ( element ) , ( response1 , response2 ) - > response1.append ( `` , '' ) .append ( response2.toString ( ) ... | Parallel Stream behaving differently to Stream |
Java | I 'm trying to re-order my items list ( Using android getListView , not custom ) by distance and I 'm having issues.I 'm getting the Spherical distance in meters ( double ) using Maps Utils inside the adapter ( SomeAdapter ) .double distance = SphericalUtil.computeDistanceBetween ( fromCoord , toCoord ) ; But after I f... | @ Override protected void onPostExecute ( Boolean result ) { try { SQLiteHelper dbHelper = new SQLiteHelper ( getActivity ( ) ) ; pds = new SomeDataSource ( dbHelper.db ) ; ArrayList < Raids > some = pds.getAllRaids ( ) ; SomeAdapter listViewAdapter = new SomeAdapter ( getActivity ( ) , some ) ; getListView ( ) .setAda... | Android re-order adapter by distance |
Java | I searched about a day now , but didnt find any example for my problem in Javacode.I have a worldmap with a size of 2000*1400 Pixels with a 'Mollweide ' projection.How can I find out what is the longitude and laltitude of the point ( 500,300 ) in my map ? I would like to code this in Java.I tried to do this with the 'J... | Point2D.Double pointonmap = null ; Point2D.Double latlon = null ; MolleweideProjection molproj=new MolleweideProjection ( ) ; pointonmap = new Point2D.Double ( 1400,1000 ) ; latlon=molproj.inverseTransform ( pointonmap , new Point2D.Double ( ) ) ; System.out.println ( `` latlon : `` + latlon.getX ( ) + `` , `` + latlon... | Get Longitude Laltitude of a point in my Worldmap in Mollweide projection |
Java | On page 140 of Effective Java we are advised that a method signature with a wildcard is preferable to one with a type parameter that only appears once . For example , is preferable toHowever it is not possible to set an item of a List < ? > to be anything ( except null ) so Effective Java suggests writing a private hel... | public static void swap ( List < ? > list , int i , int j ) public static < T > void swap ( List < T > list , int i , int j ) private static < T > void swapHelper ( List < T > list , int i , int j ) { list.set ( i , list.set ( j , list.get ( i ) ) ) ; } public static void swap ( List < ? > list , int i , int j ) { swap... | Raw types and performance |
Java | The following signature is valid and commonly used in Scala : However , since > : is the Scala equivalent of super in Java , my first idea to convert this signature ( replacing the function type with BiFunction and making use of Use-Site variance annotations aka Bounded Wildcards ) would beBut oh no ! The compiler comp... | trait Collection [ A ] { def reduceLeft [ B > : A ] ( f : ( B , A ) = > B ) : B } interface Collection < A > { < B super A > B reduceLeft ( BiFunction < ? super B , ? super A , ? extends B > mapper ) } public < R extends E > R reduceLeft ( BiFunction < ? super R , ? super E , ? extends R > mapper ) { if ( this.isEmpty ... | Java 'reduceLeft ' signature / Lower-bounded Type Arguments |
Java | I made a little test to manipulate a short and I came across a compilation problem.The following code compile : while this one does n't : I 've read that shorts are automatically promoted to int , but what 's the difference between those two codes ? | short s = 1 ; s += s ; short s = 1 ; s = s + s ; // Can not convert from int to short | Difference between s = s + s and s += s with short |
Java | What is the reason that the first line does not compile and the second and third one does ? | interface A { void s ( ) ; } public static void main ( String [ ] args ) { A a = ( ) - > 5 ; // DOES NOT compile A b = ( ) - > new Integer ( 5 ) ; // does compile A c = ( ) - > Stream.of ( 1 , 2 , 3 ) ; // does compile } | Lambda Expression that has return type as void can compile with wrapper but not compile with primitive |
Java | I receive some crash reports from android ( with java.lang.NullPointerException ) , but I do n't understand what mean __null __ in stacktrace below : And I do n't understand what access $ xxx functions is ? Furthermore , formatElapsedTime is not called from onEnterPressed neither directly nor indirectly ! That is absol... | at __null__.formatElapsedTime ( MainActivity.java ) at __null__.access $ 102 ( MainActivity.java ) at __null__.access $ 200 ( MainActivity.java ) at __null__.access $ 500 ( MainActivity.java ) at ru.yandex.subbota_job.multiplicationtable.MainActivity.onEnterPressed ( MainActivity.java ) at ru.yandex.subbota_job.multipl... | Strange stack at android crash report |
Java | Hello dear Programmers , I have a String String input = `` 30.09.1993 '' ; Then i want to save all numbers in this string in an array ( Only numbers ! ) . The `` . '' are at index 2 and 5 so i want to skip these parts of my string in my loop with an if-statement.I fixed my problem and everything works fine but I 'm con... | String input = `` 30.09.1993 '' ; int [ ] eachNumbers = new int [ 8 ] ; int x = 0 ; for ( int i = 0 ; i < = 9 ; i++ ) { if ( i ! = 2 & & i ! = 5 ) { eachNumbers [ x ] = Integer.parseInt ( input.substring ( i , i+1 ) ) ; x++ ; } } String input = `` 30.09.1993 '' ; int [ ] eachNumbers = new int [ 8 ] ; int x = 0 ; for ( ... | Logic of Java Operators & & and || |
Java | I 've been reading up on ( and experimenting with ) several Java mocking APIs such as Mockito , EasyMock , JMock and PowerMock . I like each of them for different reasons , but have ultimately decided on Mockito . Please note though , that this is not a question about which framework to use - the question really applie... | Car mockCar = mock ( Car.class ) ; when ( mockCar.getMaxSpeed ( ) ) .thenReturn ( 100.0 ) ; | Value of Behavior Verification |
Java | So , I use IntelliJ IDEA to program in Java , and I was experimenting with the keyword instanceof and my code looked eventually like this : IntelliJ gives me at the two instanceof Two line a hint `` [ ... ] is allways true '' , but for one instanceof Two IntelliJ does n't give me a `` [ ... ] is always false '' hint . ... | public class Main { public static void main ( String args [ ] ) { One one = new One ( ) ; One two = new Two ( ) ; if ( one instanceof Two ) { System.out.println ( one ) ; } if ( two instanceof Two ) { System.out.println ( one ) ; } } } class One { } class Two extends One { } | IntelliJ show `` always true '' hint but not `` always false '' for instanceof |
Java | How can a stream be created lazily ? During migration of collection based code I have run into this pattern multiple times : The resulting concatenated stream is typically processed lazily , as we know . Therefore the expensive collection is not needed at all , if the stream processing stops in the first part of the co... | Collection collection = veryExpensiveCollectionCreation ( ) ; return Stream.concat ( firstStream , collection.stream ( ) ) ; return Stream.concat ( firstStream , new LazyStreamProvider ( ) { Stream < Something > createStream ( ) { return veryExpensiveCollectionCreation ( ) .stream ( ) ; } ) ; | Create stream lazily |
Java | I am opening file pick Intent with , Bellow code I Want remove Contact option from list , please can anyone help.Thanks | Intent intent_upload = new Intent ( ) ; intent_upload.setType ( `` */* '' ) ; intent_upload.setAction ( Intent.ACTION_GET_CONTENT ) ; activity.startActivityForResult ( intent_upload , Constants.FILE_PICK_REQUEST_CODE ) ; | Remove Contact select option form file select options |
Java | Right now I 'm implementing a method that has one parameter of the type Class and this method returns a boolean if the given class object requires an instance of it 's enclosing class for it to be instantiated.This method currently works as follows : To explain why it is designed as such : It first checks if it 's a to... | if ( clazz.getEnclosingClass ( ) == null ) { return false ; } if ( clazz.isAnonymousClass ( ) || clazz.isMemberClass ( ) ) { return ! Modifier.isStatic ( clazz.getModifiers ( ) ) ; } if ( clazz.getEnclosingConstructor ( ) ! = null ) { return true ; } final Method enclosingMethod = clazz.getEnclosingMethod ( ) ; if ( en... | Java : How do i determine whether a local class defined in an initializer block requires an enclosing instance for instantiation ? |
Java | I just want to replace one element with different list of elements , I ca n't find a way how to do it . Where dynamicContentHtmls is list of Elements and element is the one which should be replaced.My experimental code : | int i=0 ; for ( Element element : dynamicContents ) { //element.remove ( ) ; element.append ( dynamicContentHtmls.get ( i ) ) ; //TextNode text = new TextNode ( dynamicContentHtmls.get ( i ) , `` '' ) ; //element.replaceWith ( text ) ; //element.html ( ) .replaceAll ( element.html ( ) , //dynamicContentHtmls.get ( i ) ... | How can I replace one element with list of elements using jsoup ? |
Java | We are using openJDK11.0.6 java.net.http HTTP ( HTTP1.1 ) client to fetch content from websites . After a long execution time , we noticed a performance decrease . CPU is 100 % used even when the app does nothing . We were able to determine that it comes from a lot of app leaked socket ( CLOSE-WAIT state ) . There is a... | import java.net.URI ; import java.net.http.HttpClient ; import java.net.http.HttpClient.Version ; import java.net.http.HttpRequest ; import java.net.http.HttpResponse ; import java.net.http.HttpResponse.BodyHandlers ; public class BasicFetcherApp { public static void main ( String [ ] args ) throws Exception { System.o... | Connections leaking with state CLOSE_WAIT with java.net.HttpClient |
Java | Preface : I understand generics and how they 're declared at the class level ( e.g . class MyClass < T > ) but I 've never seen it declared at the level of a static method , and without any explicit bindings ( e.g . class MySubclass < String > extends MyClass ) .I found this code snippet in an app I 'm working on ( I d... | private static < T > T getItemExtra ( final Intent intent , final String extraName ) { T item = null ; if ( intent ! = null & & intent.getExtras ( ) ! = null ) { item = ( T ) intent.getExtras ( ) .get ( extraName ) ; } return item ; } String s1 = getItemExtra ( someIntent , `` some_string_extra '' ) ; Uri u1 = getItemE... | What is a generic method and how is < T > bound in this case ? |
Java | I 've developed a Jersey API which returns either XML or JSON ( depending on the request header ) . When deployed on my Windows 2012 server ( Tomcat ) , it works no problem.When I deploy ( after compiling it on Ubuntu ) to an Ubuntu machine in AWS ( Glassfish ) , I get the following errors when I request JSON : No erro... | The server encountered an internal error that prevented it from fulfilling this request.exception javax.servlet.ServletException : org.glassfish.jersey.server.ContainerException : java.lang.NoClassDefFoundError : Could not initialize class org.eclipse.persistence.jaxb.BeanValidationHelperroot cause org.glassfish.jersey... | Returning Json From Jersey on Linux Throws Exception |
Java | Referring to the FeedReaderContract class on Android Developers page : Saving Data in SQL DatabasesThe code starts as : i.e . there is a default public constructor for the class.Is that code comment correct ? How does a public empty constructor prevent instantiation - should this maybe be private ? ... am I still half ... | public final class FeedReaderContract { // To prevent someone from accidentally instantiating the contract class , // give it an empty constructor . public FeedReaderContract ( ) { } | Empty constructor in FeedReaderContract demo |
Java | i am planning to perform a standard list command to get a vector or a list of the content of a directory.I know this is easy by usingThe problem is that I need a list/array/vector of URLs . So my thoughts were to convert the files to URL . With the org.apache.commons.io.FileUtils library this is possible with the follo... | File f = new File ( `` C : /testDir '' ) ; File [ ] files = f.listFiles ( ) ; URL [ ] urls = FileUtils.toURLs ( files ) ; | Fastest possibility of listing a directory and getting the URLs of every file in Java |
Java | In Java8When I write such code : Java8 streams are divided into two sections ; intermediate vs terminal operations , where the -AFAIK - actual action ( under-the-hood iterations ) is done in the terminal ops , while each intermediate ops appends its own -let me name it- Apply inner classes.By this , there will be only ... | Stream < Integer > xs = Arrays.asList ( 1 , 3 , 5 , 6 , 7 , 10 ) .stream ( ) ; xs.map ( x - > x * x ) .filter ( x - > x > 15 ) .forEach ( System.out : :println ) ; @ Override @ SuppressWarnings ( `` unchecked '' ) public final < R > Stream < R > map ( Function < ? super P_OUT , ? extends R > mapper ) { Objects.requireN... | Does Scala has intermediate/terminal ops as Java8 has ? |
Java | Following https : //developer.atlassian.com/bamboodev/bamboo-tasks-api/executing-external-processes-using-processservice I would like to invoke some command using ProcessService bean . The injection as described in the link , does not work . I checked the source of several other plugins at Bitbucket , but each is using... | import com.atlassian.bamboo.process.ProcessService ; public class CheckTask implements TaskType { private final ProcessService processService ; public CheckTask ( @ NotNull final ProcessService processService ) { this.processService = processService ; } | Bamboo ProcessService bean does not exist ? |
Java | I knew one can prevent the code formatting in eclipse by surrounding the code withBut I do n't want to write it manually all the time . It would be perfect just mark the code , press a hotkey and the code gets prevented from formatting.Anybody knows how ? Thx ! | // @ formatter : off// my awesome formatted code ... public Set < Person > transformCustomersToPersons ( List < Customer > customers ) { Set < Person > persons = new HashSet < Person > ( ) ; for ( Customer customer : customers ) { persons.add ( new Person ( customer.getFirstname ( ) , customer.getLastname ( ) , custome... | Prevent Code-Formatting in Eclipse by HotKey |
Java | The easiest way to convert a Java Collection to a Scala equivalent is using JavaConversions , since Scala 2.8.. These implicit defs return wrappers for the contained Java Collection . Scala 2.9 introduced parallel collections , where operations on a collection can be executed in parallel and the result collected later ... | myCollection.par | How to create a Scala parallel collection from a Java collection |
Java | Lets say I have two observable streamsHow can I join these on when they have an attribute that matches ? Something like the psudo code below : | Observable < Book > books ; Observable < Movie > movies ; Observable < BookMoviePair > pairs = books.join ( movies ) .where ( ( book , movie ) - > book.getId ( ) == movie.getId ( ) ) ) .return ( ( book , movie ) - > new BookMoviePair ( book , movie ) ) ; | RxJava join observable streams by matching attribute value |
Java | Can I instantiate a concrete Java class that uses recursive generics in Kotlin , if so then how ? DetailsI am trying to instantiate a Java class that uses recursive generics similar to the example below . I found a work around for wrapping the Java class in a new class , but that feels like I am sidestepping a problem ... | public class MyLegacyClass < T extends MyLegacyClass < T > > { // implementation ... } // In Java we just ignore the generic type ... MyLegacyClass myLegacyClass = new MyLegacyClass ( ) ; class myClass { // Error : One type argument expected for class ... val x : MyLegacyClass = MyLegacyClass ( ) // Still 'Error : One ... | Instantiate a concrete Java class that uses recursive generics in Kotlin |
Java | I am trying to understand what the following means ? What is the advantage of doing something like this ( e.g . use-case ? ) . | public class Bar < T extends Bar < T > > extends Foo < T > { //Some code } | Java generics syntax |
Java | I have the following available methods in a Utils class : And in a method of myClass I have : The second piece of code has a compilation error : The method withTx ( Function < OrientGraph , Object > ) is ambiguous for the type myClassI guess this comes from the compiler , which is not able to determine if the lambda is... | protected < U > U withTx ( Function < OrientGraph , U > fc ) { // do something with the function } protected void withTx ( Consumer < OrientGraph > consumer ) { withTx ( g - > { consumer.accept ( g ) ; return null ; } ) ; } withTx ( g - > anotherMethod ( g ) ) ; withTx ( g - > { anotherMethod ( g ) ; } ) ; | Disambiguate overloaded methods that accept different functional interfaces |
Java | Mouse events and scroll events behave in different waysMouse Events : The event is captured by mainStageThe event is captured by mainStageThe event is not capturedScroll Events : The event is captured by mainStageThe event is captured by secondStageThe event is not capturedIs there any way that transparent secondStage ... | Pane mainPane = new Pane ( new Label ( `` Main Stage '' ) ) ; mainPane.setPrefSize ( 300 , 300 ) ; mainStage.setScene ( new Scene ( mainPane ) ) ; Stage secondStage = new Stage ( ) ; Pane secondPane = new Pane ( new Label ( `` Second Stage '' ) ) ; secondPane.setBackground ( new Background ( new BackgroundFill ( Color.... | Transparent JavaFX stage capture scrolling events if there is another window behind |
Java | Can someone imagine when this code : should become this : ( In our company we have a Sonar rule that forces such coping or arguments for all methods . ) I can imagine why it can be important for standard methods , but I can not find any benefit of having it done at a start of tools main method . Am I missing something ... | public static void main ( final String [ ] args ) { // do something } public static void main ( final String [ ] args ) { String [ ] argsCopy = doCopy ( args ) ; // do something } | should MAIN method copy input arguments ? |
Java | I have a problem when trying to persist a data model class into a database . I have a class like this : The second field was added after first one . When to persist object created with this class via : A new row in database is created , but only with first field added . The second one is empty . When I am debugging the... | class DataModelClass { //some more field etc . @ Column ( name = `` number1 '' , nullable = true ) private Integer number1 ; @ Column ( name = `` number2 '' , nullable = true ) private Integer number2 ; public DataModelClass ( ) { } ( ... ) public Integer getNumber2 ( ) { return number2 ; } public void setNumber2 ( Int... | Can not persist data model 's field into database , but can retrieve it |
Java | Abstract : I would like to interact with two classes ( 'Item ' and 'Block ' ) that share many similar functions as if they were implemented from an interface with these functions , however they are not and I can not edit them . What are my options for dealing with this ? Am I stuck writing super hacky code ? Details : ... | public interface ItemOrBlockAdapter { public String myGetUnlocalizedName ( ) ; public ItemOrBlockAdapter mySetCreativeTab ( CreativeTabs tab ) ; } public class BlockAdapter extends Block implements ItemOrBlockAdapter { protected BlockAdapter ( String uid , Material m ) { super ( m ) ; GameRegistry.registerBlock ( this ... | Forcing two similar classes to behave as if they were polymorphic in Java |
Java | Consider : I found no way to express that I mean the X from Bar < X > and not Foo.X in the foobar ( X t ) implementation . Is there no other way than renaming the generic parameter X in Bar or the static inner class ? | public interface Foo < T > { public static class X { } public void foobar ( T t ) ; } public class Bar < X > { Foo < X > foo = new Foo < X > ( ) { public void foobar ( X t ) { } } ; } | Generics name clash |
Java | I am developing a programming tool on the Netbeans Platform.In that , I have an action to find usages and I want to add Alt + F7 as a shortcut to fire my action . I have implemented this for Alt + F3 and some other shortcuts . But in this case , Alt + F7 is already used in the Netbeans Platform to find usages . How can... | @ ActionRegistration ( displayName = `` # CTL_FindUsagesAction '' ) @ ActionReferences ( value = { @ ActionReference ( path = `` Shortcuts '' , name = `` A-F7 '' ) , | Add Alt + F7 as shortcut to an action in Netbeans platform |
Java | How is one supposed to document Java Record parameters ? I am referring to the parameters that end up becoming constructor parameters , class fields.I tried : but IntelliJ IDEA flags @ params as an error . I could n't find an online example of how this is supposed to work . The closest discussion I found is https : //b... | /** * @ param name the name of the animal * @ param age the age of the animal */public record Animal ( String name , int age ) { } | How to document Java Record parameters ? |
Java | Against this pattern designThe only , I guess , with method ( ) in Base I can get the specific type.Are there more benefits ? | interface Base < T extends Base > { T method ( ) ; } interface Base { Base method ( ) ; } | What is the benefit of this design pattern ? |
Java | The javax.activation.MimeType class does not compare intuitively ( to me ) due to a lack of an overridden equals-method . Consider the following snippet ; It seems to me that a and b are equal in every aspect and that a.equals ( b ) should return true.Is there a reason that this class does not implement an equals-metho... | MimeType a = new MimeType ( `` image/png '' ) ; MimeType b = new MimeType ( `` image/png '' ) ; a.equals ( b ) ; // falsea.toString ( ) .equals ( b.toString ( ) ) ; // truea.getBaseType ( ) .equals ( b.getBaseType ( ) ) ; // truea.getSubType ( ) .equals ( b.getSubType ( ) ) ; // truea.getParameters ( ) .size ( ) ; // 0... | Why does javax MimeType not implement equals ? |
Java | This question goes from my previous post in here.. Before I post my question , I am pasting the contents from oracle docs ; My understanding of type erasure when overriding is involved is as follows : if after erasure , the signature of m1 and m2 are same , then then they are considered overridden.so in my previous pos... | 8.4.8.1 . Overriding ( by Instance Methods ) An instance method m1 , declared in class C , overrides another instance method m2 , declared in class A iff all of the following are true : C is a subclass of A . The signature of m1 is a subsignature ( §8.4.2 ) of the signature of m2.8.4.2 . Method Signature The signature ... | how does erasure handles overriding scenarios in Java ? |
Java | This question may be a little bit subjective , but I 'm just trying to follow the best programming practices for organization of code.I have a class Polynomial that makes a lot of reference to the class Rational , and in many different methods it uses a Rational value that is equivalent to 1 , 0 , or -1 for comparisons... | public static final Rational ZERO = new Rational ( 0 ) ; public static final Rational ONE = new Rational ( 1 ) ; public static final Rational NEG_ONE = new Rational ( -1 ) ; | Java Code Organization : Where to keep instance of static class |
Java | I really do n't know how to explain this error properly ... It started when I added this method to my controller class : And I 've confirmed that without this method ( which is called on by a class , on start up of the program ) I do n't have an error.My error ? When I run from eclipse , the programe starts to load the... | public void loadPlayerComboBox ( ) { try { final PreparedStatement collectPlayerNames = ConnectionManager.getConnection ( ) .prepareStatement ( `` SELECT `` +PLAYER_NAME+ '' FROM PLAYERS '' ) ; final ResultSet playerNameResults = collectPlayerNames.executeQuery ( ) ; while ( playerNameResults.next ( ) ) { IViewManager.... | Bizarre Java error/bug : Stack Overflows , null pointers and double locking |
Java | I have a Java class with multiple `` type '' values , and a class which can take one of those types.I 'm trying to change the implementation of the constructor depending the Type enum using Java 's type system , but ca n't find any information on how to do it.Is something to this effect possible in Java ? Like it is in... | public enum Type { A , B , C } public class Action { public Action ( Type.A type , String value ) { } public Action ( Type.B type , Float value ) { } public Action ( Type.C type , String value ) { } } | Java function signature accept single enum value |
Java | Having this method : Can I access the static variables of the class ? | readAllTypes ( Class clazz ) { ... } | Can I access the static variables of the 'Class ' Object ? |
Java | I 'm new to programming and Java . I 've noticed that , in the Java API , there are methods with strange assignments inside if statements . Here is an example from the Map interface : Is there some sort of benefit to nesting the assignment this way ? Is this purely a style choice ? Why not just do the assignment when c... | default V replace ( K key , V value ) { V curValue ; if ( ( ( curValue = get ( key ) ) ! = null ) || containsKey ( key ) ) { curValue = put ( key , value ) ; } return curValue ; } // why not do it like this ? default V replace ( K key , V value ) { V curValue = get ( key ) ; // not nested if ( curValue ! = null || cont... | Why does Java API have seemingly strange assignments inside if statements ? |
Java | I have an swing panel with a JLabel inside of it . The JLabel looks like this : However it displays in the UI like the following : Bar Foo BarFor some reason , the first line just disappears . If I take out the slash or remove the html tags , it works as expected . Is there a way to make the first line show up with the... | new JLabel ( `` < html > /Foo < br/ > /Bar < br/ > /Foo < br/ > /Bar < /html > '' ) ; | Why does JLabel not display '/ ' when it is the first character ? |
Java | The following simple examples cause compile-time error . But It 's not clear why. -- and -- DEMOBut the following works fine : Does it allow to tranfer control to the only while , for or do statement ? It does n't say in the JLS . What it actual says is : A continue statement with label Identifier attempts to transfer ... | public static void main ( String [ ] args ) throws java.lang.Exception { int i = 0 ; d : { System.out.println ( `` d '' ) ; } while ( i < 10 ) { i++ ; continue d ; } } public static void main ( String [ ] args ) throws java.lang.Exception { int i = 0 ; d : { System.out.println ( `` d '' ) ; while ( i < 10 ) { i++ ; con... | Labeled continue statement within while loop |
Java | Good ol ' JOptionPane contains a plethora of static methods . There are many combinations , yet to change certain options ( like buttons ) you still must specify other optional arguments - often defaults ( like a null icon ) . This does n't lead to easy to read code.Moreover the methods are n't particularly consistent ... | String [ ] buttonText = { `` Looks good '' , `` It sucks '' } ; Object selection = new OptionPaneBuilder ( `` What do you think ? '' ) .question ( ) .message ( messageComponent ) .resizable ( true ) .showOptionDialog ( parent , buttonText ) ; return buttonText [ 0 ] .equals ( selection ) ; // returns int ( or enum ? ) ... | Does anyone know of code that wraps JOptionPane using the builder pattern ? |
Java | I 'm looking for a regex that will split a string as follows : with the output resulting in : The string is split at every character . However , if there are digits next to each other , they should remain grouped in one string . | String input = `` x^ ( 24-3x ) '' ; String [ ] signs = input.split ( `` regex here '' ) ; for ( int i = 0 ; i < signs.length ; i++ ) { System.out.println ( sings [ i ] ) ; } `` x '' , `` ^ '' , `` ( `` , `` 24 '' , `` - '' , `` 3 '' , `` x '' , `` ) '' | Regex for splitting at every character but keeping numbers together |
Java | In the life-cycle of my application , I have to re-create an ArrayList that contains other ArrayLists of objects ( reading them from storage ) . The ArrayList is always assigned to the same data member in a class , essentially leaving the older ArrayList-of-ArrayLists dangling ( unreference-able or inaccessible ) .My u... | for ( InnerArray aList : outerArray ) aList.clear ( ) ; outerArray.clear ( ) ; | Does this form of memory management make sense at all in Java ? |
Java | I have an IDevice interface and two enum realizations of this interface : AndroidDevice and IosDevice.The issue is : I want to use latent typing and call values ( ) method on an interface reference : So I have to add public IDevice [ ] values ( ) ; to my interface : But it does n't work . Eclipse asks me to remove stat... | private IDevice getDeviceByReadableName ( String versionInXml , IDevice devices ) { for ( IDevice device : devices.values ( ) ) { // ... public interface IDevice { // ... public IDevice [ ] values ( ) ; } | Latent typing using interface and Enum |
Java | The following code compiles and runs successfully without any exceptionshould n't the line ArrayList < SuperSample > ssList = ( ArrayList < SuperSample > ) o ; produce a ClassCastException ? while the following code produces a compile time error error to prevent heap pollution , should n't the code mentioned above hold... | import java.util.ArrayList ; class SuperSample { } class Sample extends SuperSample { @ SuppressWarnings ( `` unchecked '' ) public static void main ( String [ ] args ) { try { ArrayList < Sample > sList = new ArrayList < Sample > ( ) ; Object o = sList ; ArrayList < SuperSample > ssList = ( ArrayList < SuperSample > )... | should n't this code produce a ClassCastException |
Java | I was writing a Sieve-type function in Clojure based on Sieve of Eratosthenes ... ..and came across an error with lists of pairs : ClassCastException clojure.lang.Cons can not be cast to java.lang.Number clojure.lang.Numbers.remainder ( Numbers.java:171 ) However , changing the marking style , giving up on cons and usi... | ( defn mark-true [ n ] ( cons n ' ( true ) ) ) ( defn unmarked ? [ ns ] ( not ( list ? ns ) ) ) ( defn divides ? [ m n ] ( if ( = ( mod n m ) 0 ) true false ) ) ( defn mark-divisors [ n ns ] ( cond ( empty ? ns ) ' ( ) ( and ( unmarked ? ( first ns ) ) ( divides ? n ( first ns ) ) ) ( cons ( cons ( first ns ) ' ( false... | Collection of pairs in Clojure using cons |
Java | I encountered with the case when I need to convert List < Book > to Map < String , Book > and the only solutions I can find is how to do Map < String , List < Book > > .The class itself looks the following way ( I ommitted getters/setters and constructors ) : I want to map all books by certain unique keys , so probabil... | public class Book { private String asin ; private String author ; private String title ; } Map < String , Book > booksByAsinAndTitle = books.stream ( ) .collect ( Collectors.groupingBy ( ( book ) - > book.getAsin ( ) + `` || '' + book.getTitle ( ) ) ) .entrySet ( ) .stream ( ) .collect ( Collectors.toMap ( x - > x.getK... | How to create List < T > to Map < String , T > instead of Map < String , List < T > > ? |
Java | What 's the advantage of this OpenJDK line number 1455.Code snippet : Notice that , although a reference to private final char value [ ] is copied to the local val for access inside the loop , its .length field is still accessed through value , not val.I suspect `` performance '' to be the answer ( e.g . it is faster t... | private final char value [ ] ; // ... public int hashCode ( ) { int h = hash ; if ( h == 0 & & value.length > 0 ) { char val [ ] = value ; // < -- - this line for ( int i = 0 ; i < value.length ; i++ ) { h = 31 * h + val [ i ] ; } hash = h ; } return h ; } | Why copy a field reference to a local before using it in a loop ? |
Java | when you have a method , I understand that it makes sense to declare it generic so that i can take generic arguments . Like this : But what exactly is the idea behind making a whole class generic if I can simply declare every method generic ? | public < T > void function ( T element ) { // Some code ... } | What is the point of making a class generic ? |
Java | Its pretty basic UI , but I can not setup the JCheckBox buttons so that they are placed immediately after one another ( vertically ) without any spacing . How would I reduce the spacing seen below ? | JPanel debugDrawPanel = new JPanel ( new GridLayout ( 0,1 ) ) ; JPanel eastPanel = new JPanel ( new GridLayout ( 1,0 ) ) ; JTabbedPane tab = new JTabbedPane ( ) ; click = new ClickPanel ( this ) ; setSettings ( new Settings ( ) ) ; for ( Setting setting : getSettings ( ) .getAll ( ) ) { JCheckBox checkBox = new JCheckB... | Remove huge gaps between check boxes on panel |
Java | What is the best way to put javascript/html/css code in the maven repository , so that is easily usable by java projects.Is there a way to do it such that the included project can be easily made `` web-visible '' by the including project ? For example assume I write a very useful tricks.js file an put it in the mvn rep... | < script src= '' /some/thing/tricks.js '' / > | best practice : how to host server-side code in the maven repository |
Java | I was looking at a way to optimize some things in our code base with generic functions . There is a function with return type List < Object > which could have return type List < SpecifiedType > .Bellow is a minimalist version of that function called function . It takes a parameter type , based on it calls a correspondi... | public static ArrayList < String > forString ( ) { ArrayList < String > res = new ArrayList < > ( ) ; // Fetching and processing data specific to String return res ; } public static < T > ArrayList < T > forGeneric ( Class < T > type ) { ArrayList < T > res = new ArrayList < > ( ) ; // Fetching data return res ; } publ... | Java redundant casts required in generic method |
Java | The above code will not compile without : If i remove it , I get the following errorCan someone explain this ? It seems like I am starting with and IntStream , converting to a Stream of Characters and then back to IntStream . | public static int construction ( String myString ) { Set < Character > set = new HashSet < > ( ) ; int count = myString.chars ( ) // returns IntStream .mapToObj ( c - > ( char ) c ) // Stream < Character > why is this required ? .mapToInt ( c - > ( set.add ( c ) == true ? 1 : 0 ) ) // IntStream .sum ( ) ; return count ... | Why do I need to map IntStream to Stream < Character > |
Java | I 'm new to java ( 2 weeks ) and I 'm trying to convert a inputted string in to ascii code and trying to print the sum.I 've tried using IntStream.of ( AsciiArray ) .sum but since its a string and not an int it does n't work ( Understandably ) example of what I 'm trying to do : `` Enter a 5 letter word ( all lower cas... | import java.util.Arrays ; import java.util.Scanner ; public class Strings { public static void main ( String [ ] args ) { Scanner input = new Scanner ( System.in ) ; System.out.println ( `` Enter a 5 letter word ( all lower case ) : `` ) ; String word = input.nextLine ( ) ; int length = word.length ( ) ; byte [ ] bytes... | How do find the sum of an ascii array ? |
Java | I 'm frequently running into performance issues when I XSL transform large amounts of data into HTML . This data is usually just a couple of very large tables of roughly this form : During transformation , I want to visually group the records like thisA silly implementation is this one ( set is from http : //exslt.org ... | < table > < record > < group > 1 < /group > < data > abc < /abc > < /record > < record > < group > 1 < /group > < data > def < /abc > < /record > < record > < group > 2 < /group > < data > ghi < /abc > < /record > < /table > + -- -- -- -- -- -- -- +| Group 1 |+ -- -- -- -- -- -- -- +| abc || def |+ -- -- -- -- -- -- --... | How to avoid O ( n^2 ) complexity when grouping records in XSLT ? |
Java | I have created an API which allows users to build out queries using a tree . The tree is built from the SearchOperationRequest class.So from this example I could create a SearchOperationRequest that asks for all WHERE hidden = false AND X = 88This request is built into a specification using a generic specification buil... | @ Data @ ApiModel ( value = `` SearchOperationRequest '' , description = `` Condition for the query '' ) public class SearchOperationRequest { @ ApiModelProperty ( value = `` Conditional statement for the where clause '' , allowableValues = `` EQUALS , NOT_EQUALS , GREATER_THAN , LESS_THAN , LIKE , STARTS_WITH , ENDS_W... | Build JPA Specification from tree |
Java | I 'm currently stuck on a problem from CodeAbbey . I do n't want an answer to the entire thing.This is the meat of the question : Input data will have : initial integer number in the first line ; one or more lines describing operations , in form sign value where sign is either + or * and value is an integer ; last line... | char c = src.charAt ( 2 ) ; import java.util.Scanner ; public class Challenge14 { static Scanner in = new Scanner ( System.in ) ; public static void main ( String [ ] args ) { System.out.println ( `` Enter Your first number : `` ) ; int x = in.nextInt ( ) ; for ( int i = 0 ; i < 7 ; i++ ) { String [ ] s = new String [ ... | Modular calculator getting data inside a String array |
Java | Stumbled upon incompatible types error cause of which I do n't understand.Why is this piece of code wrong ? | List < List < String > > a = new ArrayList < > ( ) ; List b = a ; // is okList < List > c = a ; // incompatible types | Generics incompatible types |
Java | I 'd like to write a java framework , that supports JRE7 as a baseline , but takes advantage of JRE8 features , if being run in the context of a JRE8 ( upwards compatible ? ? ) . ( Or maybe I have this backwards ... i.e . JRE8 is the baseline , but degrades gracefully to support JRE7 ) .Does Java provide a way to do th... | public class Index { void tellme ( String yourname ) { /* ... */ } public static void main ( String [ ] args ) throws Exception { Method tellme = Index.class.getDeclaredMethod ( `` tellme '' , String.class ) ; Method java8Params = null ; try { java8Params = Method.class.getMethod ( `` getParameters '' ) ; } catch ( NoS... | How do I programmatically perform feature detection in Java ? |
Java | I hope some one can help me , this is what I want to do.I have a JTextPane and I want to take a screenshot to that specific JTextPane coordinates and size , so far I can do a screenshot with the size of the JTextPane but I ca n't get the specific coordinates my screenshots always gets the ( 0,0 ) coordinates.This is my... | void capturaPantalla ( ) { try { int x = txtCodigo.getX ( ) ; int y = txtCodigo.getY ( ) ; Rectangle areaCaptura = new Rectangle ( x , y , txtCodigo.getWidth ( ) , txtCodigo.getHeight ( ) ) ; BufferedImage capturaPantalla = new Robot ( ) .createScreenCapture ( areaCaptura ) ; File ruta = new File ( `` P : \\captura.png... | Coordinates of a JTextPane to make a Screenshot in Java |
Java | This is n't a major issue , but I do n't understand why this happens , so I figured I 'd post it here . This is my code : The code runs fine except for one thing . The error message Make sure to enter a number . sometimes displays after the menu , sometimes before , sometimes in the middle of the menu . This is the out... | do { printMenu ( ) ; //method to print menu try { user=input.nextInt ( ) ; } catch ( InputMismatchException imme ) { System.err.println ( `` Make sure to enter a number . `` ) ; input.next ( ) ; continue ; } switchMenu ( user ) ; //method with switch method for user input } while ( 1 < 2 ) ; 1 . Book a ticket2 . Cancel... | Java - Error-message displaying incorrectly |
Java | I have code that extracts some specific large ( about 15k entries ) binary serialized file archive to folder on disk.extractExact function calls for every entry in archive.after this , if I try to call Files.delete ( < archive_file_path > ) method - I will get an exception : java.nio.file.FileSystemException : The proc... | public void extractExact ( Path absolutePath , DoubleConsumer progressConsumer ) throws IOException { ... // Extract to file channel try ( final FileOutputStream fos = new FileOutputStream ( absolutePath.toFile ( ) ) ) { PakExtractor.Extract ( pakFile , Entry , fos.getChannel ( ) , progressConsumer ) ; } } | FileOutputStream try-with-resources does n't close file descriptor |
Java | I have two ArrayLists ( list1 & list2 ) . I would like to see if any 1 ( or more ) of the objects in list2 ( which are strings ) occur in list1.So , for some examples : However , the method containsAll ( ) does not work in this use case , as 1234 does not occur in list1 , and will result in a result of false , also con... | List < String > list1 = Arrays.asList ( `` ABCD '' , `` EFGH '' , `` IJKL '' , `` QWER '' ) ; List < String > list2 = Arrays.asList ( `` ABCD '' , `` 1234 '' ) ; //Should result in true , because `` ABCD '' is in list 1 & 2 ArrayList list1 = { 1 , 2 , 3 , 4 , 5 } ArrayList list2 = { 1 , 2 , 3 } -- > TrueArrayList list2... | ArrayList contains one or more entities from another ArrayList |
Java | I 've got something along the lines of the following : How do I modify that so that I can do the following instead ? | public class A { public void theMethod ( Object arg1 ) { // do some stuff with a single argument } } public class B { public void reflectingMethod ( Object arg ) { Method method = A.class.getMethod ( `` theMethod '' , Object.class ) ; method.invoke ( new A ( ) , arg ) ; } } public class A { public void theMethod ( Obje... | Java reflection when a method has a variable arglist |
Java | Just curious about the directory layout for the JDK . So there are two separate java.exe files - one is in : and one is in : Why does there need to be two files ? The motivation for this question arises from some challenge I 'm having installing a program ( SQL Developer ) . | C : \Program Files ( x86 ) \Java\jdk1.7.0_45\bin C : \Program Files ( x86 ) \Java\jdk1.7.0_45\jre\bin | In the Java install directory , why are there multiple java.exe files ? |
Java | I 'm new to generics , so not sure where I 'm going wrong ... I have classes , called Cat , Dog and Rabbit , which implement the interface Animal.The following code will compileBut the following code will notThe compiler says the types are incompatible . Where am I going wrong ? UPDATEThanks for everyone 's helpI 've c... | Set < ? extends Animal > animalSet ; Set < Dog > dogSet = new HashSet < Dog > ( ) ; animalSet = dogSet ; Map < String , Set < ? extends Animal > > animalMap ; Map < String , Set < Dog > > dogMap = new HashMap < String , Set < Dog > > ( ) ; animalMap = dogMap ; // this line will not compile Map < String , ? extends Set ... | Generics - Java collection within a collection |
Java | We have this code in many places where we swap integers if one value is higher than the other . Is there a way to re-factor this code , so it can be re-used ? | int numerator2 = < some random number > ; int denominator2 = < some random number > ; if ( numerator2 > denominator2 ) { int temp = denominator2 ; denominator2 = numerator2 ; numerator2 = temp ; } | Is there a way to code re-factor swapping integers |
Java | We are looking to migrate from Maven to Gradle , and have worked through most of the challenges you would expect for replacing the parent POM concept . There is one sticky point that we have n't figured out yet . We need to specify the version of Spring Boot we are using globally , but I run into invalid build file pro... | repositories { mavenLocal ( ) /* Removed our internal repositories */ jcenter ( ) mavenCentral ( ) } apply plugin : 'java'apply plugin : 'jacoco'apply plugin : 'maven-publish'apply plugin : 'io.spring.dependency-management'group = 'nedl-unified-platform'/* Required to publish Spring Boot microservices to publish to rep... | How do you parameterize the Spring Boot Gradle plugin ? |
Java | Let 's say you have a Client and a Server that wants to share/synchronize the same Models/Objects . The models point to each other , and you want them to keep pointing at the same object after being sent/serialized between the client and the server . My current solution roughly looks like this : But i 'm not too satisf... | class Person { static Map < Integer , Person > allPeople ; int myDogId ; static Person getPerson ( int key ) { return allPeople.get ( key ) ; } Dog getMyDog ( ) { return Dog.getDog ( myDogId ) ; } } class Dog { static Map < Integer , Dog > allDogs ; int myOwnersId ; static Dog getDog ( int key ) { return allDogs.get ( ... | Pattern/Library for sending objects over network , keeping pointers |
Java | I have a BigDecimal amount that I want to cast to Long if it is not null , but I got a java.lang.NullPointerException exception doing : | BigDecimal bgAmount = getAmount ( ) ; long totalSupplyFilterMin = Optional.ofNullable ( bgAmount.longValue ( ) ) .orElse ( Long.MIN_VALUE ) ; | Optional and casting at the same time |
Java | First I declare a class : Now I execute the expression in REPL : and it outputsBut why does n't the method *** go first ? Is n't the priority of *** higher than +++ ? And how about Java and C ? Is it the same as in Scala ? | class Op ( var x : Int ) { def +++ ( op : Op ) = { println ( this.x + `` +++ `` + op.x ) this.x += op.x this } def *** ( op : Op ) = { println ( this.x + `` *** `` + op.x ) this.x *= op.x this } } op1 +++ op2 +++ op3 *** op4 | The method execution puzzle in Scala |
Java | Sample testThe strange result : Why this differs ? | @ Testpublic void should_be_equals ( ) { LocalDate now = new LocalDate ( 2015,01,29 ) ; assertThat ( now.plusMonths ( 1 ) .plusMonths ( 1 ) ) .isEqualTo ( now.plusMonths ( 2 ) ) ; } org.junit.ComparisonFailure : Expected :2015-03-29Actual :2015-03-28 | JodaTime : plusMonths ( 1 ) two times differ from plusMonths ( 2 ) |
Java | I have a little issue with my Collision Detection System for a Game.In the game are several structures which connect to each other . However they should not connect when there is another structure in between them.For some weird reason it sometimes fails to connect to directly adjacent structures when there is a structu... | public void drawConnections ( Graphics g ) { ArrayList < EnergyContainer > structurecopy = ( ArrayList < EnergyContainer > ) Mainclass.structures.clone ( ) ; //all structures in a list structurecopy.remove ( this ) ; //as we are member of the list structurecopy.removeIf ( t - > ( ! hasStructureInRangeWithoutObstaclesIn... | Collision Detection Issues |
Java | A Sample can be deleted if status is S or P. I have this tests : Should I go further ? How should I test when the sample ca n't be deleted ? For example : Is this test useful ? What about the test naming ? Would be this logic tested enough ? | @ Testpublic void canBeDeletedWhenStatusIsP ( ) { Sample sample = new Sample ( ) ; sample.setState ( `` P '' ) ; assertTrue ( sample.canBeDeleted ( ) ) ; } @ Testpublic void canBeDeletedWhenStatusIsS ( ) { Sample sample = new Sample ( ) ; sample.setState ( `` S '' ) ; assertTrue ( sample.canBeDeleted ( ) ) ; } @ Testpu... | Should I test cases in which nothing is expected to happen |
Java | I have added a chart in AnchorPane , and I want to get the bounds of its plot ( chart-plot , I have marked it with cyan color ) , so that I could add some texts on top of it , but I should know its exact bounds according to its ancestor ( s ) . If I do it manually , I may fail when the paddings ' size of the nodes will... | import javafx.application.Application ; import javafx.geometry.Side ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.chart.LineChart ; import javafx.scene.chart.NumberAxis ; import javafx.scene.layout.AnchorPane ; import javafx.stage.Stage ; public class Main extends Application { @ Override... | How to get node bounds according to its specific ancestor in JavaFX 8 ? |
Java | I have two questions : Question 1 : Is this in O ( n ) ? Does it matter how many loops ( not nested loops ) are in method1 ? Question 2 : What if there is ainside the method1 , what function is it ? | public static void method1 ( int [ ] a , int [ ] b ) { int sum1 = 0 , sum2 = 0 ; for ( int i = 0 ; i < a.length ; i++ ) { sum1 += a [ i ] ; } for ( int i = 0 ; i < b.length ; i++ ) { sum2 += b [ i ] ; } } Arrays.sort ( a ) ; | Confused about Big O notation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.