lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | Here is from HashMap:I wonder why not use member variable values directly ? Why create the local variable named vs ? How is that better than : | transient Collection < V > values ; public Collection < V > values ( ) { Collection < V > vs = values ; if ( vs == null ) { vs = new Values ( ) ; values = vs ; } return vs ; } transient Collection < V > values ; public Collection < V > values ( ) { if ( values == null ) { values = new Values ( ) ; } return values ; } | Why not use values variable directly , the vs variable is not necessary |
Java | Please , tell me difference between the next situations : There is no compilation error in this caseANDThere is compilation error | public class Test { private static < T extends Throwable > void doThrow ( Throwable ex ) throws T { throw ( T ) ex ; } public static void main ( String [ ] args ) { doThrow ( new Exception ( ) ) ; //it 's ok } } public class Test { private static < T extends Throwable > void doThrow ( Throwable ex ) throws Throwable { ... | What 's the difference between the next situations |
Java | I have the below classWill the iterator ( ) call in the printElement method throw ConcurrentModificationException ? The basic question is if the lock on class object is acquired ( as done in printElement method ) , will it lock the class members/ variables too ? please help me with the answer . | public class Example { public static List < String > list = new ArrayList < String > ( ) ; public static void addElement ( String val ) { synchronized ( list ) { list.add ( val ) ; } } public static synchronized void printElement ( ) { Iterator < String > it = list.iterator ( ) ; while ( it.hasNext ( ) ) { //print elem... | Does a lock on class , locks class variables too ? - java |
Java | I have a code like this : Why when creating A with no generic type getFiled returns String but getFileds returns List < Object > ? I have to define A as A < String > a = new A < > ( ) for this to work properly.Thanks , | public class A < T extends String > { T field ; List < T > fields ; public T getField ( ) { return field ; } public List < T > getFields ( ) { return fields ; } public static void test ( ) { A a = new A ( ) ; String s = a.getField ( ) ; List < String > ss = a.getFields ( ) ; } } | Why is the base type not returned when no generic type specified ? |
Java | Currently i have code like below . A list embedded with in another list , and i want to get the total count of the embedded list objects.I want to write a quick oneliner for this . Is there an efficient Lambda or FP trick i can do in Java 8 ? | int totalNo = 0 ; for ( ClassB classB : listOfClassB ) { totalNo+= classB.getAnotherObjList ( ) .size ( ) ; } | Accumulate count of list 's within another list |
Java | Suppose I have a simple list : The target is `` test '' and I want to add the value before the target into a new list , so the output would be [ result1 , result2 ] .It 's easy enough to add the `` test '' values with something like listTwo = listOne.stream ( ) .filter ( i - > i.equals ( `` test '' ) ) .collect ( Colle... | List < String > listOne = Arrays.asList ( `` str1 '' , `` result1 '' , `` test '' , `` str4 '' , `` result2 '' , `` test '' , `` str7 '' , `` str8 '' ) ; for ( int i = 1 ; i < listOne.size ( ) ; i++ ) { if ( listOne.get ( i ) .equals ( `` test '' ) ) { listTwo.add ( listOne.get ( i - 1 ) ) ; } } | Find value n steps away from target in List with stream |
Java | I am writing a class to represent time series data , i.e . basically a map of ( Instant , T ) pairs for a generic type TSome of the classes we deal with implement an interfaceand I want to provide a more convenient method in the TimeSeries interface to add such data items without stating the time explicity . Basically ... | interface TimeSeries < T > { void add ( Instant when , T data ) ; } interface TimeStamped { Instant getTimeStamp ( ) ; } interface TimeSeries < T > { void add ( Instant when , T data ) ; default < X extends T & TimeStamped > void add ( X data ) { add ( data.getTimeStamp ( ) , data ) ; } } interface TimeSeries < T > { v... | Generic parameter with additional constraint through intersection types |
Java | I have an mysql query : From this query I am getting no . of Full Day present.I have present_status= 'Half Day ' & present_status = 'Full Day ' in my database records . How to count 'Full Day ' + 'Half Day ' ? | SELECT count ( * ) as ` present_days ` FROM tbl_intime_status WHERE employee_status = 'Out ' and present_status = 'Full Day ' and date LIKE ' % / '' +month2+ '' / '' +year1+ '' ' and employee_id= '' + EmpId+ | How to sum records of a single column with different possibilities ? |
Java | I launch a jetty instance indirectly when creating a JAX-RS endpoint using cxfThis works just fine , but how can i configure the size of the jetty threadpool minThreads and maxThreads programmatically when launching it via CXF ? | JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean ( ) ; sf.setResourceClasses ( HelloWorldResource.class ) ; sf.setResourceProvider ( HelloWorldResource.class , new SingletonResourceProvider ( new HelloWorldResource ( ) ) ) ; sf.setAddress ( `` http : //localhost:9000/ '' ) ; sf.create ( ) ; | Configure jetty that is launched via CXF programmatically |
Java | This question might be considered opinionated but I really ca n't seem to find a straight answer . So either I 'm missing something or I 'm asking the wrong questions.So , I 'm an undergrad student and new in the whole Spring app development and I 'm currently creating an app with React acting as the frontend and build... | @ RestController @ RequestMapping ( `` /api '' ) @ Slf4j @ RequiredArgsConstructor @ Componentpublic class GeocodingController { private final OkHttpClient httpClient = new OkHttpClient ( ) ; @ PostMapping ( value = `` /reversegeocoding '' ) public String getReverseGeocode ( @ RequestBody LatLng latlng ) throws IOExcep... | Is routing API calls through my own RESTful API considered an acceptable strategy ? |
Java | Why in the below code is assigning a value to the static variable acceptable but using that same variable is not ? | class Test { static { var=2 ; //There is no error in this line System.out.println ( var ) ; //Why is there an error on this line if no error on the above line } static int var ; } | Static blocks and variables |
Java | What are the norms for creating JPackage installer Java application on Linux ? I have created an installer for Windows , and am now creating one on Linux ( using Ubuntu ) So far I have : for creating a debian installer , it works ( installs not yet running properly ) but I am confused about a number of things , I am no... | -i target/Jaikoz/buildLinux -- main-class com.jthink.jaikoz.Jaikoz -- name Jaikoz -- main-jar lib/jaikoz.jar -- app-version 10.1.0 -- copyright `` Copyright 2020 JThink Ltd , United Kingdom '' -- arguments `` -l2 -m2 -f '' -- java-options `` -Dhttps.protocols=TLSv1.1 , TLSv1.2 '' -- java-options `` -- add-opens java.ba... | What should linux-menu-group be when creating JPackage installer Java application on Linux ? |
Java | Given that 2 strings : I want to find out whether each character in stringB H A T S exists in stringAIn a junior approach , the process can be done within a nested for-loop which its computation complexity is O ( n^2 ) .I am looking for a faster solution to solve this problem . | String stringA = `` WHATSUP '' ; String stringB = `` HATS '' ; for ( int i = 0 ; i < stringA.length ( ) ; i++ ) { for ( int j = 0 ; j < stringB.length ( ) ; j++ ) { if ( stringA.charAt ( i ) == stringB.charAt ( j ) ) //do something } } | Find whether each character in 1 string is exist in another string , faster than O ( n^2 ) |
Java | C # 's extension methods are great for adding syntactic sugar . Java extension methods are great for allowing library developers to add methods to their interfaces.I am a non-library Java developer and know I will reap a lot of benefits from getting new functionality from libraries , but I would still like to have the ... | String data = StringUtils.capitalize ( `` abcd '' ) ; // instead of thisString data = `` abcd '' .capitalize ( ) // I would like to do this | Will Java have a way for non-library developers to use extension methods ? |
Java | I am writing my own Array List . Here is the remove method of the same , Now i will perform some remove operationNow this will result in the following output , But when i use the ArrayList from the API , i will get the output asAm i missing something ? Can someone please explain me where i went wrong . | public E remove ( int index ) { E value = ( E ) elementData [ index ] ; for ( int i=index ; i < size-1 ; i++ ) { elementData [ i ] =elementData [ i+1 ] ; } elementData [ size-1 ] =null ; return value ; } Box < Integer > list = new Box < > ( ) ; for ( int i=1 ; i < 5 ; i++ ) { list.add ( i ) ; } print ( list ) ; list.re... | remove ( ) in ArrayList |
Java | I need to extend an abstract class which I can not modify : With a generic class like this : My question is obvious : what should be returned by VerticalCheckBoxSelect : :getType to be compilable ( and correct ) ? | public abstract class CustomField < T > extends AbstractField < T > implements HasComponents { // some code @ Override public abstract Class < ? extends T > getType ( ) ; // some code } public class VerticalCheckBoxSelect < T > extends CustomField < Set < T > > { @ Override public Class < ? extends Set < T > > getType ... | Class abstraction and generics |
Java | Let 's say I have simple class : I have multiple pojo classes in my project and I want to be able to serialize each object to json . So I created new Serializer class ( gson used to serialize ) : And my example class extends Serializer : And I am able to serialize any object of class extending Serializer by calling toJ... | public class TestClass { public String field1 = `` Field1 '' ; public String field2 = `` Field2 '' ; public String field3 = `` Field3 '' ; } public class Serializer { public String toJson ( ) { return new Gson ( ) .toJson ( this ) ; } } public class TestClass extends Serializer { public String field1 = `` Field1 '' ; p... | Java - pass type to superclass static method |
Java | Recently I was reading the following piece of code from oracle collection tutorial when i came across this piece of code.I was not able to understand why the returned value is something | public static < E > Set < E > removeDups ( Collection < E > c ) { return new LinkedHashSet < E > ( c ) ; } < E > Set < E > and not just Set < E > ? | generic return object |
Java | I would like to pass a reference to a primitive type to a method , which may change it.Consider the following sample : The output running the sample is : Which means int_ref was past to the function by value , and not by reference , despite my optimistic name.Obviously there are ways to work around this particular exam... | public class Main { Integer x = new Integer ( 42 ) ; Integer y = new Integer ( 42 ) ; public static void main ( String [ ] args ) { Main main = new Main ( ) ; System.out.println ( `` x Before increment : `` + main.x ) ; // based on some logic , call increment either on x or y increment ( main.x ) ; System.out.println (... | A reference to primitive type in Java ( How to force a primitive data to remain boxed ) |
Java | I was experimenting on initialization order in Java and I came across something really confusing : As you can see , we can not reference a field that was not declared yet , hence the compile error on System.out.println ( staticField ) ; in the first static block : Can not reference a field before it is defined.However ... | static { System.out.println ( `` Static 1 , staticField ca n't be accessed ( compile error ) '' ) ; staticField = `` value '' ; // NO COMPILE ERROR ! //System.out.println ( staticField ) ; // compile error } public static String staticField ; static { System.out.println ( `` Static 2 , staticField= '' + staticField ) ;... | Why does assignment in static init block compile without error ? |
Java | I 'm trying to figure out the whole Java generics topic.More specifically this issue : How can I add an `` extends '' wildcard specifying that the set method can receive E or any inheriting class of E ( in which case the Node will hold a upcasted version of the parameter ) .Or will it work even if I leave it the way it... | public class Node < E > { private E data ; public Node ( E data ) { this.data=data ; } public E get ( ) { return this.data ; } public void set ( E data ) { this.data=data ; } } | Parameters of a Java generic method |
Java | case 1 : it can work when using for-each loop:orcase 2 : it will catch compile-time errorIn case 2 , I know the variable i is not effectively final because its value changed between loop iterations . But I can not understand why the lambda can work in case 1 . | private void m10 ( String [ ] arr ) { for ( String s : arr ) { Supplier < String > supplier = ( ) - > { System.out.println ( s ) ; return null ; } ; supplier.get ( ) ; } } private void m10 ( Object [ ] arr ) { for ( Object s : arr ) { Supplier < String > supplier = ( ) - > { System.out.println ( s ) ; return null ; } ;... | Why is the loop variable effectively final when using for-each ? |
Java | I have to `` translate '' codes with a conversion table like this : My first idea was to use a Map associating each symbol to its translation and to load the table from a database or a text/xml file . Is there a better way ? Does n't have to be lightning fast , just easy to maintain and test.TIA . | | symbol | translation | | 1 | 3 || 2 | 4 || 3 | 6 || 4 | 5 || 5 | 2 || 6 | 1 || 7 | 1 | | How to convert/translate information ? |
Java | Java supports pass by value ( always works on a copy ) but when you pass a user defined object then it changes the actual object ( kind of pass by reference but no pointer changes ) , which I understand but why the changeObject2CLEAR method below is actually changing the value of the object ? Instead it has to work on ... | import java.util.HashMap ; import java.util.Map ; public class PassBy { class CustomBean { public CustomBean ( ) { } private int id ; private String name ; public int getId ( ) { return id ; } public void setId ( int id ) { this.id = id ; } public String getName ( ) { return name ; } public void setName ( String name )... | Issue with pass by value in java |
Java | In a program I was working on , I ran into a data storage issue , specifically related to ArrayLists . This is not the actual code I was testing , but it provides an example of what I mean.If you run it , you get , true , true , and false . The code recognizes that both are equal to 129 but for some reason returns fals... | public class test { public static void test ( ) { ArrayList < Integer > bob = new ArrayList < Integer > ( ) ; bob.add ( 129 ) ; bob.add ( 129 ) ; System.out.println ( bob.get ( 0 ) == 129 ) ; System.out.println ( bob.get ( 1 ) == 129 ) ; System.out.println ( bob.get ( 0 ) == bob.get ( 1 ) ) ; } } public class test { pu... | Does == comparison use byte in ArrayList comparisons ? |
Java | First , a bit of context code : The above represents the data structure I am dealing with . I have an outer map ( key type is irrelevant ) , that contains inner `` property maps '' as values . These inner maps use strings to lookup different kind of data . In the case I am working on , each v1 , v2 , ... represents a `... | import java.util . * ; import java.util.concurrent.atomic.DoubleAdder ; import java.util.function.Function ; import java.util.stream.Collectors ; class Scratch { static enum Id { A , B , C } static class IdWrapper { private final Id id ; public IdWrapper ( Id id ) { this.id = id ; } Id getId ( ) { return id ; } } publi... | Is there a way to collect a map using `` groupingBy '' for MULTIPLE elements within a nested structure ? |
Java | when I am runnig the code in unix system.exit ( Integer.parseInt ( e.getMessage ( ) ) ) is giving 254 output : | System.out.println ( Integer.parseInt ( e.getMessage ( ) ) ) ; System.out.println ( e.getMessage ( ) ) ; System.exit ( Integer.parseInt ( e.getMessage ( ) ) ) ; -2 -2 254 | why I am getting two different values from system.out.println ( ) and system.exit ( ) ? |
Java | Here are three sample lines from my dataset : I am trying to come up with a pattern matcher which would capture the following : feature namethe relation ( = , > = , < ) feature value ( could be a mix of numbers and/or characters , but never contains a colon ) result ( the value that comes after the colon and before the... | | | | | featureB > = 16104.33 : 18873.52 ( 1/0 ) | featureA > = 17980.32featureC = ABC BLAH BLAH blA ' H $ blah 4/ blah blah Pattern.compile ( `` ( ? : \\| ) * ( .* ? ) ( > ? =| < ) ( ( ? ! : ) . ) * ( ? : : ? ) ( .* ? ) ( ? : \\ ( .*\\ ) ) ? '' ) | Java - Pattern matches but fails to capture |
Java | I change a value that is used to determine when a while-loop terminates in a seperate thread . I do n't want to know how to get this working . If I access the variable test only through synchronized getters/setters it works as expected..I would have expected , if some read/write commands are lost due to concurrency the... | public class CustomComboBoxDemo { public static boolean test = true ; public static void main ( String [ ] args ) { Thread user =new Thread ( ) { @ Override public void run ( ) { try { sleep ( 2000 ) ; } catch ( InterruptedException e ) { } test=false ; } } ; user.start ( ) ; while ( test ) { System.out.println ( `` fo... | Strange behavior in Java with unsyncronized access in a multithreading program |
Java | How can I get type safety for a set of classes when there are cyclic relationships . I have 3 classes , Router , Interactor and Component such thatI want to ensure that a specific router is tied to a specific component and specific interactor.Edit The architecture of the app ensures that we have exactly 1 router for 1 ... | abstract class Router < C extends Component , I extends Interactor > abstract class Interactor < R extends Router > abstract class Component < I extends Interactor > | Java Cyclic Generics |
Java | My code : As you see , in line x , T have to be String.class and returns String . But compile failed without casting the result to T. Change line x to return new String ( `` abc '' ) ; results Incompatible types . | private static < T > T get ( Class < T > clazz ) throws IllegalAccessException , InstantiationException { if ( clazz.equals ( String.class ) ) { return ( T ) new String ( `` abc '' ) ; //line x } else { return clazz.newInstance ( ) ; } } | Why I must cast to Generic Type T even if I know it returns correctly ? |
Java | I have this code : I know I can declare a function which hold lambda : I want to make this function to hold implementation of Runnable from new Thread.But I do n't know what to put between < > of Function . | new Thread ( ( ) - > { //do things } ) .start ( ) ; new Thread ( ( ) - > { //do same things } ) .start ( ) ; Function < Integer , Integer > add = x - > x + 1 ; | Function which hold implementation of Runnable |
Java | I was posting an answer to a different question , when I came across a little mystery . The class definition ( slightly modified from the original questioner ) is here : In main , we then create a new Playground , Playground < String > animals = new Playground < String > ( 5 ) ; and put some animal Strings in it . ( Do... | public class Playground < T > { private int pos ; private final int size ; private T [ ] arrayOfItems ; public Playground ( int size ) { this.size = size ; pos = 0 ; arrayOfItems = ( T [ ] ) new Object [ size ] ; } public void addItem ( T item ) { arrayOfItems [ pos ] = item ; pos++ ; } public void displayItems ( ) { f... | Array return can be used in assignment , but not in loop |
Java | I encountered the following behavior while using a ByteBuffer . It looks like a bug to me , but perhaps I 'm using the libraries incorrectly.Code : Output : What 's the deal with the leading space ? Am I doing something wrong ? Is this expected behavior ? If so , why ? | public static void main ( String [ ] args ) { byte [ ] byteArray = `` hello '' .getBytes ( Charset.forName ( `` UTF-16 '' ) ) ; CharBuffer buffer = ByteBuffer.wrap ( byteArray ) .asCharBuffer ( ) ; System.out.println ( buffer.length ( ) ) ; for ( int i = 0 ; i < buffer.length ( ) ; i++ ) { System.out.print ( buffer.get... | Why is the first character in the CharBuffer returned by ByteBuffer : :asCharBuffer always a space ? |
Java | If multiple fields are declared in a single statement using a field annotation , does the annotation apply to all of the fields ? For example , will the following result in x , y , and z all having the @ Nullable annotation ? I 'm looking for an official specification on this , but have had trouble finding one . | @ Nullable public Integer x , y , z ; | Do annotations apply to all variables in a declaration statement ? |
Java | Should defensive copies always be made for object references of mutable objects passed to constructors ? If yes , then how 'deep ' should I go in making copies . In the following example should I make deep copies inside copy constructors of all classes involved ? Eg:3.. What if some class forgets to implement deep copy... | class Graph { AdjacencyList ; public Graph ( Graph graph ) { this.list = graph.list ; // shallow copy OR this.list = ArrayCopy ( graph.list ) ; // deep copy } } class DFS implements GraphAlgo { Graph g DFS ( Graph g ) { this.g = g ; // shallow copy OR this.g = new Graph ( graph ) // deep copy } DFS ( Algo algo ) { this... | How deep should copy constructors get |
Java | How could I parse the following String to a LocalDateTime-Object ? 20200203092315000000I always get the following exception but I did n't understand it : My application code looks like : | java.time.format.DateTimeParseException : Text '20200203092315000000 ' could not be parsed at index 0 at java.time.format.DateTimeFormatter.parseResolved0 ( DateTimeFormatter.java:1949 ) at java.time.format.DateTimeFormatter.parse ( DateTimeFormatter.java:1851 ) at java.time.LocalDateTime.parse ( LocalDateTime.java:492... | How do I parse an ISO-8601 formatted string that contains no punctuation in Java 8 ? |
Java | Fianlly , the console prints a NullPointerException error . The CoreJava says that we should n't modify the Collection which will return back to the stream after modified . And I do n't have a clear understanding of the principle . | List < String > list = new ArrayList ( ) { { add ( `` apple '' ) ; add ( `` banana '' ) ; add ( `` orange '' ) ; } } ; Stream < String > stringStream = list.stream ( ) ; stringStream.forEach ( m- > { if ( m.equals ( `` banana '' ) ) { list.remove ( `` banana '' ) ; } } ) ; System.out.println ( stringStream.count ( ) ) ... | Transfer a List into a Java Stream , and then delete a element of the List.Some errors occur |
Java | I 'm installing a production Crafter 3.0 instance built from source , using the current documentation as guidance . However , I 'm having issues at this point : I ca n't find the INSTALL_DIR/apache-tomcat/solr-crafter/conf/solrconfig.xml file , and solr itself seems to be in different path . | Change the path where the preview Solr search indexes will be stored , e.g . /opt/crafter/data/preview-indexes : In INSTALL_DIR/apache-tomcat/solr-crafter/conf/solrconfig.xml , update the value of < dataDir > to the preview indexes folder path ( e.g . < dataDir > /opt/crafter/data/preview-indexes < /dataDir > ) . | In CrafterCMS , how do I configure Solr in Crafter 3.0 ? |
Java | Is there any difference among case1 , case2 and case3 ? Is there any advantage or disadvantage related to performance ? | public class Test { private String name ; public void action ( ) { name = doSome ( ) ; // case 1 setName ( doSome ( ) ) ; // case2 this.name =doSome ( ) ; // case3 } public String doSome ( ) { return `` Hello '' ; } /** * @ return the name */ public String getName ( ) { return name ; } /** * @ param name the name to se... | Java Variable setting |
Java | My code is : '' solveIt '' method returns after 30 seconds and until it returns , frame is n't installed properly but after solveIt method returns , the frame gets installed properly but what i want is that before going into solveIt method , the frame should be properly on the screen . Is there any method that can wait... | solveDb_userfileInconsistency solve = new solveDb_userfileInconsistency ( ) ; solve.setVisible ( true ) ; try { solve.solveIt ( ) ; } catch ( InstantiationException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; } catch ( IllegalAccessException e ) { // TODO Auto-generated catch block e.printStackTrac... | JFrame is loaded late |
Java | I am new to OODP , I am trying to have a method that is able to take in any kind of List data so that I can abstract things out . How can i do this ? | public abstract class CommonClass { abstract void send ( < what should i put here ? ? ? > ) { } } public class ClassA extends CommonClass { void send ( List < Comments > commentsList ) { // do stuff } } public class ClassB extends CommonClass { void send ( List < Post > postList ) { // do stuff } } | Abstract method with different parameters Java |
Java | Consider the following visitor for a simple language interpreter.For completeness I add some code that gives necessary implementation details ( you can skip and read directly the question ) .a var statement is defined like that : a valid language instanceAn abstract way to represent the VarStat node is the following : ... | public interface Visitor { void visit ( VarStat vs ) ; void visit ( Ident i ) ; void visit ( IntLiteral a ) ; void visit ( Sum s ) ; } public interface Visitable { void accept ( Visitor v ) ; } public class VarStat implements Visitable { Ident i ; Exp e ; public VarStat ( Ident id , Exp ex ) { i = id ; e = ex ; } publi... | Is skipping `` accept '' where type is known , a valid optimization for the Visitor pattern ? |
Java | Can the AdditionalBound described in JLS8 cast expression be used for casting anything except that a lambda expression or a method reference ? It is said , that it could be : and that : The target type for the casting context ( §5.5 ) introduced by the cast expression is ( ... ) the intersection type denoted by the Ref... | ( ReferenceType { AdditionalBound } ) UnaryExpressionNotPlusMinus X x = ( I1 & I2 ) some_UnaryExpressionNotPlusMinus Object l1 = ( Collection & Iterable ) new ArrayList < > ( ) ; List l2 = ( ByteList & Iterable ) new ArrayList < > ( ) ; Collection l3 = ( List & Iterable ) new ArrayList < > ( ) ; | Using of AdditionalBound in cast expressions |
Java | A new feature of Java 9 is that it can not only forcefully kill processes ( in the meaning of SIGKILL ) it had created but it may also support to send a SIGTERM ( in Java called `` normal termination '' ) .According to the documentation of Process one can query if the implementation supports this : public boolean suppo... | Process p = Runtime.getRuntime ( ) .exec ( `` javaw -cp target/classes TestClassWait10Minutes '' ) ; p.waitFor ( 5 , TimeUnit.SECONDS ) ; System.out.println ( p.supportsNormalTermination ( ) ) ; | Any VM supporting Process.supportsNormalTermination==true ? |
Java | I 'm trying to teach myself Java Networking . I tried to write a little WebChat-Application and it runs just fine when I 'm trying to run it in Eclipse , but when I 'm trying to run it in Debug-Mode I keep getting this error : I tried to fix it but I failed many times ... This is my code : | Thread [ AWT-EventQueue-0 ] ( Suspended ( exception NullPointerException ) ) owns : Object ( id=39 ) File. < init > ( String ) line : 251 LoadNativeBundleAction.run ( ) line : 79 AccessController.doPrivileged ( PrivilegedExceptionAction < T > ) line : not available [ native method ] MacOSXResourceBundle.getMacResourceB... | NullPointerException at Thread AWT-EventQueue-0 ( File. < init > ) |
Java | Say I have this : my question is - how can I define the thread that 's used in the pool , specifically would like to override the interrupt method on thread ( s ) in the pool : | class Queue { private static ExecutorService executor = Executors.newFixedThreadPool ( 1 ) ; public void use ( Runnable r ) { Queue.executor.execute ( r ) ; } } @ Override public void interrupt ( ) { synchronized ( x ) { isInterrupted = true ; super.interrupt ( ) ; } } | Override interrupt method for thread in threadpool |
Java | I am creating JDBC Statements and ResultSets.Findbugs rightly points out that I do n't close these if an exception is thrown.So now I have : ( Only I have rather more result sets and prepared statements and so on open ... so my nesting of finallys is rather deeper ) There has to a better way to ensure a large number of... | Statement stmt = null ; ResultSet res = null ; try { stmt = ... res = stmt.executeQuery ( ... ) ; ... } finally { try { if ( res ! = null ) res.close ( ) ; // < -- can throw SQLException } finally { if ( stmt ! = null ) stmt.close ( ) ; } } | Ensure objects are closed if an exception is thrown |
Java | I have a generic class with this definition : Where AntColony goes this way : And Ant goes like this : I was hoping to extend AntColony in this fashion : But Eclipse is showing an error on the FlowShopAntColony parameter class : Which confuses me , since FlowShopAntColony is defined this way : And AntForFlowShop goes l... | public class AcoProblemSolver < C , E extends Environment , A extends AntColony < E , Ant < C , E > > > { public abstract class AntColony < E extends Environment , A extends Ant < ? , E > > { public abstract class Ant < C , E extends Environment > { public class FlowShopProblemSolver extends AcoProblemSolver < Integer ... | Java generics : Bound mismatch |
Java | In Java , is giving 4 as an output and notas expected by me . | 4 % -8 -4 | Why is 4 % -8 equal to 4 ? |
Java | For some reason I do n't understand why this code prints true and false , what is special about array that it does not include that annotation here ? It works as expected if you use getParameters instead . | import java.lang.annotation . * ; @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( { ElementType.TYPE_USE , ElementType.PARAMETER } ) @ interface Lel { } class Test { public static void a ( @ Lel String args ) { } public static void b ( @ Lel String [ ] args ) { } public static void main ( String [ ] args ) throws Ex... | Why getAnnotatedParameterTypes does not see annotations for array type ? |
Java | My mystery begins like this . Consider this bit of code : If you look past most of the scaffolding ( I just wanted to make sure it 's minimally complete and you can run your compiler on it ) , you 'll see in the middle there 's an annotation , and it takes a String array initializer , and there 's a comma after `` thin... | import java.util.Set ; import javax.annotation.processing . * ; import javax.lang.model.element.TypeElement ; @ SupportedOptions ( { `` thing1 '' , `` thing2 '' , } ) public class fc extends AbstractProcessor { @ Override public boolean process ( Set < ? extends TypeElement > anns , RoundEnvironment re ) { return false... | Java : ever seen a compiler or tool that REJECTS a final comma in array initializer ? |
Java | It 's not exactly as the title says , but close to . Consider these Spring beans : Important note : I 'm using JDBC transaction manager that supports savepoints.What I 'm expecting this to do is , when EvilException is thrown , the transaction of the BeanA is rolled back , which with this setup happens to be the savepo... | @ Beanclass BeanA { @ Transactional ( propagation = Propagation.REQUIRED , rollbackFor = EvilException.class ) public void methodA ( ) { /* ... some actions */ if ( condition ) { throw new EvilException ( ) ; } } } @ Beanclass BeanB { @ Autowired private BeanA beanA ; final int MAX_TRIES = 3 ; @ Transactional ( propaga... | Rollback for doubly nested transaction bypasses savepoint |
Java | I have two separate entities : and Where andGenericValidator is an abstract class having a number of subclasses I would not like users to access directly . How should I handle those things better ? I do n't understand when it 's better to create a class likeinstead of implementing the Validatable interface as I shown e... | public enum Rule implements Validatable , StringRepresentable { // ... } public inteface Filter extends Validatable , StringRepresentable { // ... } public inteface Validatable { public GenericValidator getValidator ( ) ; } public interface StringRepresentable { public String getStringRepresentation ( ) ; } public clas... | Using FactoryMethod pattern |
Java | Which are the default modifiers for x and m in ? I suppose that the code above is equivalent to : where the modifiers public and public static final are redundant , but I did n't find an official explanation for this.I was looking here : https : //docs.oracle.com/javase/8/docs/technotes/guides/language/annotations.html... | public @ interface Anno { int m ( ) default x ; int x = 10 ; } public @ interface Anno { public int m ( ) default x ; public static final int x = 10 ; } | Which are the default modifiers for fields and methods in a Java annotation ? |
Java | Just to give you a background which probably has nothing to do with the question . Trying to use the JAHMM library to build and score HMM's.One of the parameters to the functions mentions the above as the datatype and I have no idea what it means.From what I understand with help from a friendList < ? extends Observatio... | List < ? extends List < ? extends ObservationInteger > > | Confused by the following data type |
Java | Why when I use reference this in a variable declaration , illegal forward reference does n't appear ? What 's the difference between declaration with this and without it ? The following example fails to compile because of the illegal forward reference : By qualifying the use of b by this the compilation error goes away... | class FailsToCompile { int a = b ; //illegal forward reference int b = 10 ; } class Compiles { int a = this.b ; //that 's ok int b = 10 ; } | Problem with illegal forward reference in Java |
Java | In String functions like substring ( ) returns helwhereas 0-3 index includes helland in regex Matcher 's end ( ) methodreturns 4 whereas first match ends at index 3I 'm just curious about why java works in this way | `` hello '' .substring ( 0 , 3 ) mat = Pattern.compile ( `` test '' ) .matcher ( `` test '' ) ; mat.find ( ) ; System.out.println ( mat.end ( ) ) ; | Why Java uses one past index for upper bound in string operations ? |
Java | I am recently started using java stream and write a one User service , which returns a stream of users . Using that user stream , I process other logic . Following is the piece of code that I am dealing with stream and it works fineBut when I start writing Junit then it fails with following error message.Here is my uni... | try ( Stream < User > users = userService.getStream ( ) ) { users.forEach ( user - > { } ) ; java.lang.IllegalStateException : stream has already been operated upon or closed at java.util.stream.AbstractPipeline.sourceStageSpliterator ( AbstractPipeline.java:279 ) at java.util.stream.ReferencePipeline $ Head.forEach ( ... | How to write Junit for Java Stream |
Java | I needed to dig into the specifics of method invocation in Java , and while reading the section Choosing the Most Specific Method in The Java Language Specification ( Java SE 12 Edition ) , I found that ( 1 ) during invocation multiple methods can be maximally specific and that ( 2 ) having multiple maximally specific ... | interface A { } interface B { } class C implements A , B { < T extends A > void foo ( T t ) { } ; < T extends B > void foo ( T t ) { } ; } class Main { public static void main ( String [ ] args ) { new C ( ) . < C > foo ( null ) ; } } | Example of multiple maximally specific methods that does not result in a compile-time error |
Java | If i change the byte to int I get a compiler error . Could you explain the problem ? | public class A { protected int xy ( int x ) { return 0 ; } } class B extends A { protected long xy ( int x ) { return 0 ; } //this gives compilor error //protected long xy ( byte x ) { return 0 ; } // this works fine } | Why do I get a compilation error when I try to have two methods with the same name and parameter type ? |
Java | Why is it that trying to catch an exception that will not occurr , will give a compilation error , whereas I can throw any Exception , it wo n't give an error ? Both can be checked at compile time , so it would just make more sense to me if the behavior is the same ? In the given example , the catch-block will generate... | public void throwTest ( ) throws SQLException , IOException { try { } catch ( SQLException e ) { } } | Why can you throw a non occurring exception but not catch it |
Java | I am creating an Android application . I am new to android . I want to create a label like in the image below . Here is the below code that I have tried.I have labels over the images . Any help will be appreciated . Thanks | < FrameLayout android : layout_weight= '' 1 '' android : layout_gravity= '' center '' android : layout_width= '' 80dp '' android : layout_height= '' 80dp '' android : id= '' @ +id/fl_bg '' > < ImageView android : layout_gravity= '' center '' android : id= '' @ +id/iv_avatar '' android : layout_width= '' 80dp '' android... | android custom user interface |
Java | I 'm solving a Project Euler Problem 14 using java . I am NOT asking for help solving the problem . I have already solved it , but I ran into something I ca n't figure out.The problem is like this : The following iterative sequence is defined for the set of positive integers : n = n/2 , if n is even n = 3n + 1 , if n i... | public class Euler014 { public static void main ( String [ ] args ) { int maxChainCount = 0 ; int answer = 0 ; int n ; int chainCount = 1 ; for ( int i = 0 ; i < 1000000 ; i++ ) { n = i ; while ( n > 1 ) { if ( n % 2 == 0 ) { //check if even n /= 2 ; } else { //else : odd n = 3*n + 1 ; } chainCount++ ; } if ( chainCoun... | Use of integers and doubles give different answers when they should n't |
Java | Suppose I am modelling different animals in Java . Every animal has some combination of these abilities : walk , swim and fly . For the example , the ability set is constant . I can store this information as getters that return constants . For example : The run-time check is then : Or I can use `` tagging '' interfaces... | public class Penguin implements Animal { public boolean canWalk ( ) { return true ; } public boolean canSwim ( ) { return true ; } public boolean canFly ( ) { return false ; } // implementation ... } if ( animal.canFly ( ) ) { // Fly ! } public class Penguin implements Animal , Flyer , Swimmer { // implementation ... }... | In Java , should I use getters or interface tagging for constant properties ? |
Java | I would like to know how can I get all the elements from a collection containing a specific value.Like this : But I would like to filter the collection directly . I read that I can do this using LAMBDA , example : But I Do n't know how to apply this example.Thank you . | @ Overridepublic Collection < Sale > selectSales ( String map ) { HashSet < Sale > sales = new HashSet ( ) ; for ( Sale sale : salesList ) { if ( sale.getMap ( ) .equals ( map ) ) { sales.add ( sale ) ; } } return sales ; } list.removeIf ( c - > c.getCarColor ( ) == Color.BLUE ) ; | How can I filter directly a collection based on a value ? |
Java | I found this in some code I wanted to optimize . Here is the snipet : Then I decided to use the regex wisely and I did this : Then a friend told me to do this instead : Since I like to know the result of my changes I did a test to verify if it was a good optimization . So , the result with ( java version `` 1.6.0_27 ''... | tempString = bigBuffer.replaceAll ( `` \\n '' , `` '' ) ; tempString = tempString.replaceAll ( `` \\t '' , `` '' ) ; tempString = bigBuffer.replaceAll ( `` [ \\n\\t ] '' , `` '' ) ; tempString = bigBuffer.replaceAll ( `` \\n|\\t '' , `` '' ) ; | Is this normal Java regex behavior ? |
Java | why my thread ca n't be stopped ? ? ? if i use rp.num == 0 , the thread can be stopped immediately . But , why when i changed the rp.num == x ( x is any number greater than 0 ) the thread can not stop ? please help me solve this thing ... thanks for any helps . | class Threadz { class runP implements Runnable { int num ; private volatile boolean exit = false ; Thread t ; public runP ( ) { t = new Thread ( this , `` T1 '' ) ; t.start ( ) ; } @ Override public void run ( ) { while ( ! exit ) { System.out.println ( t.currentThread ( ) .getName ( ) + '' : `` +num ) ; num++ ; try { ... | Thread can not stop |
Java | While going through the libgdx source code for a Stage , I encountered this segment : ( Link on GitHub . ) What interested me was this line : Batch batch = this.batch ; My first guess was some caching improvement . Am I right , or is there another reason to avoid using the instance variable directly ? | public void draw ( ) { Camera camera = viewport.getCamera ( ) ; camera.update ( ) ; if ( ! root.isVisible ( ) ) return ; Batch batch = this.batch ; if ( batch ! = null ) { batch.setProjectionMatrix ( camera.combined ) ; batch.begin ( ) ; root.draw ( batch , 1 ) ; batch.end ( ) ; } if ( debug ) drawDebug ( ) ; } | Java Local reference over instance variable |
Java | Can anyone explain how this code snippet works ... The actual code itself is not relevant as it was from a short tutorial on using an MVP pattern for Android.My main question is how this code structure works and whether this is an inner class , of sorts , or maybe a transaction.. I have n't seen a code structure like t... | public void loadCustomer ( int id ) { ( mCustomerModel.load ( id ) ) { mCustomerView.setId ( mCustomerModel.getId ( ) ) ; mCustomerView.setFirstName ( mCustomerModel.getFirstName ( ) ) ; mCustomerView.setLastName ( mCustomerModel.getLastName ( ) ) ; } } | Is this an Inner Class |
Java | Given AGenericClass declared as below : What are the differences between variables a , b , and c ? a b and c all are declared without complaint from the IDE , but they all behave differently when setSubject is called . | public class AGenericClass < T > { T subject ; public void setSubject ( T subject ) { this.subject = subject ; } } AGenericClass < String > a = new AGenericClass < > ( ) ; AGenericClass < ? > b = new AGenericClass < String > ( ) ; AGenericClass c = new AGenericClass < String > ( ) ; a.setSubject ( `` L '' ) ; // OK.b.s... | How do these three parameterized variables differ ? |
Java | Same regex , different results ; JavaJavaScriptI ca n't understand why this is the case ? | String regex = `` Windows ( ? =95|98|NT|2000 ) '' ; String str = `` Windows2000 '' ; Pattern p = Pattern.compile ( regex ) ; Matcher m = p.matcher ( str ) ; System.out.println ( m.matches ( ) ) ; // print false var value = `` Windows2000 '' ; var reg = /Windows ( ? =95|98|NT|2000 ) / ; console.info ( reg.test ( value )... | Same regex have different results in Java and JavaScript |
Java | I am trying to call a java method which takes List < Class < ? > > from scala . The compilation fails with I tried using JavaConverters but get the same error.Java method : Calling from Scala : | type mismatch ; found : java.util.List [ Class [ T ] ] where type T < : Person.type required : java.util.List [ Class [ _ ] ] void registerClasses ( List < Class < ? > > var1 ) ; def registerEntities ( ) = registry.registerClasses ( List ( Person.getClass ) .asJava ) | How to call java method taking parameter as List < Class < ? > > from Scala |
Java | The question might be foolish as intern has no major usage here , still I am confused about the fact , why does b == c results true.Whenis executed , String b references to object having `` bc '' Does b.intern create the literal `` bc '' in String Constant pool , even if it does , how come b==c result in true ? | String a = `` abc '' ; String b = a.substring ( 1 ) ; b.intern ( ) ; String c = `` bc '' ; System.out.println ( b == c ) ; String b = a.substring ( 1 ) | How does intern work in the following code ? |
Java | At first glance I thought the following makes sense : And it compiles properly so everything seems A-OK.But then I thought about it some more , in the context of erasure , and it seems to me that the Test interface gets erased to this : So how is Impl still able to implement Test ? | interface Test < T > { T getValue ( T n ) ; } class Impl implements Test < Integer > { public Integer getValue ( Integer n ) { return n ; } } interface Test { Object getValue ( Object n ) ; } | Why does erasure still allow overriding/implementation ? |
Java | I am considering this from the Java Language Specification : If the catch block completes abruptly for reason R , then the finally block is executed . Then there is a choice : If the finally block completes normally , then the try statement completes abruptly for reason R. If the finally block completes abruptly for re... | try { .. do stuff that might throw RuntimeException ... } finally { try { .. finally block stuff that might throw RuntimeException ... } catch { // what to do here ? ? ? } } | Java - detect whether there is an exception in progress during ` finally ` block |
Java | Hi , the code above gives an error like that : Multiple markers at this line - str can not be resolved to a variable - Syntax error on token `` String '' , AssignmentOperator expected after this tokenWhy there is an error like this ? Of course I know str will be unreachable after defined . But java does n't gives an ex... | if ( true ) String str ; | non-braces if block variable definition gives an error |
Java | I am somewhat mystified by the output of this program : Here 's what it outputs : It appears the compiler is `` promoting '' an object of type Integer to Long , just as it would normally promote primitive values . I 've never heard of object promotion and this behavior seems very surprising.My question : is this really... | public class xx { public static void main ( String [ ] args ) throws Exception { Number x = false ? new Long ( 123 ) : new Integer ( 456 ) ; System.out.println ( x + `` isa `` + x.getClass ( ) .getName ( ) ) ; } } 456 isa java.lang.Long java version `` 1.8.0_60 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_60-b27... | Does the Java JLS specify promotion of primitive wrapper types ? |
Java | I want to make a method that accepts any class T that implements any interface I.Then do something with the class and return the interface I that is implemented.Here 's what I 've tried : I 'm then creating an interface and a class which implements that interface : However , when I 'm calling the method referencing Use... | class MyLibrary { public static < I , T extends I > I registerImplementation ( Class < T > classImpl ) { I interfaceImpl = ( I ) classImpl.newInstance ( ) ; return interfaceImpl ; } } interface UserInterface { void doSomethingDefined ( ) ; } class UserClass_v1_10_R2 implements UserInterface { @ Override public void doS... | How to return interface from generic class implementing the interface ? |
Java | I try to find the current Browser for an specific Hack in GWT.like : ( View-class ) | if ( GWT.getBrowserName ( ) .contains ( `` IE '' ) ) { // DOM.setElementPropertyBoolean ( ... Hack } else { // normal stuff } | GWT Browser distinction in Client |
Java | In the book `` Core Java Volume 1 '' that I am reading it says the equality should n't work with inheritance . So , I have the following example which seems to have something wrong going on : http : //ideone.com/PhFBwGIt returns `` Equal '' for both symmetrical comparisons which presumably it should n't . Is it missing... | public class Main { public static void main ( String [ ] args ) { C c = new C ( `` Test '' , 10 ) ; D d = new D ( `` Test '' , 10 ) ; if ( c.equals ( d ) ) System.out.println ( `` Equal '' ) ; else System.out.println ( `` Unequal '' ) ; if ( d.equals ( c ) ) System.out.println ( `` Equal '' ) ; else System.out.println ... | What 's wrong with using Inheritance Equality in Java ? |
Java | In this case , I need to explicitly convert a+b to byte like this : It 's the same with short : Otherwise it gives an error.But in case of integers , it 's not required to convert explicitly : This will work just fine.Why is that ? We do n't need to explicitly cast even in the case of long as well . | byte a=10 ; byte b=20 ; b=a+b ; b= ( byte ) ( a+b ) ; short x=23 ; short y=24 ; int p=7788 ; int q=7668 ; p=p+q ; | Why is there no need to explicitly cast in case of integers ? |
Java | I am getting below output in following format , which is default I think.But I want to change this format as below.Below code I am using in java class.How can I rearrange the json format ? For more understanding , pasting above method with simple syntax.Sample Code Method.. | { `` count '' :100 , '' sum '' :25640.13 , '' min '' :2.65 , '' max '' :483.91 , '' average '' :256.4013 } { `` sum '' : '' 25640.13 '' , '' avg '' : '' 256.40 '' , '' max '' : '' 483.91 '' , '' min '' : '' 2.65 '' , '' count '' :100 } @ Overridepublic DoubleSummaryStatistics getStatistic ( ) { logger.info ( `` Getting... | How can we customize order of count , avg , sum , min and max in DoubleSummaryStatistics object in java8 |
Java | The traditional way to iterate over an ( integer , in this example ) array of elements is the following : However , does this mean that after each iteration 'array.length ' is re-evaluated ? Would it not be more efficient to do this ? : In this way , ( to my understanding ) the program only has to calculate it once and... | int [ ] array = { 5 , 10 , 15 } ; for ( int i = 0 ; i < array.length ; i++ ) [ //do something with array [ i ] } int [ ] array = { 5 , 10 , 15 } ; int noOfElements = array.length ; for ( int i = 0 ; i < noOfElements ; i++ ) { //do something with array [ i ] } | Is there a difference in runtime efficiency if I evaluate the size of the array outside the loop ? |
Java | I 've read everywhere that if a field is used at the same time by different threads , some sort of synchronization is needed , and that if it is used by only one thread , it 's not needed . But what if it 's used by different threads , but not at the same time ? Let 's take a code like this : MyRunnable is : Is it safe... | Thing thing = new Thing ( ) ; Thread t1 = new Thread ( new MyRunnable ( thing ) ) ; Thread t2 = new Thread ( new MyRunnable ( thing ) ) ; t1.start ( ) ; t1.join ( ) ; //Wait for t1 to finisht2.start ( ) ; class MyRunnable implements Runnable { //skipped constructor and field `` private final Thing thing '' public void ... | Is it safe to use an object in different threads , but NOT at the same time ? |
Java | Say I have a method : but sometimes when I run this method , I do n't need to synchronize on anything.What is a good pattern to conditionally synchronize on something ? The only pattern I can think of is a callback , something like this : is there another way to do it , without a callback ? | public void run ( ) { synchronized ( this.foo ) { } } public void conditionalSync ( Runnable r ) { if ( bar ) { r.run ( ) ; return ; } synchronized ( this.foo ) { r.run ( ) ; } } public void run ( ) { this.conditionalSync ( ( ) - > { } ) ; } | Conditionally define synchronized block |
Java | Straight out from Java concurrency in Practice : The above is a Thread-safe class : since its setters are synchronized.I understand also why the getter does n't individually return x / y but instead returns an array . I have 2 questions .Why ? private SafePoint ( int [ ] a ) public SafePoint ( SafePoint p ) { this ( p.... | @ ThreadSafepublic class SafePoint { @ GuardedBy ( `` this '' ) private int x , y ; private SafePoint ( int [ ] a ) { this ( a [ 0 ] , a [ 1 ] ) ; } public SafePoint ( SafePoint p ) { this ( p.get ( ) ) ; } public SafePoint ( int x , int y ) { this.x = x ; this.y = y ; } public synchronized int [ ] get ( ) { return new... | Multithreading private constructor |
Java | I often find myself doing something like this : where f is a computation intensive function . This requires twice as many evaluations of f as are actually necessary . I 'd prefer to but then I do n't know how to get the original element that this minimum corresponds to.One ugly way around this isand thenIs there a bett... | list.stream ( ) .min ( new Comparator < > ( ) { @ Override public int compare ( E a , E b ) { return Double.compare ( f ( a ) , f ( b ) ) ; } } ) list.stream ( ) .mapToDouble ( f ) .min ( ) class WithF < E > { private final E e ; private final double fe ; WithF ( E e , double fe ) { this.e = e ; this.fe = fe ; } public... | Find pre-map element in stream corresponding to post-map minimum |
Java | I was answering this question , where I recommended utilizing exports to syntax to prevent external consumers from accessing code that is intended for internal use between modules.But on further reflection , the only real safety checking that modules implement is that it matches the name . Consider this example where I... | module a { exports unsafe to b } module b { requires a } | Securely Export Packages to Java Modules |
Java | I am trying to write the Data Structure for a Hash Table using Chaining . When i remove the keyword `` static '' from the nested class , i get the error that `` Can not create a generic array of SeparateChaining.Node '' ? on the line where i allocate memory to hmap using new.With the static keyword it works fine.Can an... | public class SeparateChaining < Key , Value > { private int m ; private Node [ ] hmap ; private int n ; public SeparateChaining ( ) { m=5 ; n=0 ; //error here on removal of static keyword from the node class declaration hmap=new Node [ m ] ; } private ____ class Node //works fine with static . Otherwise shows error { p... | For a Generic outerclass , why do i need to declare the nested class static ? |
Java | I am experimenting with DateFormat and I 've come across an issue where I 'm creating a date , storing it as a string and then parsing it back into a date and somehow ending up with the same date but a different day of the week.I get the output ; If I make the number of milliseconds in d1 smaller then when the date is ... | import java.text . * ; import java.util . * ; public class Dates { public static void main ( String [ ] args ) { Date d1 = new Date ( 1000000000000000L ) ; System.out.println ( `` d1 = `` + d1.toString ( ) ) ; DateFormat df = DateFormat.getDateInstance ( DateFormat.SHORT ) ; String s = df.format ( d1 ) ; System.out.pri... | Why is there a 1 day difference in these dates ? |
Java | I followed an instruction to trigger the JavascriptInterface from a webview , but it isnt triggered in my case.I have an class QuickTextViewer with following : I also added the following to proguard-rules.pro ( actually public only for testing ) In my case onPageFinished is triggered but resize ( ) not ! Any suggestion... | public class QuickTextViewer { private WebView webView ; ... ... public QuickTextViewer ( ) { webView = dialog.findViewById ( R.id.mywebview ) ; webView.setWebViewClient ( new WebViewClient ( ) { @ Override public void onPageFinished ( WebView view , String url ) { view.loadUrl ( `` javascript : MyApp.resize ( document... | triggering JavascriptInterface from a android webview |
Java | I was using LongStream 's rangeClosed to test the performance of the sum of the numbers . When I tested the performance through JMH , the result was as below.The difference between rangedReduceSum and rangedSum is that only the internal function sum ( ) is used . Why is there so much performance difference ? After veri... | @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.MILLISECONDS ) @ Fork ( value = 1 , jvmArgs = { `` -Xms4G '' , `` -Xmx4G '' } ) @ State ( Scope.Benchmark ) @ Warmup ( iterations = 10 , time = 10 ) @ Measurement ( iterations = 10 , time = 10 ) public class ParallelStreamBenchmark { private static final ... | Why is there a difference between LongStream reduce and sum performance ? |
Java | We have a Student class as follows : We have a LIST of Students as follows : This List needs to be converted into a HashMap < String , Integer > such that : the map does not contain any duplicate Studentif a duplicate student name is found , his marks shall be added withthe previous occurrence.So the output should be :... | class Student { private int marks ; private String studentName ; public int getMarks ( ) { return marks ; } public void setMarks ( int marks ) { this.marks = marks ; } public String getStudentName ( ) { return studentName ; } public void setStudentName ( String studentName ) { this.studentName = studentName ; } public ... | Transform a List < Object > to a Map < String , Integer > such that the String is not a duplicate value using Java 8 Streams |
Java | I have the following collection : Here 's sample data : Since I know all enums , I want to convert it to the list of POJO . The definition of the object is as below : I have tried different solutions , like with mapping inside mapping : Unfortuantely , what I am getting is List < List < SomeClass > > . Is there any oth... | Map < String , Map < SomeEnum , Long > > map = ... { `` Foo '' : { SomeEnum.BAR1 : 1 , SomeEnum.BAR2 : 2 , SomeEnum.BAR3 : 3 } , `` two '' : { ... } class SomeClass { String name ; long bar1Value ; long bar2Value ; long bar3Value ; } map.entrySet ( ) .stream ( ) .map ( e - > e.getValue ( ) .entrySet ( ) .stream ( ) .ma... | Convert Map < ? , Map < ? , ? > to List of Objects |
Java | I have a question , a little bit theoretical : Assume , I have the following classes : The second report needs an additional parameter release to work properly , but my interface is defined without parameters for execute method , so I work around it with a setter method , so it would look like : So I do n't like this a... | interface ReportInterface { void execute ( ) ; } class Report implements ReportInterface { private final Repository rep ; Report ( Repository ref ) { this.rep = ref ; } public void execute ( ) { //do some logic } } class ReportWithSetter implements ReportInterface { private final Repository rep ; private String release... | Java - Getter/Setter , behavior and Interfaces |
Java | What am I looking for ? Let 's consider int a = 5 for exampleIts binary is : 101So when we dothen the rightmost bit , i.e. , 1 in this case , would drop off , I want to catch it in some variable..i.e. , In this case I have a hard-coded value but it can be any arbitrary user input for number.If I do b = a > > 1 then b= ... | a > > 1 1st iteration k = 1 2nd iteration k = 0 3rd iteration k = 1 | Catching the `` dropping '' bit value |
Java | Consider an object which produces data that is consumed by another object to generate a result . The process is encapsulated in a class and the intermediate data is not relevant.In the example below , the process takes place on construction and there is no issue . The type parameter on the constructor ensures compatibl... | public class ProduceAndConsume { public interface Producer < T > { T produce ( ) ; } public interface Consumer < V > { void consume ( V data ) ; } public < IntermediateType > ProduceAndConsume ( Producer < ? extends IntermediateType > producer , Consumer < IntermediateType > consumer ) { consumer.consume ( producer.pro... | Enforce class fields to be same generic type without specifying a class type parameter |
Java | There is a Spring-MVC project in which there are three types of users : Customer , Admin , Cook . All of them are inherited from the class User . Roles are created without ENUM , simply through static String constants ( shown in the User class ) . After I added Spring Security , authorization is successful , but when I... | { `` timestamp '' : `` 2020-05-08T19:48:43.999+0000 '' , `` status '' : 403 , `` error '' : `` Forbidden '' , `` message '' : `` Forbidden '' , `` path '' : `` /admin/cooks '' } package com.tinychiefdelights.model ; import io.swagger.annotations.ApiModel ; import lombok.Data ; import org.springframework.security.core.G... | Why the application does not see the Roles in Spring Security ( Forbidden ) |
Java | I know that HashSet < String > data structure can store unique strings and say if string is present with O ( 1 ) complexity , because it uses hash code . Can the same complexity be achieved , if I want to ignore letter case ? Next use case should work : Is it possible to implement such data structure ? | Set < String > set = new IgnoreLetterCaseSet ( ) ; set.add ( `` New York '' ) ; set.contains ( `` new york '' ) == true ; set.contains ( `` NEW YORK '' ) == true ; set.each ( it - > print it ) -- - > prints `` New York '' | Data structure that stores strings and ignores letter case |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.