lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I have read http : //cr.openjdk.java.net/~briangoetz/lambda/lambda-state-4.html and noticed that all the examples have argument type declared explicitly , even though it 's already known from the interface-function declaration.Ca n't we go with justUPDATE : In the JSR-335 Draft , I have found that inferred-type paramet... | public interface FileFilter { /** ... **/ boolean accept ( File pathname ) ; } FileFilter java = ( File f ) - > f.getName ( ) .endsWith ( `` .java '' ) ; ( f ) - > f.getName ( ) .endsWith ( `` .java '' ) ; ? ( int x ) - > x+1 // Single declared-type parameter ( int x ) - > { return x+1 ; } // Single declared-type param... | Are there any reasons why specifying the argument type is required in Java 8 lambda syntax ? |
Java | I 've seen a bunch of examples on the internet that , in order to use the streams API to do parallel stuff , just call the .parallelStream ( ) method like this : But in other cases I 've seen the parallel stream being used inside a thread pool submition , like this : Does just calling parallelStream ( ) executes whatev... | mySet .parallelStream ( ) ... // do my fancy stuff and collect ForkJoinPool.commonPool ( ) .submit ( ( ) - > { mySet .parallelStream ( ) ... // do my fancy stuff and collect } ) | Does simply calling parallelStream run the tasks in parallel ? |
Java | The Java Stream.forEach function has the serious limitation that it 's impossible for its consumer to throw checked exceptions . As such , I would like to access a Stream 's elements one by one.I want to do something like this : However , findAny is a short-circuiting terminal operation . That is , it closes the stream... | while ( true ) { Optional < String > optNewString = myStream.findAny ( ) ; if ( optNewString.isPresent ( ) ) doStuff ( optNewString.get ( ) ) ; else break ; } | How to read a Stream one by one ? |
Java | here why is ex implicitly final ? What is the use of making ex implicitly final ? | catch ( IOException|SQLException ex ) { logger.log ( ex ) ; throw ex ; } | Why is the catch parameter implicitly final ? |
Java | The following code compiles using JDK6 ( I tried 1.6.0_24 ) But compiling under JDK7 ( e.g . 1.7.0 ) , I get this error : Can anyone point as to whether this was an intentional change to Java 's generics ? | class XY < A extends XY < A , B > , B extends XY < B , A > > { } XY.java:1 : error : type argument B is not within bounds of type-variable Aclass XY < A extends XY < A , B > , B extends XY < B , A > > { ^ where B , A are type-variables : B extends XY < B , A > declared in class XY A extends XY < A , B > declared in cla... | Mutually self-referencing type parameters compiling under JDK6 but not 7 ? |
Java | I guess I might be missing something obvious here , but anyway lets see the code.On Running this you will get a output as following : I can see super is referring to FreeMap , not TreeMap , if it would have thrown a StackOverflow Exception I could have understood . Why nullpointerexception ? Thanks in advance | public static class FreeMap extends TreeMap < String , Integer > { @ Override public Integer put ( String key , Integer value ) { out.println ( super.toString ( ) ) ; out.println ( super.getClass ( ) .getName ( ) + '' `` +key+ '' : `` +value ) ; int i = super.put ( key , value ) ; //line 227 assert this.size ( ) == 1 ;... | The Subclass of java.util.TreeMap gives NullPointerException on call put ( key , value ) method |
Java | I have a bitmask to be stored in one byte , as I only need 8 bits . When I 'm creating it I do it as a String ( I thought it would be easier in this way ) and then I transform it to a byte with Byte.parseByte ( mask,2 ) , but I found it does not work for certain values : But if I do : There is no problem.PS : I found a... | String bits= '' 10000001 '' ; Byte.parseByte ( bits,2 ) ; // throws a NFE byte b= ( byte ) 0x81 ; //1000 0001 | Why Byte.parseByte ( `` 10000001 '' ,2 ) throws a NFE ? |
Java | I have a build.xml which imports other ant xml files . I 'd like to get all javac tasks from it so I can see what classpath is set to for these tasks ( javac is used at multiple targets ) . I came up with the following code ( simplified a bit ) : However , there are tasks like MacroDef which may have nested other tasks... | public static void main ( String [ ] args ) throws Exception { Project project = new Project ( ) ; project.init ( ) ; String build = `` build.xml '' ; File buildFile = new File ( build ) ; ProjectHelper.configureProject ( project , buildFile ) ; Hashtable < String , Object > ht = project.getTargets ( ) ; for ( String k... | Retrieving certain tasks programatically from an ant buildfile |
Java | Say I have a queue , and I want to exhaust it . The way I would do it is something likebut this feels like an archaic method.I would like something more like the forEach method . It is , of course , present - the Queue being a Collection - but it iterates over the elements , rather than consuming them.Ideally , I would... | void emptyQueue ( Queue < T > q ) { T i ; while ( ( i = q.poll ( ) ) ! = null ) consume ( i ) ; } | What is the idiomatic way to exhaust a Queue in Java 8 ? |
Java | I 'm trying take screenshot of a cardview which is in a DialogFragment . When I take a screenshot via Code . Top rounded corners are not showing but the bottom rounded corners are showing correctly . I saw these issues mentioned in the below Questions ... Cardview loses its radius when taken a screenshot programmatical... | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : id= '' @ +id/mainlinear '' android : layout_width= '' mat... | Cardview Rounded Corners are not showing up in Screenshot ? |
Java | I have a list of allowed custom annotations and I 'm trying to check whether a specific annotation is allowed by calling the contains method on the list.This works but Sonar complains about rule squid : S2175 . It says : A `` List < Class > '' can not contain a `` Class '' A couple Collection methods can be called with... | private boolean testClassContains ( ) { final List < Class < ? extends Annotation > > annotations = Arrays.asList ( MyAnnotation.class , YourAnnotation.class ) ; return annotations.contains ( YourAnnotation.class ) ; } | How to check if a List < Class > contains a Class while avoiding Sonar rule squid : S2175 |
Java | I have a quick question . The code block that starts right after the static keyword declaration , what type of method is that ? I have n't ever seen that before . If anyone could enlighten me , that would be greatly appreciated . Thanks . | public class Card { public enum Rank { DEUCE , THREE , FOUR , FIVE , SIX , SEVEN , EIGHT , NINE , TEN , JACK , QUEEN , KING , ACE } public enum Suit { CLUBS , DIAMONDS , HEARTS , SPADES } private final Rank rank ; private final Suit suit ; private Card ( Rank rank , Suit suit ) { this.rank = rank ; this.suit = suit ; }... | Unusual `` static '' method declaration |
Java | I have this class called Container : and the class called Token : and finally a test class for the Token classThe test compiles and runs just file in eclipse . When building on the commad linea compile error is raised : The compilation also fails when I change line 21 to one ofWhen I change the line to one ofcompilatio... | public class Container { private final Map < String , Object > map = new HashMap < > ( ) ; public void put ( String name , Object value ) { map.put ( name , value ) ; } public Container with ( String name , Object value ) { put ( name , value ) ; return this ; } public Object get ( String name ) { return map.get ( name... | Java compiler : How can two methods with the same name and different signatures match a method call ? |
Java | I have a problem when trying to convert bytes to String in Java , with code like : and the original bytes are not the same as the transferred bytes , which are respectively I once thought it is due to the UTF-8 charset mapping for the negative `` -3 '' . So I change it to `` -32 '' . But the transferred array remains t... | byte [ ] bytes = { 1 , 2 , -3 } ; byte [ ] transferred = new String ( bytes , Charsets.UTF_8 ) .getBytes ( Charsets.UTF_8 ) ; [ 1 , 2 , -3 ] [ 1 , 2 , -17 , -65 , -67 ] [ 1 , 2 , -32 ] [ 1 , 2 , -17 , -65 , -67 ] | What happens under the hood when bytes converted to String in Java ? |
Java | I am trying to port some java code to scala . The code uses annotations with a member called type however this is a keyword in scala . Is there a way to address this valid java member in scala ? Here is the Java codeThis part of the code is identical in scala except that type is a keyword so it does not compile . Is th... | @ Component ( name = `` RestProcessorImpl '' , type = mediation // Compile error ) public class RestProcessorImpl { // impl } package spike1 ; public class HasType { public String type ( ) { return `` the type '' ; } } class UseType { def hasType = new HasType hasType.type ( ) // Compile error } | Can not set a java annotation member called type in scala ? |
Java | http : //grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/ArrayList.java # 473My question is , why did they have to do an cycle through the backing array { O ( n ) } to make each element eligible for garbage collection when they could just have reinitialized the backing array , discarding... | public void clear ( ) { modCount++ ; // Let gc do its work for ( int i = 0 ; i < size ; i++ ) elementData [ i ] = null ; size = 0 ; } | Why Was java.util.Arraylist # clear implemented the way it was in OpenJDK ? |
Java | I know that double check locking without volatile variable is not safe based on this link http : //www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.htmlI want to simulate this situation at my home computer . I have standard jdk1.7 and multicore processor . But I am not able to simulate the broken behaviour . ... | class Foo { private Helper helper = null ; public Helper getHelper ( ) { if ( helper == null ) { synchronized ( this ) { if ( helper == null ) { helper = new Helper ( ) ; } } } return helper ; } } | How to break double checked locking without volatile |
Java | We have the following rules for our username validation : Username can have alphanumeric charactersUsername can have an underscore , hyphen or a periodFor now assume the username is in ASCII Username can not start or end with a periodUsername can not start , end or have any spacesWe have the following regex for the sam... | ^ ( ( [ a-zA-Z0-9 ] + [ _- ] * [ a-zA-Z0-9 ] * ) ( [ \\ . ] * [ a-zA-Z0-9 ] ) * ) + $ M45766235H.M96312865E @ EXAMPLE.COM import java.util.regex . * ; public class R { static final Pattern namePattern = Pattern.compile ( `` ^ ( ( [ a-zA-Z0-9 ] + [ _- ] * [ a-zA-Z0-9 ] * ) ( [ \\ . ] * [ a-zA-Z0-9 ] ) * ) + $ '' ) ; pub... | Regex for a username increases CPU consumption |
Java | I am using android studio 1.3 , and libgdx 1.6.2 to create a game . I want to incorporate google play services to my game and I have completed everything in one step , because I did it before without problem . However , this time it gave me an exception : So here is what I changed other than adding baseGameUtils ( whic... | java.lang.IllegalStateException : A fatal developer error has occurred . Check the logs for further information . at com.google.android.gms.common.internal.zzi $ zza.zzc ( Unknown Source ) at com.google.android.gms.common.internal.zzi $ zza.zzr ( Unknown Source ) at com.google.android.gms.common.internal.zzi $ zzc.zznQ... | Libgdx - IllegalStateException at unknown location |
Java | I 'm going over some source code and trying to figure out where _csrf came from . As far as I can guess , it looks like an implicit EL object . Maybe related to authentication and spring security.The below is the code that contains _csrf . What does $ { _csrf } do ? Is this an implicit EL object ? | < input type= '' hidden '' name= '' $ { _csrf.parameterName } '' value= '' $ { _csrf.token } '' / > | What does $ { _csrf } do ? Is this an implicit EL object ? |
Java | I was given the assignment to compare a pair of 3 positive double variables , while ignoring their order , in Java.I did the following : I 've heard from the teacher that there is a mathematical way of comparing this pair of 3 numbers.So far , I 've tried to compare their addition , subtraction , the sum of their power... | if ( ( a1 == a2 & & b1 == b2 & & c1 == c2 ) || ( a1 == a2 & & b1 == c2 & & c1 == b2 ) || ( a1 == b2 & & b1 == a2 & & c1 == c2 ) || ( a1 == b2 & & b1 == c2 & & c1 == a2 ) || ( a1 == c2 & & b1 == a2 & & c1 == b2 ) || ( a1 == c2 & & b1 == b2 & & c1 == a2 ) ) // if true | Matematical way to compare a pair of 3 variables |
Java | Can any one help me to get out of this exception . unexpected element ( uri : '' http : //cpps.xxx.com/splm-service '' , local : '' PartInquiryService '' ) . Expected elements are ( none ) Here is the code and xml i am usingHere is the xml am using it ..I will be getting this xml as a response from MQHere is the PartIn... | File file = new File ( `` PartInquiryService.xml '' ) ; JAXBContext jaxbContext = JAXBContext.newInstance ( PartInquiryService.class ) ; Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller ( ) ; PartInquiryService partInqService = ( PartInquiryService ) jaxbUnmarshaller.unmarshal ( file ) ; < PartInquiryServ... | Stuck up with JAXB - unmarshal XML exception |
Java | Can anyone explain this to me , does the += operator evaluate the right side first then it concatenate it with the left side ? | String str = `` Hello '' ; str += ( ( char ) 97 ) +2 ; // str = `` Hello99 '' ; str = str + ( ( char ) 97 ) +2 ; // str = `` Helloa2 '' ; | Strange behavior Java += operator |
Java | While reviewing for an exam I noticed I had written a logical error and I believe it is because of the compound assignment += because the Increment ++ executes as intended but it only occurs when assigning the value of foo to foo +1 or Here is the code.My question is why does foo+=foo+1 result in -1 ? Please Note : I a... | foo += foo + 1 ; //Break Statement Boolean exit = false ; int foo = 1 , bar = 60 ; while ( ! exit ) { foo+=foo+1 ; //Bad Code //foo++ ; //Good Code //foo=foo+1 ; // Good Code //foo+=1 ; // Good Code //System.out.println ( foo ) ; //Results in -1 ( Infinite Loop ) if ( foo == bar ) { break ; } System.out.println ( `` st... | Why does foo+=foo+1 in a loop result in -1 ? |
Java | I am using RestTemplate as my HttpClient to execute URL and the server will return back a json string as the response . Customer will call this library by passing DataKey object which has userId in it.Using the given userId , I will find out what are the machines that I can hit to get the data and then store those mach... | public class DataClient implements Client { private RestTemplate restTemplate = new RestTemplate ( new HttpComponentsClientHttpRequestFactory ( ) ) ; private ExecutorService service = Executors.newFixedThreadPool ( 15 ) ; public Future < DataResponse > getData ( DataKey key ) { DataExecutorTask task = new DataExecutorT... | How to follow Single Responsibility principle in my HttpClient executor ? |
Java | I 'm fairly new to Android development and I 've created my first `` real '' application that does the following : Launches MainActivityMainActivity processes Extra Data and then displays a ViewDialog that extends Dialog . ViewDialog has a showDialog ( ) method that does the following to setup and display the Dialog : ... | protected void showDialog ( final Activity activity ) { dialog = new Dialog ( activity ) ; dialog.requestWindowFeature ( Window.FEATURE_NO_TITLE ) ; dialog.setCancelable ( false ) ; dialog.setContentView ( dialog_layout ) ; // Set background color of the dialog ConstraintLayout currentLayout = ( ConstraintLayout ) dial... | Android Java : How do I prevent my Dialog box from showing MainActivity appname briefly when the Dialog closes ? |
Java | SummaryRecently we upgraded to Spring Data Elasticsearch 4.x . Part of this major release meant that Jackson is no longer used to convert our domain objects to json ( using MappingElasticsearchConverter instead ) [ 1 ] . This means we are now forced to add a new id field to all our documents.Previously we had domain ob... | import org.springframework.data.annotation.Id ; public ESDocument { @ Id private String id ; private String field1 ; @ JsonIgnore public String getId ( ) { return id ; } public String getField1 ( ) { return field1 ; } { `` _index '' : `` test_index '' , `` _type '' : `` _doc '' , `` _id '' : `` d5bf7b5c-7a44-42f9-94d6-... | Spring Data Elasticsearch ( 4.x ) - Using @ Id forces id field in _source |
Java | My problem is that I am using a class not developed by me ( I took it from Microsoft Azure SDK for Java ) . The class is called Node and you can see it here.As you can see the class is a generic class declared recursively like this : When I try to instantiate it I do n't know how to do it . I am doing this but I know I... | public class Node < DataT , NodeT extends Node < DataT , NodeT > > { ... } Node < String , Node < String , Node < String , Node < ... > > > > myNode = new Node < String , Node < String , Node < String , Node < ... > > > > ; | How to instantiate a generic recursive class in Java |
Java | I have the code like this : I can understand why str1.intern ( ) == str1 and str3.intern ( ) == str3 are true , but I do n't understand str2.intern ( ) == str2.Why this is false ? My java version is : 1.8.0_73 | String str1 = new StringBuilder ( `` 计算机 '' ) .append ( `` 软件 '' ) .toString ( ) ; System.out.println ( str1.intern ( ) == str1 ) ; //trueString str2 = new StringBuilder ( `` ja '' ) .append ( `` va '' ) .toString ( ) ; System.out.println ( str2.intern ( ) == str2 ) ; //falseString str3 = new StringBuilder ( `` Str '' ... | Why does the String.intern ( ) method return two different results ? |
Java | I made an implementation of Wagner Fischer algorithm in java with input cost , but I want to display all steps.I search but ca n't find any idea.After a long time I tried to keep each transformation in matrix alongside cost and to go through back to first solution then reverse it ... is this a good idea , if it is , ho... | kitten - > sitting1.replace k with s2.keep i3.keep t4.keep t5.replace t6.add g import java.io.File ; import java.io.FileNotFoundException ; import java.util.Scanner ; public class Principal { static int c1 , c2 , c3 ; static String word1 , word2 ; public static void main ( String [ ] args ) throws FileNotFoundException... | Wagner Fischer algorithm + display steps |
Java | According to my understanding , the following piece of code should result in a deadlock.The reason being , when thread t1 locks static object firstData , he has acquired a lock on the class . So , when he tries to lock another static object secondData , the request should block . However , the program runs fine and pri... | public class Deadlock { public static void main ( String [ ] args ) { Thread t1 = new Thread ( new DeadlockRunnable ( ) ) ; t1.start ( ) ; } } class DeadlockRunnable implements Runnable { static Object firstData = new Object ( ) ; static Object secondData = new Object ( ) ; public void run ( ) { synchronized ( firstDat... | Locking static members of a class |
Java | I 'm trying to download a pdf file using URLConnection . Here 's how I setup the connection object.I obtained inputstream from the connection object.And the output stream to write the file contents.BlockingQueue is created so that threads performing read and write operations can access the queue.Now created thread to r... | URL serverUrl = new URL ( url ) ; urlConnection = ( HttpURLConnection ) serverUrl.openConnection ( ) ; urlConnection.setDoInput ( true ) ; urlConnection.setRequestMethod ( `` GET '' ) ; urlConnection.setRequestProperty ( `` Content-Type '' , `` application/pdf '' ) ; urlConnection.setRequestProperty ( `` ENCTYPE '' , `... | PDF file download using BlockingQueue |
Java | I went through the default implementation of the new Java 8 Map methods like getOrDefault and noticed something slightly weird . Consider for example the getOrDefault method . It is implemented as follows.Now , the `` weird '' thing here is the `` Result of assignment used '' pattern in ( ( v = get ( key ) ) ! = null .... | default V getOrDefault ( Object key , V defaultValue ) { V v ; return ( ( v = get ( key ) ) ! = null ) || containsKey ( key ) ? v : defaultValue ; } default V getOrDefault ( Object key , V defaultValue ) { V v = get ( key ) ; return v ! = null || containsKey ( key ) ? v : defaultValue ; } public V getOrDefault ( java.l... | Java 8 Map default implementation details |
Java | Below are the 3 java classes which I am using for my android application development . I would like to add the student data ( name and phone number ) from the AddActivity to be stored in MainActivity page after clicking `` Add '' . I have researched on this and tried using an array . But I am quite confused on how the ... | public class MainActivity extends AppCompatActivity { ListView listView ; Button addStudent ; ArrayList < Student > students = new ArrayList < Student > ( ) ; protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; add ( ) ; } public vo... | How do I add data I have keyed in a EditText box into an array to list in another activity ? |
Java | I have a List < String > called lines and a huge ( ~3G ) Set < String > called voc . I need to find all lines from lines that are in voc . Can I do this multithreaded way ? Currently I have this straightforward code : Is there a way to search for few lines at the same time ? May be there are existing solutions ? PS : I... | for ( String line : lines ) { if ( voc.contains ( line ) ) { // Great ! ! } } | Parallelize search in a Java set |
Java | I 'm trying to write the following condition : How can I do it in a better way ? | if ( javaList.contains ( `` aaa '' ) ||javaList.contains ( `` abc '' ) ||javaList.contains ( `` abc '' ) ) { //do something } | How to check if any of multiple elements are in a List in a convenient way ? |
Java | I am trying to create a table class that extends ArrayList . In it , I would like to be able to create a map method that takes a lambda expression and returns a new table with the mapped values . I would also like to do this with filter . I use the map and filter a lot and I do n't like typing out the whole thing over ... | public abstract class Table < E extends Element > extends ArrayList < E > { // a lot of other stuff . public Table < E > map ( /*WHAT DO I PUT HERE ? */ mapper ) { return this.stream ( ) .map ( mapper ) .collect ( /*WHAT DO I PUT HERE ? */ ) ; } public Table < E > filter ( /*WHAT DO I PUT HERE ? */ predicate ) { return... | How do I add map and filter when I extend ArrayList in Java ? |
Java | When i tried to convert a String Object to boolean , the result is different.boolFlag ends up having a false value . | String strFlag= '' true '' ; boolean boolFlag = Boolean.getBoolean ( strFlag ) ; | String object to Boolean |
Java | If each of them is guaranteed to have a unique key ( generated andenforced by an external keying system ) which Map implementation isthe correct fit for me ? Assume this has to be optimized forconcurrent lookup only ( The data is initialized once during theapplication startup ) .Does this 300 million unique keys have a... | Map < String , < boolean , boolean , boolean , boolean > > | 300 million items in a Map |
Java | In Go , it is OK to call a method on a null pointer so long as that pointer is never dereferenced : ( For runnable code , click here ) In Java , however , calling a method on a null pointer , even if the method never dereferences any member variables , still causes a null pointer exception : Does anybody know why this ... | type empty struct { } func ( e *empty ) Allocated ( ) bool { return e ! = nil } class Test { public boolean Allocated ( ) { return this ! = null ; } } | Why ca n't you call a method on a null pointer in Java ? |
Java | I am developing JavaFx application in netbeans , in netbeans the project is building and running fine . I made a build ( mvn package ) from my project its finished without error but when I launch the program its not loading all the scenes and the FXMLLoader return with null value in this cases . All .fxml file in the s... | public class JavaFXApplication extends Application { public static final String TOOLBAR_MAIN = `` toolbarMain '' ; public static final String TOOLBAR_MAIN_FXML = `` /fxml/ToolbarMain.fxml '' ; public static final String TOOLBAR_SUB = `` toolbarSub '' ; public static final String TOOLBAR_SUB_FXML = `` /fxml/ToolbarSub.f... | Some scene not loading after maven build |
Java | Pure methods are those without side effects : their only effect is to return a value which is a function of their arguments.Two calls to the same pure method with the same arguments will return the same value . So , given two calls to a pure method with identical arguments , can HotSpot optimize away the second call , ... | int add ( int x , int y ) { return x + y ; } int addTwice ( int x , int y ) { return add ( x , y ) + add ( x , y ) ; } | Can HotSpot optimize away redundant calls to pure methods without inlining them ? |
Java | A friend of mine found this tidbit in the Java API ( https : //docs.oracle.com/javase/7/docs/api/java/lang/Enum.html ) , and by reading the following article https : //docs.oracle.com/javase/tutorial/java/generics/genTypes.html I could understand what the aforementioned line entailed syntactically but from the examples... | Class Enum < E extends Enum < E > > | Uses of recursive type bounds |
Java | I want to do this to protect the card from erasable or cloning the card . I read many documentsSome tell the user the fourth block to set permission to reading and write..According to @ Michael RolandThe authentication keys and the access conditions for each sector of a MIFARE card are located in the last block of that... | + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- + -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |+ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- + -- -- + -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+| Key... | Is it possible to lock command , protect cloning or not erasable by other app for MIFARE card 1k |
Java | Consider the following example code : When I now call new TestClass ( ) .doSth ( `` foo '' , `` bar '' ) I get the expected result A . But if I change the method signature of the first method by chaging the parameter l to a primitive type : calling new TestClass ( ) .doSth ( `` foo '' , 2L ) will yield a reference to c... | public class TestClass { public void doSth ( String str , String l , Object ... objects ) { System.out.println ( `` A '' ) ; } public void doSth ( String str , Object ... objects ) { System.out.println ( `` B '' ) ; } } public class TestClass { public void doSth ( String str , long l , Object ... objects ) { System.out... | Java overloading : reference to call ambiguous |
Java | If I have something like this : and I eventually make a SubClass object . Will x be true or false ? From http : //docs.oracle.com/javase/specs/jls/se5.0/html/execution.html # 12.5it looks like it will be false . | public class SuperClass { SuperClass ( ) { x = true ; } public boolean x ; } public class SubClass extends SuperClass { SubClass ( ) { x = false ; } } | When is a Java Implicit Constructor called compared to the Base Class Constructor ? |
Java | I use the OpenOffice API from my Java Program to handle Documents for me . Sometimes ( once every 100k or so calls ) the dispose method of a Document does not return , the CPU load stays at 100 % but nothing seems to happen.How should I act / code correctly in this situation ? My current approach is to wait for the dis... | XDesktop xDesk = ( ... ) // achive desktopxDesk.terminate ( ) ; Runtime.getRuntime ( ) .exec ( `` pkill soffice '' ) ; // `` taskkill /IM soffice '' on windows disposeThread.stop ( ) ; | Java : Method does not return . ( XComponent.dispose |
Java | There is the following code : It prints : 12.0This one does n't compile . Why ? | Integer time = 12 ; Double lateTime = 12.30 ; Boolean late = false ; Double result = late ? lateTime : time ; //Why here can I assign an Integer to a Double ? System.out.println ( result ) ; Integer time = 12 ; Double lateTime = 12.30 ; Double result = time ; //Integer can not be converted to DoubleSystem.out.println (... | Wrappers and Auto-boxing |
Java | Can you please explain this code snippet from HashMap constructor specifically the line capacity < < = 1 : | // Find a power of 2 > = initialCapacity198 int capacity = 1 ; 199 while ( capacity < initialCapacity ) 200 capacity < < = 1 ; | What does < < = operator mean in Java ? |
Java | In this answer I recommended usingbut two people complained that the result contained the string `` null '' , e.g. , 23.null . This could be explained by $ 1 ( i.e. , group ( 1 ) ) being null , which could be transformed via String.valueOf to the string `` null '' . However , I always get the empty string . My testcase... | s.replaceFirst ( `` \\.0* $ | ( \\.\\d* ? ) 0+ $ '' , `` $ 1 '' ) ; assertEquals ( `` 23 '' , removeTrailingZeros ( `` 23.00 '' ) ) ; | confusion in behavior of capturing groups in java regex |
Java | First of all I would like to clarify my understanding of the WeakReference as the following question depends on the same . The output of the above code isnulljava.lang.ref.WeakReference @ 7852e922Which means that although there is the actual person object is garbage collected once a GC runs , there is an object of Weak... | static void test ( ) { Person p = new Person ( ) ; WeakReference < Person > person = new WeakReference < > ( p ) ; p = null ; System.gc ( ) ; System.out.println ( person.get ( ) ) ; System.out.println ( person ) ; } static class Person { String name ; } static class PersonMetadata { String someData ; public PersonMetad... | How does a value in an entry in the WeakHashMap gets garbage collected when the actual object is garbage collected ? |
Java | I 'm trying to replace a reflective invocation with a MethodHandle , but varargs seem to be impossible to deal with.My reflective invoker currently looks like this : My current attempt at rewriting it looks like this ( the interface the Invoker exposes has to stay the same ) : And this works just fine in most cases . B... | public class Invoker { private final Method delegate ; public Invoker ( Method delegate ) { this.delegate = delegate ; } public Object execute ( Object target , Object [ ] args ) { return delegate.invoke ( target , args ) ; } } public class Invoker { private final Method delegate ; private final MethodHandle handle ; p... | How to invoke a MethodHandle with varargs |
Java | Before I ask for help , let me tell you what I did : Assuming I have a sampling rate of 8000Hz and sample size of 16 bits ( 2 bytes ) , at the end of the second I need 16000 byte or 8000 short.Now I have a 10fps recording speed then for each fps I need 16000/10 = 1600 byte.So , here is how the story proceeds : Variable... | byte [ ] eachPass = new byte [ 1600 ] ; //used to store data from TargetDataLine for each passbyte [ ] backingArray = new byte [ 16000 ] ; //the complete data for one secondByteBuffer buffer = ByteBuffer.wrap ( backingArray ) ; //buffer which stores the complete datashort [ ] audioSample = new short [ 16000/2 ] ; //aud... | Am I doing this correctly ? |
Java | I 'd expect this code to throw a ClassCastException : But it does n't . Casting String to T does n't fail , until I use the returned object somehow , like : Background : I created a Class which uses JAXB to unmarshal an XML file . It looks like this : Depending on whether the root-Element is an anonymous type or not , ... | public class Generics { public static void main ( String [ ] args ) { method ( Integer.class ) ; } public static < T > T method ( Class < T > t ) { return ( T ) new String ( ) ; } } public class Generics { public static void main ( String [ ] args ) { method ( Integer.class ) .intValue ( ) ; } public static < T > T met... | Why does n't this generic cast fail ? |
Java | As Hans Boehm in the Google I/O '17 talk `` How to Manage Native C++ Memory in Android '' suggests I use the PhantomReferenceclass to ensure native peers are deleted properly.In the linked video at 18 min 57 sec he shows an example implementation of an object registering itself to the PhantomReference class for it 's t... | import android.databinding . * ; public class WorkViewModel extends BaseObservable { private long _nativeHandle ; public WorkViewModel ( Database database , int workId ) { _nativeHandle = create ( database.getNativeHandle ( ) , workId ) ; WorkViewModelPhantomReference.register ( this , _nativeHandle ) ; } private stati... | Delete native peer with general PhantomReference class |
Java | I 'm adding millions of entries of a custom object to a List . This turns out to be very slow and the graphical user interface keeps freezing randomly as well ( not responding on Windows ) even though the adding operation is wrapped in a SwingWorker so it should not affect the EDT . Furthermore , the CPU utilization go... | List < SearchResult > updatedSearchResults = new ArrayList < > ( ) ; SearchResult searchResult = new SearchResult ( ... ) ; updatedSearchResults.add ( searchResult ) ; import java.io.ByteArrayOutputStream ; import java.io.IOException ; import java.math.BigInteger ; import java.util.ArrayList ; import java.util.List ; p... | Java List Horrible Adding Performance |
Java | When overloading methods that contain parameters that dont match , the JVM will always use the method with the smallest argument that is wider than the parameter . I have confirmed the above with the following two examples : Widening : byte widened to int } Boxing : int boxed to IntegerBoth the above examples output ``... | class ScjpTest { static void go ( int x ) { System.out.println ( `` In Int '' ) ; } static void go ( long x ) { System.out.println ( `` In long '' ) ; } public static void main ( String [ ] args ) { byte b = 5 ; go ( b ) ; } class ScjpTest { static void go ( Integer x ) { System.out.println ( `` In Int '' ) ; } static ... | Overloading methods with var-args - combined with boxing and widening |
Java | Question based on https : //stackoverflow.com/a/29671501/2517622Given a list of employees with id , name and IQ : I want to output : So , remove duplicates from the list based on id property of employee and choose employee with the highest IQ for obvious reasons . : ) Particularly , I am interested in adjusting this so... | List < Employee > employee = Arrays.asList ( new Employee ( 1 , `` John '' , 80 ) , new Employee ( 1 , `` Bob '' , 120 ) , Employee ( 1 , `` Roy '' , 60 ) , new Employee ( 2 , `` Alice '' , 100 ) ) ; [ Employee { id=1 , name='Bob ' , iq=120 } , Employee { id=2 , name='Alice ' , iq=100 } ] import static java.util.Compar... | Remove duplicates based on property and predicate in Java 8 |
Java | EditThis post pertains to a homework assignment I have for school that dictates I rely on swing to display my threads and boolean flags for blocking.My application creates a bunch of `` job '' objects that each contain a thread . Each job belongs to a creature . A creature can possess multiple jobs but can only perform... | public void run ( ) { long time = System.currentTimeMillis ( ) ; long startTime = time ; long stopTime = time + 1000 * ( long ) ( jobTime ) ; double duration = stopTime - time ; synchronized ( this.target ) { while ( this.target.isWorking ) { status = ' w ' ; showStatus ( ) ; // hmmmmmmmm try { this.target.wait ( ) ; }... | Multi-Threading not working correctly |
Java | I am running Matlab2017 on windows 10.I call a python script that runs some Speech Recognition task on cloud with something like this : When the above command is called , the python script runs the input audio file on the ASR cloud engine , and as it runs , I can see Speech Recognition scores for the audio file from Py... | userAuthCode=1 ; % authentication code for user account to be run on cloud cmd = [ ' C : \Python27\python.exe runASR.py userAuthCode ] ; system ( cmd ) ; for i=1 : 2 userAuthCode=i ; cmd = [ ' C : \Python27\python.exe runASR.py userAuthCode ] ; runtime = java.lang.Runtime.getRuntime ( ) ; pid ( i ) = runtime.exec ( cmd... | Calling multiple instances of python scripts in matlab using java.lang.Runtime.getRuntime not working |
Java | I 'm delving into the question of is String.equals ( ) really that bad and while trying to do some benchmarking of it came across some surprising results.Using jmh , I wrote up a simple test ( code and pom at end ) which sees how many times the function can be run in 1 second.The this is a 1300x factor between testEqua... | Benchmark Mode Samples Score Score error Unitsc.s.SimpleBenchmark.testEqualsIntern thrpt 5 698910949.710 47115846.650 ops/sc.s.SimpleBenchmark.testEqualsNew thrpt 5 529118.774 21164.872 ops/sc.s.SimpleBenchmark.testIsEmpty thrpt 5 470846539.546 19922172.099 ops/s package com.shagie ; import org.openjdk.jmh.annotations.... | Why is String.equals much slower for non-identical ( but equal ) String objects ? |
Java | I am working on someone 's code and came across the equivalent of this : Where someVolatileMember is defined like this : If some thread , A , is running the for loop and another thread , B , writes to someVolatileMember then I assume the number of iterations to do would change while thread A is running the loop which i... | for ( int i = 0 ; i < someVolatileMember ; i++ ) { // Removed for SO } private volatile int someVolatileMember ; final int someLocalVar = someVolatileMember ; for ( int i = 0 ; i < someLocalVar ; i++ ) { // Removed for SO } | Java volatile loop |
Java | I know that if the Collection will be changed while some thread is traversing over it using iterator , the iterator.next ( ) will throw a ConcurrentModificationException.But it shows different behavior depending on the number of elements in the list.I tried a code snippet in which I traversed a list in for-each loop an... | public static void main ( String [ ] args ) { List < String > list=new ArrayList < String > ( ) ; list.add ( `` One '' ) ; for ( String string : list ) { System.out.println ( string ) ; list.remove ( string ) ; } } public static void main ( String [ ] args ) { List < String > list=new ArrayList < String > ( ) ; list.ad... | Abnormal behaviour of java.util.List based on number of elements in it |
Java | I 'm working with Shopify at the moment and using their webhook notifications so I can save stuff to our database.Within their webhook headers , they provide a header of : X-Shopify-Hmac-Sha256which is : Each Webhook request includes a X-Shopify-Hmac-SHA256 header which is generated using the app 's shared secret ( loo... | < cfscript > variables.stArgs = { } ; variables.stArgs.stWebHookData = getHTTPRequestData ( ) ; application.stObj.stShopify.oShopifyWebHookBusiness.receiveWebHook ( argumentCollection=variables.stArgs ) ; < /cfscript > local.data = arguments.stWebHookData.toString ( ) ; local.macClass = createObject ( `` java '' , `` j... | coldfusion calculating HMAC256 of a getHTTPRequestData |
Java | In Java , we have functions of the sort : Do note that I am not modifying the input in any way because a lot of time we happen to use ImmutableList for the List . More commonly , we try to ensure immutability in functions to whatever degree possible . However , a pitfall I see here is that , all my methods very often u... | public Collection < String > removeNulls ( Collection < String > input ) { List < String > output = new ArrayList < > ( ) ; // ... return output ; } Set < String > mySet = new SortedSet < > ( ) ; mySet.add ( 10 ) ; mySet.add ( 9 ) ; // I know that my collection is now sortedCollection < String > myFilteredSet = removeN... | Correct way to develop generic modifiers in Java |
Java | I 'd like to print headers of *.java files in all sub-directories recursively that have more than two type parameters ( i.e . parameters within < R ... H > in the samples below ) . One of the files looks like ( with names reduced for brevity ) : multiple-lines.javawith expected output : but another could look like this... | class ClazzA < R extends A , S extends B < T > , T extends C < T > , U extends D , W extends E , X extends F , Y extends G , Z extends H > extends OtherClazz < S > implements I < T > { public void method ( Type < Q , R > x ) { // ... code ... } } ClazzA.java:10 : class ClazzA < R extends A , ClazzA.java:11 : S extends ... | gawk or grep : single line and ungreedy |
Java | I would like to know the use of ? in java generics . By studying placeholder T and the wildcard ? , I wondered about ? , gone through several websites/pages and books but failed to understand it . So I created the below class to study the differences . Here in one case , There might be several scenarios missing from my... | import java.util.List ; public class Generics2 { public < T > void method1 ( List < T > list ) { System.out.println ( list ) ; } public < T extends Number > void method2 ( List < T > list ) { System.out.println ( list ) ; } /*public < T super Integer > void method3 ( List < T > list ) { } *///super does not work . publ... | What is use of having ? in java |
Java | Why does combining images where BG is a JPEG cause unexpected results ? This is a follow-up to my answer in Overlaying of 2 images doesnt work properly . The source posted there ( using a BG image created in memory ) looks like this : The BG image is on the left.The FG image ( a PNG with transparency ) is in the middle... | import java.awt . * ; import java.awt.image.BufferedImage ; import javax.swing . * ; import java.io.ByteArrayInputStream ; import java.io.ByteArrayOutputStream ; import java.net.URL ; import javax.imageio.ImageIO ; class CombineImages { public static void main ( String [ ] args ) { Runnable r = new Runnable ( ) { @ Ove... | Combining images where BG is a JPEG causes unexpected results |
Java | I have the following two interfaces : I want to enforce the following : The type parameter of the View ( called ( a ) ) , should be a Viewable that views upon that view ( a ) .The type parameter of Viewable ( called ( b ) ) , should be a View , which is viewable via that same viewable ( b ) .I think I got the bounds do... | /** * A marker interface to denote that an object implements a view on some other object . * * @ param < T > The type of object that is viewed */public interface View < T extends Viewable < View < T > > > { } /** * An interface for objects that are viewable via a view . * * @ param < T > The type of viewable object */p... | Recursive type parameters for an almost-cyclic type bound |
Java | Is there a good reason to use parameters that shadow fields ? What is the difference between these two : andAnd what if you use the this keyword without parameters that shadow fields in this example ( I 'm guessing it 's just unnecessary ) : | public class Point { public int x = 0 ; public int y = 0 ; //constructor public Point ( int a , int b ) { x = a ; y = b ; } } public class Point { public int x = 0 ; public int y = 0 ; //constructor public Point ( int x , int y ) { this.x = x ; this.y = y ; } } public class Point { public int x = 0 ; public int y = 0 ;... | Is there a good reason to use parameters that shadow fields ? |
Java | Is there a way to copy some List ( or combined string if necessary ) N times in Java using Stream APIIf the list consists of { `` Hello '' , `` world '' } and N = 3 , the result should be { `` Hello '' , `` world '' , `` Hello '' , `` world '' , `` Hello '' , `` world '' } What I 've done so far is to get combined Stri... | Optional < String > sentence = text.stream ( ) .reduce ( ( value , combinedValue ) - > { return value + `` , `` + combinedValue ; } ) ; | Copy List elements N times using Stream API |
Java | I want to make clickable cell of the palette in Vuforia ( without Unity ) by tap on screen : I found Dominoes example with similar functionality and do that : create one plate object and multiply cells objectscall isTapOnSetColor function with parameter x , y ( click coordinates ) on tap and get coordinates , coordinat... | boolean bool = checkIntersectionLine ( matrix44F , lineStart , lineEnd ) ; bool intersection = checkIntersectionLine ( domino- > pickingTransform , lineStart , lineEnd ) ; | How to make clicks on part of model in Vuforia ( without Unity ) ? |
Java | I have a system of object instances that contain a reference to a definition object . I have a top-level class for each inheritance tree . The instance object has a generic reference to the corresponding definition class.Using generics in the getter , a subclass of the top-level object can get the right type of definit... | class Def { } abstract class Animal < D extends Def > { D def ; D getDef ( ) { return def ; } } class CatDef extends Def { } class Cat extends Animal < CatDef > { } abstract class BearDef extends Def { } abstract class Bear < D extends BearDef > extends Animal < D > { } class BlackBearDef extends BearDef { } class Blac... | Why does n't this generic recognize its superclass boundary ( Java ) ? |
Java | I saw java hash map , the clear method , like this : I do n't understand , why to take new tab to clear.Why not use table to clear ? | public void clear ( ) { modCount++ ; Entry [ ] tab = table ; for ( int i = 0 ; i < tab.length ; i++ ) tab [ i ] = null ; size = 0 ; } | Could not understand implementation of clear method of HashMap in java |
Java | Are these two ( valid ) generic bounds : the same ? Suppose I have an interfaceAnd some enums that implement it : And I want to require that an implementation uses not only a MyInterface but also that it is an enum . The `` standard '' way is by an intersection bound : But I 've discovered that this also works : With t... | < T extends Enum < T > & MyInterface > < T extends Enum < ? extends MyInterface > > interface MyInterface { void someMethod ( ) ; } enum MyEnumA implements MyInterface { A , B , C ; public void someMethod ( ) { } } enum MyEnumB implements MyInterface { X , Y , Z ; public void someMethod ( ) { } } static class MyInterse... | Is there a difference between the generic bounds `` Enum < T > & Foo '' and `` Enum < ? extends Foo > '' |
Java | I run this in Java 7 and I get : But when I run the same operations in Perl 5.8.8 I get different results for two out of three : Why is there such a difference in the last two calculations ? How can I get perl to match java results ? | double remainder1 = 1 % 1000 ; double remainder2 = 0.01 % 1000 ; double remainder3 = -1 % 1000 ; System.out.println ( `` START : `` +remainder1+ '' | `` +remainder2+ '' | `` +remainder3 ) ; > > > START : 1.0 | 0.01 | -1.0 my $ remainder1 = 1 % 1000 ; my $ remainder2 = 0.01 % 1000 ; my $ remainder3 = -1 % 1000 ; print `... | Why does modulo operation gives different results in Java VS Perl ? |
Java | I m learning about java optional wrapper , to do so I m reading the following tutorialhowever I have a simple question that is not answered in the article : in item 25 : Avoid Using Identity-Sensitive Operations on Optionals they are mentioning to NEVER use an optional object in a synchronized way like this : but there... | Optional < Product > product = Optional.of ( new Product ( ) ) ; synchronized ( product ) { ... } | Why you should never use synchronized on Optional java object |
Java | The following code : compiles without errors in JDK 8 ( using -source 1.6 ) , but fails in JDK 6 with the error message : While I do understand what the error is about , why does this compile with JDK 8 ? Is this documented anywhere ? | void someMethod ( Object value ) { String suffix = getSuffix ( ) ; if ( suffix ! = null ) value += suffix ; [ ... ] } Operator '+ ' can not be applied to java.lang.Object and java.lang.String | Operator '+ ' can not be applied to Object and String |
Java | Consider following code , I want to make it a thread safe class , so that it will never get odd number : I am now doubt of the lock field , which is declared to be final , will this matter ? or it will break the thread safety ? I think if the lock field is not declared to be final , this should be a thread-safe class .... | class Test { private int value = 0 ; private final Object lock ; public void add ( ) { synchronized ( lock ) { value++ ; value++ ; } } public int getValue ( ) { synchronized ( lock ) { return value ; } } } | can I use synchronized to a final field ? |
Java | I 'm trying to have a functor F which may throw multiple exceptions ( in the example below Checked and SQLException ) . I want to be able to call a function with F as an argument , such that whatever checked exceptions F throws ( except SQLException which would be handled internally ) get rethrown.Intuitively , I would... | import java.sql.Connection ; import java.sql.SQLException ; class Checked extends Exception { public Checked ( ) { super ( ) ; } } @ FunctionalInterfaceinterface SQLExceptionThrowingFunction < T , U , E extends Exception > { U apply ( T t ) throws E , SQLException ; } class ConnectionPool { public static < T , E extend... | Java type inference of generic exception type |
Java | According to the Javadoc : ... If start is equal to ± Double.MAX_VALUE and direction has a value such that the result should have a larger magnitude , an infinity with same sign as start is returned . But according to this example : Output : Eh ? Not only is it not Double.POSITIVE_INFINITY , it 's actually smaller in m... | public static double nextAfter ( double start , double direction ) System.out.println ( Double.MAX_VALUE ) ; System.out.println ( Math.nextAfter ( Double.MAX_VALUE , 1 ) ) ; System.out.println ( Math.nextAfter ( Double.MAX_VALUE , 1 ) == Double.POSITIVE_INFINITY ) ; 1.7976931348623157E3081.7976931348623155E308false ...... | Why is n't Math.nextAfter ( Double.MAX_VALUE , 1 ) equal to Double.INFINITY ? |
Java | is an attribute in a JSON . How do I parse this date ? I tried the following piece of code . 2015-05-11T11:31:47 Works just fine . However,۲۰۱۵-۱۱-۰۲T۱۸:۴۴:۳۴+۰۰:۰۰ throws an IllegalArgumentException . Tried parsing the date with other locales/formats as well . No luck . Please help me out . | `` timestamp_utc '' : `` ۲۰۱۵-۱۱-۰۲T۱۸:۴۴:۳۴+۰۰:۰۰ '' try { return new DateTime ( dateStr , DateTimeZone.UTC ) ; } catch ( IllegalArgumentException e ) { java.util.Locale locale = new java.util.Locale ( `` ar '' , `` SA '' ) ; DateTimeFormatter formatter = ISODateTimeFormat.dateTime ( ) .withLocale ( locale ) ; return ... | read timestamp which is in a different locale |
Java | Output : In the above example , why does the compiler choose the widening option ( i.e . Integer -- > Number ) instead of unboxing the Integer and choosing the int option ? Thanks | class Dec26 { public static void main ( String [ ] args ) { short a1 = 6 ; new Dec26 ( ) .go ( a1 ) ; new Dec26 ( ) .go ( new Integer ( 7 ) ) ; } void go ( Short x ) { System.out.print ( `` S `` ) ; } void go ( Long x ) { System.out.print ( `` L `` ) ; } void go ( int x ) { System.out.print ( `` i `` ) ; } void go ( Nu... | Does wrapper widening beat unboxing ? |
Java | I 'm trying to split a string with multiple sentences into a string array of individual sentences . Here 's what I have so far , And this code is working perfectly fine . I get , I use the lookbehind functionality to see if a sentence ending punctuation mark precedes some or a single white space ( s ) . If so , we spli... | String input = `` Hello World. `` + `` Today in the U.S.A. , it is a nice day ! `` + `` Hurrah ! '' + `` Here it comes ... `` + `` Party time ! `` ; String array [ ] = input.split ( `` ( ? < = [ . ? ! ] ) \\s+ ( ? = [ \\D\\d ] ) '' ) ; Hello World.Today in the U.S.A. , it is a nice day ! Hurrah ! Here it comes ... Part... | Splitting a paragraph into individual sentences . Am I covering all my bases here ? |
Java | I recently was doing some coding challenges and this was one of the problems . A non-empty zero-indexed array A consisting of N integers is given . The array contains an odd number of elements , and each element of the array can be paired with another element that has the same value , except for one element that is lef... | public int solution ( int [ ] A ) { int r = 0 ; for ( int i=0 ; i < A.length ; i++ ) r ^=A [ i ] ; return r ; } | JAVA - How does the bitwise exclusive OR assignment operator work in this given solution |
Java | I read a couple of posts such as here but I was unable to find the solution for my problem . Why I am unable to add d ? It is a subtype of Object ... Type of d : A < B < X > > EDITI tried to simplify the problem . When I do : I get the error : Type mismatch : can not convert from A < B < String > > to A < B < ? > > How... | List < A < B < ? extends Object > > > rv=new LinkedList < > ( ) ; rv.add ( d ) ; //not working A < B < ? > > abcv=new A < B < String > > ( ) ; List < A < B < ? > > > rv=new LinkedList < > ( ) ; rv.add ( new A < B < X > > ( ) ) ; rv.add ( new A < B < String > > ( ) ) ; rv.add ( new A < B < Integer > > ( ) ) ; | Adding Object to Generic List with two types |
Java | Why does the declarationwork but the declarationchoke ? I 'm aware that 'top level ' ( not sure if that 's the correct phrase here ) generics in a declaration play by different rules than those inside the pointy brackets , but I 'm interested to learn the reason . Not an easy question to google , so I thought I 'd try ... | Set < Set < String > > var = new HashSet < Set < String > > ( ) ; Set < Set < String > > var = new HashSet < HashSet < String > > ( ) ; | How do nested type arguments work ? |
Java | I have a java string that looks like this ; And I want to split this String from delimiter ( fname : jon ) < here > ( lname : doe ) .I tried splitting through regex \ ) \ ( but it just breaks my codeOutputI also looked at this question : How to split a string , but also keep the delimiters ? , but it did n't helped bec... | ( fname : jon ) ( lname : doe ) ( guaranteer : Sam ( W ) Willis ) ( age:35 ) ( addr:1 Turnpike Plaza ) ( favcolor : blue ) arr = s.split ( `` \\ ) \\ ( `` ) ; for ( String a : arr ) System.out.println ( a ) ; ( fname : jonlname : doeguaranteer : Sam ( W ) Willisage:35addr:1 Turnpike Plazafavcolor : blue ) ( fname : jon... | Java Regex split string between delimiter and keep delimiter |
Java | Here is an example of some code I 'm working on : Let 's further assume there will be many different concrete implementations of FooMaker . So I wrote some code to utilize the FooMakers.The second line of code causes the issue , eclipse tells me the code should be : I 'm having trouble understanding why the Foo declara... | public interface FooMaker < T extends Enum < T > & FooType > { public List < Foo < T > > getFoos ( String bar ) ; } FooMaker < ? > maker = Foos.getRandomMaker ( ) ; List < Foo < ? > > fooList = maker.getFoos ( `` bar '' ) ; //error here ! FooMaker < ? > maker = Foos.getRandomMaker ( ) ; List < ? > fooList = maker.getFo... | Java Generics - Expected return type different than actual |
Java | I 'm trying to rename a method in my Eclipse Java project , but it seems to be renaming every method which has the same name . ( Perhaps I 'm misunderstanding what this feature is for - maybe it 's just using sed ? ) Here is a simplified example : If I select the f method in C2 , and select `` rename '' from the `` ref... | public class C1 { interface Listener { void f ( ) ; } public C2.Listener c2l = new C2.Listener ( ) { public void f ( ) { } } ; } public class C2 { interface Listener { void f ( ) ; } } public class C1 { interface Listener { void g ( ) ; } public C2.Listener c2l = new C2.Listener ( ) { public void g ( ) { } } ; } public... | How to automatically rename a Java method in Eclipse ? |
Java | How can I invert the last bit in an int ? I wrote this : But how should I rewrite invertLastBit ( ) ? | int a = 11 ; System.out.print ( a + `` `` + Integer.toBinaryString ( a ) ) //11 1011int b = invertLastBit ( a ) ; System.out.print ( b + `` `` + Integer.toBinaryString ( b ) ) ; //10 1010 static int invertLastBit ( int i ) { String s = Integer.toBinaryString ( i ) ; if ( s.charAt ( s.length ( ) -1 ) == ' 0 ' ) { s = s.... | Invert last bit |
Java | Given this code : When you compile that and run javap -c -p 'Test $ 1.class ' , you get this : When the anonymous class is created , the variable p is captured into val $ p ( as expected , because it 's needed ) , and the variable q is not ( as expected , because it 's not needed ) . However , Test.this is captured int... | class Foo { } public class Test { public Foo makeFoo ( String p , String q ) { return new Foo ( ) { public void doSomething ( ) { System.out.println ( p ) ; } } ; } } Compiled from `` Test.java '' class Test $ 1 extends Foo { final java.lang.String val $ p ; final Test this $ 0 ; Test $ 1 ( Test , java.lang.String ) ; ... | Why do anonymous classes capture `` this '' even if they do n't need to ? |
Java | It 's a followup question of jgit - git diff based on file extension.I am trying to add the formatted diff to List < String > but If I try to use same DiffFormatter as below then previous entries getting appended to the next one . Therefore I forced to create a DIffFormatter for every diff entry.Is there a better way t... | List < String > changes = new LinkedList < > ( ) ; try ( OutputStream outputStream = new ByteArrayOutputStream ( ) ; DiffFormatter diffFormatter = new DiffFormatter ( outputStream ) ) { diffFormatter.setRepository ( git1.getRepository ( ) ) ; TreeFilter treeFilter = PathSuffixFilter.create ( `` .txt '' ) ; diffFormatte... | JGit - How to reuse the DiffFormatter |
Java | Many people asked similar questions like this , but none of their answers satisfied me.The only two reordering rules that I am very sure of are as follows : Operations inside the synchronized block ( or just call itcritical section ) are allowed to be reordered , as long as it confirms to the as-if-serial semantics.Ope... | MonitorEnter ( any other needed instructions go here ) [ LoadLoad ] < ===MB1 : Inserted memory barrier [ LoadStore ] < ===MB2 : Inserted memory barrier ( Begin of critical section ) ... . ( end of critical section ) [ LoadStore ] < ===MB3 : Inserted memory barrier [ StoreStore ] < ===MB4 : Inserted memory barrier ( any... | What are valid reordering for Java synchronized ? |
Java | I 'm looking for a solution for this problem : I have an excel file , that contains data . Some of the cells have yellow background . I already created a code for importing the text to JTable , which works fine . But I want to import the background-cell-color to specific cells also . For simplicity-sake of this example... | import java.awt.Color ; import java.awt.Component ; import javax.swing.JTable ; import javax.swing.table.DefaultTableCellRenderer ; public class MyRenderer extends DefaultTableCellRenderer { @ Override public Component getTableCellRendererComponent ( JTable table , Object value , boolean isSelected , boolean hasFocus ,... | Color only specific cells in JTable |
Java | I declare a class as follows : This ... ... yields `` AdditionalClass '' . What method call or calls would allow me to interrogate that object and get `` GenericClass '' as a result ? | public class SomeClass extends AdditionalClass < GenericClass > { ... } SomeClass object = new SomeClass ( ) ; System.out.println ( object.getSuperClass ( ) .getSimpleName ( ) ) ; | Get the value of a generic declaration programmatically ? |
Java | Consider the following method : The method can be abbreviated to : Are these two representations equal in actual run time ? In other words , does the Java compiler optimize away the unnecessary definition of extra variables , that I 've placed for readability and debugging ? | private static long maskAndNegate ( long l ) { int numberOfLeadingZeros = Long.numberOfLeadingZeros ( l ) long mask = CustomBitSet.masks [ numberOfLeadingZeros ] ; long result = ( ~l ) & mask ; return result ; } private static long maskAndNegate ( long l ) { return ( ~l ) & CustomBitSet.masks [ Long.numberOfLeadingZero... | Are variable definitions that are used once optimized ? |
Java | Let 's compile the following code with ECJ compiler from Eclipse Mars.2 bundle : The compilation command is the following : $ java -jar org.eclipse.jdt.core_3.11.2.v20160128-0629.jar -8 -g Test.javaAfter the successful compilation let 's check the resulting class file with javap -v -p Test.class . The most interesting ... | import java.util.stream . * ; public class Test { String test ( Stream < ? > s ) { return s.collect ( Collector.of ( ( ) - > `` '' , ( a , t ) - > { } , ( a1 , a2 ) - > a1 ) ) ; } } private static void lambda $ 1 ( java.lang.String , java.lang.Object ) ; descriptor : ( Ljava/lang/String ; Ljava/lang/Object ; ) V flags ... | Strange `` ! * '' entry in LocalVariableTypeTable when compiling with eclipse compiler |
Java | Item has name , price , condition attributes . I want to keep the priceand conditionbut replace the name.For now I figured out this by creating new object but I think this is not best option . I just want to change one field of ArrayList item | public void modify ( String name ) { for ( Item i : item ) { if ( i.getName ( ) .equalsIgnoreCase ( name ) ) { int position = item.indexOf ( i ) ; System.out.println ( `` New name : `` ) ; String newName = in.nextLine ( ) ; Item updated = new Item ( newName , i.getPrice ( ) , i.getCondition ( ) , i.getSize ( ) ) ; item... | Updating specific attribute of an ArrayList item |
Java | Now I have an existing class that I would like to refactor to be an Enum . The class currently extends another class which is from external library . As I still would like to benefit from some logics from that extended class meanwhile would like to refactor . How should it be done ? In Java , an enum class can not exte... | class Existing extends Parent { public static final Existing A = new Existing ( ... ) ; ... . public static final Existing Z = new Existing ( ... ) ; public Existing ( Srting attr1 , String attr1 ) { super ( attr1 , attr2 ) ; } public Existing ( String attr1 ) { super ( attr1 ) ; } } enum NewDesign { A ( attr1 , attr2 ... | How can an Enum class extend another external library class ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.