lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I am building some static analysis tools to help manage the architecture of a large project . For this I am doing a couple of regexes to parse information from Java files . One of these regexes is used to scan for an @ WebService ( ... ) annotation . I was wondering if there is a situation possible where there are pare... | @ WebService ( serviceName= '' bla ( ) '' /* bla ( ) */ ) ; @ WebService ( ... ( ... ) ... ) ; | Is there ever a reason to have parentheses within an @ Webservice ( ... .. ) annotation in Java EE ? |
Java | I 'm debug ( Shift + F9 ) the method offer ( E e ) of JDK8 API 's java.util.concurrent.ConcurrentLinkedQueue , i found IntelliJ IDEA will change the field head of this queue soundlessly in the process of debugging , but the run schema ( Shift + F10 ) will not change the field , why ? and there 's no code change this fi... | head : 1159190947 head : 1159190947 head : 1159190947 head : 1159190947 head : 1989972246 head : 1791930789 head : 1791930789 head : 1791930789 head : 1989972246 head : 1989972246 head : 1791930789 head : 1791930789 import java.lang.reflect.Field ; import java.util.concurrent.ConcurrentLinkedQueue ; public class Concur... | Why my object has been changed by IntelliJ IDEA 's debugger soundlessly ? |
Java | I would like to split a string into several substrings , and I think using regular expressions could help me.Note that the curly brackets and comma 's are just a visual aid . It does n't really matter what the final form is , just that the values are seperately accessible/replacable . Thanks in advance . | I want this : To become this : < choice1 > { < choice1 > } c < hoi > ce2 { c , < hoi > , ce2 } < ch > < oi > < ce > 3 { < ch > , < oi > , < ce > , 3 } choice4 { choice4 } | Split a string into several substrings using regex . Both matches and non-matches should be returned |
Java | Here 's the code : It 's a snippet from the book Java Concurrency in Practice , and I 'm thinking about that maybe the counter reservations is unnecessary as we could simply use queue.size ( ) to get the number of elements in queue.Am I right ? | public class LogService { private final BlockingQueue < String > queue ; private final LoggerThread loggerThread ; private final PrintWriter writer ; @ GuardedBy ( `` this '' ) private boolean isShutdown ; @ GuardedBy ( `` this '' ) private int reservations ; // < -- counter public void start ( ) { loggerThread.start (... | Can I use Collection.size ( ) to replace the counter in this code ? |
Java | This might be a really elementary question but it puzzles me at this stage of my Java learning.I have got the following piece of code : If I move the line that instantiates the ArrayList object and the calls on that object outside the method , the line that creates the object is fine but the add ( ) method calls on the... | package com.soti84 ; import java.util.ArrayList ; public class InvokeMethod { public static void main ( String [ ] args ) { ArrayList < String > exams= new ArrayList < String > ( ) ; exams.add ( `` Java '' ) ; exams.add ( `` C # '' ) ; } } package com.soti84 ; import java.util.ArrayList ; public class InvokeMethod { Ar... | Calling a method on an Object from within a Class vs from within a method |
Java | I just noticed that binaries in bin in an old JRockit JDK 6 on CentOS 6 , OpenJDK 8 on Ubuntu 18.10 and Oracle JDK 11 on Windows 11 have approximately the same size.This seems odd since they nothing in common in the tasks they fulfill ( e.g . wsimport and xjc ) . Diffing a hexdump shows that the binaries only differ by... | $ ls -la /usr/lib/jvm/java-8-openjdk-amd64/bin/insgesamt 472drwxr-xr-x 2 root root 4096 Jan 31 08:03 .drwxr-xr-x 7 root root 144 Jan 31 08:03 ..-rwxr-xr-x 1 root root 14504 Jan 14 22:02 appletviewer-rwxr-xr-x 1 root root 14504 Jan 14 22:02 extcheck-rwxr-xr-x 1 root root 14504 Jan 14 22:02 idlj-rwxr-xr-x 1 root root 145... | Why do almost all Java binaries have the same size |
Java | How can I do that ? | public class ActivityTest extends Activity { public EditText edtText ; @ Override public void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.test ) ; WebView webView = ( WebView ) findViewById ( R.id.webView ) ; webView.loadUrl ( `` file : ///android_res/raw/h... | Change text of the edit text by html |
Java | I 'm making a billiards game in Java . I used this guide for collision resolution . During testing , I noticed that there is more velocity between the two collided pool balls after collision . The amount of extra velocity seems to be 0 % -50 % . About 0 % on a straight shot and 50 % on an extremely wide shot . I assume... | private void solveCollision ( PoolBall b1 , PoolBall b2 ) { System.out.println ( b1.getMagnitude ( ) + b2.getMagnitude ( ) ) ; // vector tangent to collision point float vTangX = b2.getY ( ) - b1.getY ( ) ; float vTangY = - ( b2.getX ( ) - b1.getX ( ) ) ; // normalize tangent vector float mag = ( float ) ( Math.sqrt ( ... | combined velocity is larger than initial velocity |
Java | How can I get the values of an `` enum '' in a generic ? On the other hand , I can query the values ( ) for Enum class : | public class Sorter < T extends Enum < ? > > { public Sorter ( ) { T [ ] result = T.values ( ) ; // < - Compilation error } } enum TmpEnum { A , B } public class Tmp { void func ( ) { T [ ] result = TmpEnum.values ( ) ; // < - It works } } | How can I get the values of an `` enum '' in a generic ? |
Java | I m not getting the whole data sometimes while reading the inputStream like this ( somtime full data is recieved ) .should i read the input Stream until inputStream.available ( ) is zero.. ? Data in inputStream is large.Plz Suggest some altenative with Sample code | private String readInputStream ( InputStream in ) { PushbackInputStream inputStream = ( PushbackInputStream ) in ; StringBuffer outputBuffer = null ; try { int size = inputStream.available ( ) ; outputBuffer = new StringBuffer ( size ) ; // append the data into the stringBuilder for ( int j = 0 ; j < size ; j++ ) { int... | Not getting whole data while using available ( ) |
Java | We recently faced a bug in our code which was basically related to OOPs concepts . Output : ABC @ 642c39d2Should n't this raise a run time exception ? Can someone point me to the correct direction as to why does n't this code raise an exception ? | class ABC { String a ; ABC ( ) { a = `` abc '' ; } } public class Main { static Object listABC ( ) { List < ABC > listOfABC = new ArrayList < > ( ) ; listOfABC.add ( new ABC ( ) ) ; return listOfABC ; } public static void main ( String [ ] args ) throws java.lang.Exception { List < Long > listLong = ( List ) Main.listA... | Type casting an object to any Collection type |
Java | Suppose I have a class called CommandLineOperation . This class accesses API resources . Thus I have defined one instance member of type APIAccessor.The operations in CommandLine , are infrequent , is it a better approach to instantiate APIAccessor under every operations or create once using constructor of CommandLineO... | class CommandLineOperation { APIAccessor apiAccessor ; void create ( ) { apiAccessor = new APIAccessor ( email , password ) ; //do work for creation } void update ( ) { apiAccessor = new APIAccessor ( email , password ) ; //do work for update } } class APIAccessor { String email ; String password ; APIAccessor ( email ... | Coding Pattern for use instance member |
Java | A service interface declares two methods which apparently do the same processing : The service above is being called like below : Which one of the service methods are going to be called and why the compiler does not complain about an ambiguous call in this context ? | interface Service < T > { < R > R process ( Function < ? super T , ? extends R > function ) ; T process ( UnaryOperator < T > operator ) ; } void process ( Service < CharSequence > service ) { service.process ( sequence - > sequence.subSequence ( 0 , 1 ) ) ; } | Why Java is not complaining about an ambiguous call ? |
Java | Help me please to undestand why i ca n't call the testSuper ( ) method ? There is compile error : But the testExtends ( ) method OK . However , it looks the same . | The method testSuper ( Group < ? super BClass < ? > > ) in the type Group < BClass < String > > is not applicable for the arguments ( Group < AClass < String > > ) class AClass < T > { } class BClass < T > extends AClass < T > { } class Group < T > { T name ; public void testExtends ( Group < ? extends AClass < ? > > v... | Unbounded wildcards with extends and super as parameters |
Java | So someone asked Is the ++ operator more efficient than a=a+1 ? a little while ago . I thought that I analyzed this before and initially said that there was no difference between a = a + 1 and the incremental operator ++ . As it turns out , a++ , ++a and a += 1 all compile to the same bytecode , but a = a + 1 does not ... | public class SO_Test { public static void main ( String [ ] args ) { int a = 1 ; a++ ; a += 1 ; ++a ; } } public class SO_Test { public static void main ( String [ ] args ) { int a = 1 ; a = a + 1 ; a++ ; a += 1 ; ++a ; } } | Analysis of various incremental operators vs assignment and incrementing |
Java | I have list of Payments : I created a function that takes in this list and currentDueDate.If paymentDueDate is equal to or before currentDueDate and one that 's closest to currentDueDate , I want to use that row in my calculations.For some reason my sort is not working properly.Can someone shed some light on what I am ... | Payment 1 CountyTaxAmount = 250.00 CityTaxAmount = 101.00 LienAmount = 0.00 HazardAmount = 0.00 PaymentDueDate = `` 2018-06-01 '' Payment 2 CountyTaxAmount = 10.00 CityTaxAmount = 20.00 LienAmount = 0.00 HazardAmount = 0.00 PaymentDueDate = `` 2018-05-01 '' private EscrowStatusEnum determineEscrowStatus ( Payment pcm ,... | Sort List of objects by date and applying filter |
Java | There are many immutable classes in Java like String and primitive wrapper classes , and Kotlin introduced many others like Range subclasses and immutable Collection subclasses.For iterating Ranges , from Control Flow : if , when , for , while - Kotlin Programming Language we already know : A for loop over a range or a... | repeat ( 1024 ) { doSomething ( ( ' a'.. ' z ' ) .random ( ) ) } val LOWERCASE_ALPHABETS = ' a'.. ' z'repeat ( 1024 ) { doSomething ( LOWERCASE_ALPHABETS.random ( ) ) } | Will immutable objects with const parameters be optimized to be instantiated only once by the Kotlin compiler |
Java | I am trying to collect result of a list and organise them into a Map where the value is a Map : I get java.lang.IllegalStateException : Duplicate key error as getProcessedDate ( ) is same for different values in the list.Is there a way I can merge multiple objects with same processeddate into the map ? e.g say I have t... | private Map < Organisation , Map < LocalDate , Status > > getSummaries ( final List < Status > summaries ) { return summaries .stream ( ) .collect ( groupingBy ( Status : :getOrganisation , toMap ( Status : :getProcessedDate , Function.identity ( ) ) ) ) ; } Summary ( ProcesseDate=2020-01-30 , Organisation=ABC , status... | Java 8 Stream function grouping to Map where value is a Map |
Java | Given this Java code : The expressions initializing list , list2 and list3 work fine . However , the expression initializing list4 breaks with this error in Eclipse : and this error in javac : But AbstractMap.SimpleEntry directly implements Map.Entry . So why does type inference break for list4 when it works for list1 ... | import java.util.AbstractMap.SimpleEntry ; import java.util.Arrays ; import java.util.List ; import java.util.Map.Entry ; import java.util.Optional ; public class Test { public static void main ( String [ ] args ) { SimpleEntry < Integer , String > simpleEntry = new SimpleEntry < > ( 1 , `` 1 '' ) ; Optional < Entry < ... | Why does Java type inference for generic supertypes break here ? |
Java | I need to use lambdas to generate some lists of new objects . These new objects inherit some of the traits from the existing ones . Since it 's hard to describe it without going into too much delicate details , I 'll use an example of a parent and their children . I want to generate a list of kids based on a list of pe... | public class Kid { private Colour colour ; private Person person ; public Kid ( Person person ) { this.colour = person.getColour ( ) ; } public List < Kid > listOfKids ( ) { return people.stream ( ) .map ( e - > new Kid ( e ) ) ; } } | Java - getting a list of new objects from a stream based on the list of the existing ones |
Java | I 'm writing a Swing application and trying to make a menu where each menu item has its own action : Here 's how I wanted to solve this : However , I can not use loadGame ( i ) , because it says i would have to be final . I understand the reason for this , but I do not know how to work my way around it . | private void createGameLevelMenuItems ( JMenu menu ) { for ( int i = 0 ; i < 10 ; i++ ) { JMenuItem item = new JMenuItem ( new AbstractAction ( `` Level- '' + i ) { @ Override public void actionPerformed ( ActionEvent e ) { game.loadGame ( i ) ; board.refresh ( ) ; pack ( ) ; } } ) ; menu.add ( item ) ; } } | How do I solve local referenced variables inside a for loop ? |
Java | I want to use streams like : but stop the filtering as soon as I have maximum 100 Elements ready to be collected . How can I achieve this without filtering all and calling subList ( 100 , result.size ( ) ) ? | List < String > result = myArr .stream ( ) .filter ( line - > ! `` foo '' .equals ( line ) ) .collect ( Collectors.toList ( ) ) ; | Java Streams TakeUntil 100 Elements filtered/collected |
Java | Given a class T which is a subclass of U , is it safe to cast Iterator < T > to Iterator < U > ? And assuming that the cast be safe , are there more elegant ( and warning-free ) ways of doing it other than : My reasoning why the cast is not dangerous is this : Iterator < ? > does not support inserting elements , so the... | Iterator < T > it = < insert your Iterator < T > here ... > ; Iterator < U > it2 = ( Iterator < U > ) ( Iterator < ? extends U > ) it ; | Convert from Iterator < T > to Iterator < U > where T is a subclass of U |
Java | This code : Gives such compilation error : From what I understand , E becomes ? extends Base , something that extends Base . So , why new Base ( ) ca n't be passed ? | public class Base < E > { static void main ( String [ ] args ) { Base < ? extends Base > compound = new Base < Base > ( ) ; compound.method ( new Base ( ) ) ; } // ^ error void method ( E e ) { } } Error : ( 4 , 17 ) java : method method in class Base < E > can not be applied to given types ; required : capture # 1 of ... | Why new Base ( ) can not be passed to < ? extends Base > ? |
Java | I have the following Java codeWhen the test is run , the assertion fails and exception is printed as standard output and the TestNG shows the test result as FAILED.If I catch the same exception usingthe exception is printed as error output and the TestNG shows the test result as PASSED . In both cases exception is hand... | import org.testng.annotations.Test ; @ Testpublic void testException ( ) { try { Assert.assertEquals ( 1,2 ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } catch ( AssertionError e ) { e.printStackTrace ( ) ; } | What is the difference between handling exceptions by catch block directly parent class and subclasses |
Java | I am trying to detect which class inside a jar contains main or a supplied method name ( if possible ) .At the moment I have the following codeThis will allow me to get packages and classes under these packages , but I do not know if it is possible to even get methods inside classes.Further , I do not know if this appr... | public static void getFromJars ( String pathToAppJar ) throws IOException { FileInputStream jar = new FileInputStream ( pathToAppJar ) ; ZipInputStream zipSteam = new ZipInputStream ( jar ) ; ZipEntry ze ; while ( ( ze = zipSteam.getNextEntry ( ) ) ! = null ) { System.out.println ( ze.toString ( ) ) ; } zipSteam.close ... | detect main inside a jar using java code . |
Java | I have a string like this : and regex : I want to match all 6 groups separately , but when I match the pattern , I get result like this : How can I match each group separately ? | String text = `` new SingleSizeProduct ( 422056 , 1265858 , 5430 , '3XL ' , 75 , 0 , '14.90 ' , '16.50 ' , '29.90 ' , 'TL ' ) , new SingleSizeProduct ( 422056 , 1265859 , 5341 , ' L ' , 55 , 0 , '14.90 ' , '16.50 ' , '29.90 ' , 'TL ' ) , new SingleSizeProduct ( 422056 , 1265860 , 5459 , 'M ' , 45 , 1 , '14.90 ' , '16.5... | Java regex match each group separately |
Java | I was testing a program for CPU usage check and I got a null pointer exception , so I added null check . When I added null check I started getting series of errors . Here is the code : The Highlighted lines show the null check added . Compilation error after this null check is as follows : Please help in resolving this... | double ideltime=Double.parseDouble ( cpuIdle.trim ( ) ) ; **String idelTimeStr=formatter.format ( ideltime ) ; if ( idelTimeStr ! =null ) ** double usuage=temp - Double.parseDouble ( idelTimeStr ) ; cpuUsage = formatter.format ( usuage ) ; CPUUsage.java:29 : error : '.class ' expected double usuage=temp - Double.parseD... | Adding Null check is throwing a series of compile errors |
Java | When I enter an expression in JShell ( 9.0.1 ) it comes back with : Where does the 22 come from and what 's happened to $ 1 to $ 21 ? ( They are undefined . ) I seem to vaguely remember ( when I started with Java 9.0 ) that the variables started with $ 1 , which made more sense . Now , with 9.0.1 , they all start with ... | $ 22 - > < value > | JShell dollar variable name numbering |
Java | I want to do this : But then the first 2 lines in a single line like : But the first line fails . I get : incompatible types.Required : Foo.BarFound : Foo.BarWhy is that ? And the last class : | Foo < String > foo = new Foo < > ( ) ; Foo < String > .Bar fooBar = foo.new Bar ( ) ; fooBar.doSomething ( `` this works ! `` ) ; Foo < String > .Bar fooBar2 = new Foo < > ( ) .new Bar ( ) ; fooBar2.doSomething ( `` The above line gives : incompatible types . Required : Foo.Bar Found : Foo.Bar '' ) ; public class Foo <... | Required type is same as found type |
Java | Suppose I have some string , and run the following tests on it : How is it possible that indexOf finds the substring ( it does not return -1 ) , but the regular expression in the second test does not match ? I have come across this problem while trying to write a test that checks if taglibs are rendered correctly in JS... | response.indexOf ( `` < /p : panelGrid > '' ) ; response.matches ( `` .* < /p : panelGrid > . * '' ) ; | Substring is found , but regex fails |
Java | As a Java beginner I 'm playing around with a case statement at this point.I have set : int d = ' 1 ' ; And with : System.out.println ( `` number is : `` + d ) ; , this returns 51.Now I found out that if I set it as : int d = 1 ; , it does return 1.Now my question is why does it return 49 when I set it as ' 3 ' ? What ... | int a = ' 1 ' ; switch ( a ) { case ' 1 ' : System.out.println ( `` Good '' ) ; break ; case ' 2 ' : case ' 3 ' : System.out.println ( `` great '' ) ; break ; default : System.out.println ( `` invalid '' ) ; } System.out.println ( `` value : `` + a ) ; | Java CASE why do i get a complete differet int back with and without using ' ' |
Java | I need a clarification in Dynamic polymorphism of Java.Here when i create a child class object with a base class reference , while invoking the method f.display ( ) it gives me the output as in boo 8 . This is because of dynamic polymorphism which checks the object type at run time for invoking the method.Now while pri... | class Foo { int a=3 ; public void display ( ) { System.out.println ( `` in foo `` +a ) ; } } class Bar extends Foo { int a=8 ; public void display ( ) { System.out.println ( `` in boo `` +a ) ; } } public class Tester { public static void main ( String [ ] args ) { Foo f = new Bar ( ) ; f.display ( ) ; System.out.print... | dynamic polymorphism reference pointing to base class |
Java | I need some advice about usage of Iterable < T > in Java.I have the following class : I need to create a class ValidatorChain as follows : Maybe I should just override some instant implementation of Iterable < T > instead of writing my own one from scratch . | public abstract class Validator implements Comparable < Validator > { public abstract boolean validate ( ) ; public abstract int getPriority ( ) ; @ Override public int compareTo ( Validator o ) { return getPriority ( ) > o.getPriority ( ) ? -1 : getPriority ( ) == o.getPriority ( ) ? 0 : 1 ; } } public class Validator... | Do I really need to implement iterator in that case ? |
Java | In my spring boot application , in my rest controllers , I successfully inject an instance of Authentication to get the session 's user information.However , in all of those controllers , I currently call a helper method like this : How can I reduce this code duplication ? | @ GetMappingpublic List < String > getData ( Authentication auth ) { String username = auth.getName ( ) .replaceFirst ( `` . * ? \\\\ '' , `` '' ) ; // to remove windows domain name // the rest of these methods only use variable ` username ` , never ` auth ` } | How to inject the username ( not the Authentication ) ? |
Java | I have a code that iterates on some objects of type MyType : No I 'm adding a flow that handles result of type Map < Long , MyNewType > that needs to do exactly the same thing while the only difference is that the method that returns the status is named differently ( let 's say - getObjectStatus ( ) instead of getStatu... | // result is of type Map < Long , MyType > for ( final Map.Entry < Long , MyType > someMyTypeObject : result.entrySet ( ) { // Do a bunch of stuff Status status = someMyTypeObject.getStatus ( ) ; // Do some more stuff } public < T > doIterationWork ( Map < Long , T > result ) { // Do a bunch of stuff Status status = so... | Java - Extracting code to a generic method when method names are different |
Java | I have a class that 's a multiton , so I know that given a particular key , there will never be two instances of the same class that exist . This means that , instead of : ... it 's safe for me to do this : The class is also final , so I know that nothing related to polymorphism could cause problems for comparison eith... | if ( someObject.equals ( anotherObject ) ) if ( someObject == anotherObject ) | Annotating a Java class as safe for reference comparison |
Java | I always thought final keyword has no effect , performancewise , on local method variables or parameters . So , I tried to test the following code and it seems I was wrong : I checked the bytecode and they are not the same for these 2 methods . Decompiled code in idea looks like this : Why is there a difference between... | private static String doStuffFinal ( ) { final String a = `` A '' ; final String b = `` B '' ; final int n = 2 ; return a + b + n ; } private static String doStuffNotFinal ( ) { String a = `` A '' ; String b = `` B '' ; int n = 2 ; return a + b + n ; } private static String doStuffFinal ( ) { String a = `` A '' ; Strin... | Java compiler optimizations with final local variables |
Java | While refactoring I came across the following method in a subclass : What are the benefits to keeping this method rather than simply allowing the inherited superclass method to be called ? | public void disposeResultsTable ( ) { super.disposeResultsTable ( ) ; } | Is there a benefit from having a subclass method that only calls the overridden superclass method ? |
Java | I decided to dig into source code a bit and noticed that Collections.synchronizedList ( List ) is implemented as follows : where the SynchronizedList nested class is : As can bee seen , the class useses a private lock object to provide thread-safety . But the documentation allows us to iterate over it using locking on ... | public static < T > List < T > synchronizedList ( List < T > list ) { return ( list instanceof RandomAccess ? new SynchronizedRandomAccessList < T > ( list ) : new SynchronizedList < T > ( list ) ) ; } static class SynchronizedList < E > extends SynchronizedCollection < E > implements List < E > { private static final ... | Is it safe to iterate over synchronized wrappers ? |
Java | Let 's say I have 3 classes A , B , C , and my Main.B extends A.I want to use a scanner in all of them include my main.should I move scanner by inheritance or should I use static and declare my scanner in my main ? I tried to look here but did not get a clear answer which is better : Is there any way I can use a Scanne... | public class Main { public static Scanner staticScanner = new Scanner ( System.in ) ; public static void main ( String [ ] args ) { Scanner sc = new Scanner ( System.in ) ; A a = new A ( sc ) ; C c = new C ( ) ; c.cDoSomething ( sc ) ; sc.close ( ) ; } public class A { private Scanner sc ; public A ( Scanner sc ) { thi... | Java static or inheritance variable |
Java | Thanks for all your help and sharing.My question is in regards of the Stochastic Search . This technique is used to do approximations of data through a defined amount of cicles over a , an in general , mathematical calculation . Please see following code , I tried to reduce it to its minimum . My expectation is to have... | package stochasticsearch ; import java.util.Random ; public class StochasticSearch { public static double f ( double x ) { return - ( x - 1 ) * ( x - 1 ) + 2 ; } public static void main ( String [ ] args ) { final Random random = new Random ( ) ; double startPointX = 0 ; double max = f ( startPointX ) ; long begin = Sy... | Stochastic Search to lambda expression |
Java | I have a code , which is working as required , but I want to re-write it in Java 8.This code will produce a map.Each list item will have all the servers allocated to it.OutputWhat would be the lambda equivalent ? | public static Map < String , List < String > > agg ( ) { List < String > list = Arrays.asList ( `` Item A '' , `` Item B '' , `` Item C '' ) ; List < String > servers = Arrays.asList ( `` Server A '' , `` Server B '' , `` Server C '' , `` Server D '' ) ; Map < String , List < String > > map = new HashMap < > ( ) ; for ... | Possible way to write below code in java 8 |
Java | I have the following class : which throws exception in this line : Methods to create racer that consists in the same class : The Racer Class : Abbreviations.txt file : FileLoader class : I read about Stream Supplier but I ca n't figured It out so I will be grateful for any help how to fix my program . | public List < Racer > createListOfRacers ( ) throws IOException { Stream < String > abbreviationsOfRacers = fileLoader.createStreamFromFile ( `` src/main/resources/abbreviations.txt '' ) ; Stream < Racer > racerList = abbreviationsOfRacers .map ( this : :createRacer ) ; return racerList.collect ( toList ( ) ) ; } .map ... | stream has already been operated upon or closed , gained exception when trying to create Racers |
Java | Given : The compiler accepts transform ( known ) but complains : for transform ( unknown ) . I get the opposite problem for transform2 ( ) . I 've consulted PECS and I believe that transform ( ) is the correct method declaration but I ca n't for the life of my figure out how to get a single method to handle both cases.... | public class Testcase { public static < E > List < List < E > > transform ( List < List < E > > list ) { return list ; } public static < E > List < List < ? extends E > > transform2 ( List < List < ? extends E > > list ) { return list ; } public static void main ( String [ ] args ) { List < List < Integer > > known = n... | What method declaration accepts bounded and unbounded multi-level Generics ? |
Java | I have tried passing a value between 2 methods by following different solutions on here , but passes null.The code I am trying to pass : Where I am trying to pass the value `` price '' to : The value of price in getPrice ( ) is what it is supposed to be but when I print out the value in recordData ( ) , the value = nul... | private void getPrice ( ) { DatabaseReference dbRequest = FirebaseDatabase.getInstance ( ) .getReference ( Common .request_tbl ) .child ( riderId ) .child ( `` details '' ) ; // `` Requests '' dbRequest.addValueEventListener ( new ValueEventListener ( ) { @ Override public void onDataChange ( DataSnapshot dataSnapshot ... | Unable to pass a value between methods in same class in Android |
Java | I have a bunch of files on a local file system . My server will serve those files . In some cases the server will receive an instruction to delete a file . At the moment I 'm using FileChannel.lock ( ) to acquire a lock on the file , this is mostly to make sure that some other process is n't editing the file when I try... | FileOutputStream out = new FileOutputStream ( file ) ; FileChannel channel = out.getChannel ( ) ; FileLock lock = channel.lock ( ) ; if ( lock.isValid ( ) & & ! lock.isShared ( ) ) { Path filePath = Paths.get ( file.getPath ( ) ) ; Files.delete ( filePath ) ; } FileOutputStream out = new FileOutputStream ( file ) ; Fil... | Should I have a lock on a file when I want to delete it ? |
Java | Is there a correct way to open a resource for each element in collection , than use stream api , do some map ( ) , filter ( ) , peek ( ) etc . using the resource and than close the resource ? I have something like this : This should work fine , except I 'm opening a resource ( e.g . db connection ) in the getElementFro... | List < String > names = getAllNames ( ) ; names.stream ( ) .map ( n - > getElementFromName ( n ) ) .filter ( e - > e.someCondition ( ) ) .peek ( e - > e.doSomething ( ) ) .filter ( e - > e.otherCondition ( ) ) .peek ( e - > e.doSomethingElse ( ) ) .filter ( e - > e.lastCondition ( ) ) .forEach ( e - > e.doTheLastThing ... | Is there a correct way to close resources opened in java stream api ( for each element ) ? |
Java | I expected that simple intermediate stream operations , such as limit ( ) , have very little overhead . But the difference in throughput between these examples is actually significant : I am curious : What is the reason for the quickly degrading throughput ? Is it a consistent pattern with chained stream operations or ... | final long MAX = 5_000_000_000L ; LongStream.rangeClosed ( 0 , MAX ) .count ( ) ; // throughput : 1.7 bn values/secondLongStream.rangeClosed ( 0 , MAX ) .limit ( MAX ) .count ( ) ; // throughput : 780m values/secondLongStream.rangeClosed ( 0 , MAX ) .limit ( MAX ) .limit ( MAX ) .count ( ) ; // throughput : 130m values... | Quickly degrading stream throughput with chained operations ? |
Java | While developing a two-dimensional vector class as part of a math library , I 'm considering having static and instance method pairs for stylistic and usability reasons . That is , two equivalent functions but one is static & non-mutating , and the other is instanced & mutating . I know I 'm not the first person to con... | someVector = Vector2d.add ( vec1 , vec2 ) ; someVector = ( new Vector2d ( vec1 ) ) .add ( vec2 ) ; // does the same thing although more convoluted.// similarly adding directly to a vector is simpler with a mutator method.someVector.add ( vec2 ) ; someVector = Vector2d.add ( someVector , vec2 ) ; | Having pairs of static and instanced methods that perform the same tasks ? |
Java | I do not understand how the compiler handle 's the following code as it outputs Test while I was expecting an error.I was hoping someone could tell me the exact steps the compiler goes through when executing the code so I can understand the output . My current understanding is that : The compiler checks during compile ... | List < Integer > b = new ArrayList < Integer > ( ) ; List a = b ; a.add ( `` test '' ) ; System.out.println ( b.get ( 0 ) ) ; | Unexpected adding String to List < Integers > |
Java | I have a class called User and a file called Users.csv , like below : User class : Users.csv : Also , I have a class called test , which implements a single method : test class : The problem is in the method readUsers ( ) . It is returning me an ArrayList where every element is the same , and they are the one at the la... | public class User { private String name ; private String rg ; private String type ; public String getName ( ) { return name ; } public String getRg ( ) { return rg ; } public String getType ( ) { return type ; } public void setName ( String n ) { name = n ; } public void setRg ( String r ) { rg = r ; } public void setT... | Why is this method returning an ArrayList with all the same objects ? JAVA |
Java | So I 'm building a test library that I will mainly use for personal use however I have a question.With Java , if you have 2 or more constructors in your class , if you wish to call one from another , it must be the first thing you do . This is problematic for me as I have the below setup.How can I do this , avoiding th... | public Constructor ( TypeA a , TypeB b , TypeC c ) { if ( c.getData ( ) == null ) throw new IllegalArgumentException ( `` '' ) ; this ( a , b , c.getOtherData ( ) ) ; } public Constructor ( TypeA a , TypeB b , TypeD d ) { // stuff happens } | Throw Exception then Call Constructor ? |
Java | I 'm trying to do clean and install on my Spring Boot project in before creating the Jar file for my project however I came across this errorI 'm new to Spring Boot and have never really utilized the test function of it . So my test class is pretty much default of how it was initially created with the project.My test c... | java.lang.IllegalStateException : Unable to find a @ SpringBootConfiguration , you need to use @ ContextConfiguration or @ SpringBootTest ( classes= ... ) with your test package com.Alex.demo ; import org.junit.jupiter.api.Test ; import org.springframework.boot.test.context.SpringBootTest ; @ SpringBootTestclass WebApp... | Spring boot Maven install error - Unable to find a @ SpringBootConfiguration |
Java | The above statement gives a warning `` Type safety : Unchecked cast from Class < capture # 5-of ? > to Class < ? extends MyClass > '' .This time I get an error , because of type erasure ... This time I know that the cast is safe , but the compiler does n't , and still gives the warning . ( If you ask me , the compiler ... | Class < ? extends MyClass > cls = ( Class < ? extends MyClass > ) Class.forName ( className ) ; someMethod ( cls ) ; // someMethod expects a Class < ? extends MyClass > Class < ? > cls0 = Class.forName ( className ) ; if ( cls0 instanceof Class < ? extends MyClass > ) { Class < ? extends MyClass > cls = ( Class < ? ext... | Is there a way to cast a class to have specific parameters to the java.lang.Class < > generic ? |
Java | I 'm almost completely new to Java and programming in general ( my main degree is in Law but I 'm hoping to open myself up to programming as I truly believe it 's going to be an essential skill in a couple years ) .I 've created two classes , LabClass and Student , and the point is to enroll students into the class , w... | public void addCredits ( int additionalPoints ) { credits += additionalPoints ; } public void enrollStudent ( Student newStudent ) { if ( students.size ( ) == capacity ) { System.out.println ( `` The class is full , you can not enrol . `` ) ; } else { students.add ( newStudent ) ; } students.addCredits ( 50 ) ; } | Having trouble referring to a method in another class |
Java | I 've just started learning Java GUI and faced this problem while practicing event handling.Here 's the initial windowWhen I enter a number inside the text field it 's supposed to say whether the guessed number is higher , lower or matched . If not matched it 'd prompt for another number . But the window just hangs.Aft... | import java.awt . * ; import java.awt.event . * ; import javax.swing . * ; public class RandomNumGame extends JFrame { private JLabel promptLabel , resultLabel , answerLabel ; private int tries=1 , randomNum , guessNum ; private JButton button ; private JTextField txt ; private boolean guessed ; public RandomNumGame ( ... | What is wrong with this Java GUI code ? |
Java | I would like to transform a Map < String , List < Object > > so it becomes Map < String , String > . If it were just Map < String , Object > it is easy in Java8 ; But this will not work because getValue returns a List Map < List < Object > , String > in my example . Assume Object contains a getter to be used for the ke... | stream ( ) .collect ( k - > k.getValue ( ) .getMyKey ( ) , Entry : :getKey ) ; | Inverse Map where getValue returns a List |
Java | I have the CharacterEncodingFilter in place ( first filter ) in web.xmlBut when I make a POST request , the body does not get encodedReq Body Sent : But received as | < filter > < filter-name > encodingFilter < /filter-name > < filter-class > org.springframework.web.filter.CharacterEncodingFilter < /filter-class > < init-param > < param-name > encoding < /param-name > < param-value > UTF-8 < /param-value > < /init-param > < init-param > < param-name > forceEncoding < /param-name > <... | Post body is not getting encoded even after adding filter |
Java | for a test I created following regex by mistake : I was puzzled that this regex really works and I ca n't explain the result : the result is : My ideas so far are that java tries to replace `` nothing '' between the characters but why not the characters itself ? \\w+ should match the ' H ' I would expect that every cha... | | ( \\w+ ) | public static void main ( String [ ] args ) { String toReplace= '' Hey I 'm a lovely String an I 'm giving my |value| worth ! `` ; // String replacement1= '' 2 cent '' ; // I planned to replace |value| with 2 cent String replacement1= '' @ '' ; // to produce a better Output String regex= '' | ( \\w+ ) | ''... | Programming error leads to inexplanable regex |
Java | I 'm confused with the process of loading a class . What is the order in which members of a class are executed ? See the following : Whenever I move the declarations of a and b to the top before the static block , compilation works fine . So I need to understand how this stuff works to resolve the problem above . | class L { static void fr ( ) { a=1 ; b=3 ; a=b ; } static { a=3 ; b=1 ; a=b ; // here the problem : can not reference a field before it is defined } static int a ; static int b ; public static void main ( String args [ ] ) { } } | What really happens when loading a class in java ? |
Java | Suppose we have a prototype-scoped bean.We 're injecting this bean to a class , TheDependent.But there is also another one.In each @ Autowired , a new instance of Foo gets created because it 's annotated with @ Scope ( `` prototype '' ) . I would like to access the 'dependent ' class from the factory method , FooConfig... | public class FooConfiguration { @ Bean @ Scope ( `` prototype '' ) public Foo foo ( @ Autowired Bar bar ) { return new Foo ( bar ) ; } } @ Componentpublic class TheDependent { @ Autowired private Foo foo ; } @ Componentpublic class AnotherOne { @ Autowired private Foo foo ; } | Access the injectee component from bean factory |
Java | I am using Eclipse Kepler , with JRE 7 . In the buildRunner method - why I am able to see the this of Main ? What is the 'this ' of Main in a static method ? Why does this compile ? I can only do that if value is final . I can not call instance methods of Main and stuff , but value is not decalred static ! Furthermore ... | public class Main { private final int value = 3 ; public static Runnable buildRunner ( ) { return new Runnable ( ) { @ Override public void run ( ) { System.out.println ( Main.this.value ) ; } } ; } } | Why am I able to print this field in a static method ? |
Java | There is a multidimensional String array being passed in as an Object.I 'm supposed to `` unfold '' it and process each of its primitive entries . There 's no way to know the dimensions other than by looking at the Object itself . The difficulty i 'm having is in casting . I can look up the array dimension by invoking ... | String [ ] sa = ( String [ ] ) arr ; Exception in thread `` main '' java.lang.ClassCastException : [ [ Ljava.lang.String ; can not be cast to [ Ljava.lang.String ; | How to cast a multidimensional array without knowing the dimension in Java |
Java | I have set of urls now i want to filter them out on the bases of web domains ( say wikipedia urls ) .Right now what i am doing is iterating set and for each url i am just finding a keyword of that web address.is there any other technique that is more efficient than my current approach ? | if ( ur.contains ( `` wikipedia.org '' ) ) { //do something } | How to filter URL on the bases of web domain ? |
Java | I was looking through an old codebase and I found a method that only calls its parent : Would there be any use case for such a method ? For me it looks like I could just remove it . | @ Overridepublic void select ( Object item ) { super.select ( item ) ; } | Overriding method only calls parent method - useful ? |
Java | I 'm using generics in Java for the first time , and I 'm facing an issue I do n't manage to overcome : why this compiles : But this does not : And I get this error : both methods have same erasure.I 'm sorry if this is a stupid question , but I do n't get why the order of interfaces in a bounded type parameter declara... | public interface Aa { } public interface Bb { } public interface Cc { } public static < GenericAB extends Aa & Bb > void method ( GenericAB myABobject1 , GenericAB myABobject2 ) { } public static < GenericAB extends Aa & Bb , GenericCA extends Cc & Aa > void method ( GenericAB myAbobject , GenericCA myCAobject ) { } pu... | `` both methods have same erasure '' error using bounded type parameters |
Java | I run the following Java code : The display is GMT+03:00 ! It seems that when we use timezones with ids such as Etc/GMTxx , the sign is reversed . Why ? | TimeZone tz1 = TimeZone.getTimeZone ( `` Etc/GMT-3 '' ) ; System.out.println ( tz1.getDisplayName ( ) ) ; | Strange behavior with Timezone |
Java | For example if I were to create the following class : If I were to create an instance of ExampleClass . Would that instance contain the code for the static method and/or field I created ? I have an object that will represent some data from a row in my database . I would like to create the a list of these objects from e... | public Class ExampleClass { private static String field1 ; private String field2 ; public ExampleClass ( String field2 ) { this.field2 = field2 ; } public static staticMethodExample ( String field1 ) { this.field1 = field1 ; } } | Do Static Methods and Fields take up memory in an instance of the class they are defined in ? |
Java | I get a horrific stackoverflowerror , and figured it was my deep recursion causing it ( well , the debugger helped with that ... ) . Can anyone guide me in turning my recursion into a loop ? More specifically , return find ( getNextLocation ( startPos , ++stepNum , key ) , key , stepNum ) ; causes the recursion . | H < V > .Pair currPair = ( H < V > .Pair ) arr [ startPos ] ; if ( arr [ startPos ] == null ) { return null ; } if ( currPair.key.equals ( key ) ) { return currPair.value ; } else { return find ( gNL ( startPos , ++stepNum , key ) , key , stepNum ) ; } } | How to turn recursion into iteration ? |
Java | This particular problem I 'm working on is listed as such : ConcatArrays ( int [ ] listA , int [ ] listB , int [ ] listC ) with no return type.1 . The method passes the formal array parameters listA and listB , then return the concatenated array listC.2 . The first part of listC contains elements which are the same as ... | public static void ConcatArray ( int [ ] listA , int [ ] listB , int [ ] listC ) { int aLen = listA.length ; int bLen = listB.length ; int cLen = listC [ aLen + bLen ] ; } | Is it possible to concate two int arrays without using a return type ? |
Java | I 'm trying to receive data from a client and then log it onto the console.Here is how i do this : When it comes to printing my messageToPrint it actually repeats the last one , and reprinting it with a newer one.I 've figured out what is the problem though.If i put allocation of the array data inside the while loop , ... | private final int MAX_PACKET_SIZE = 1024 ; private byte [ ] data = new byte [ MAX_PACKET_SIZE ] ; private void receive ( ) { new Thread ( ( ) - > { while ( running ) { DatagramPacket packet = new DatagramPacket ( data , data.length ) ; try { socket.receive ( packet ) ; sPort = packet.getPort ( ) ; ip = packet.getAddres... | How can erase the contents of an array in Java with safety ? |
Java | I have just started to learn about Java Runnables and I have heard of Callables . However , I am very much struggling with this problem . I would like to make a method which takes a function as an argument ( whether that be as a Callable , a Runnable , or something else , as long as I can simply call the function as co... | public static int square ( int x ) { return x * x ; } coolNewFunction ( ( ) - > square ( ) , 100 ) | Make a Method Which Generates the x and y values of Another Given Function |
Java | I have a problem displaying a number of dates that are stored as longs.I create the date objects with the constructor that takes the long argument , and then print the dates to a PDF file.However , I have a problem with older dates , when running the program on Linux , compared to Windows.Take this date : 25. april 197... | DateFormat.getDateTimeInstance ( DateFormat.FULL , DateFormat.FULL ) .format ( new Date ( 199231200000L ) ) new org.joda.time.DateTime ( ) .withDate ( 1976 , 4 , 25 ) .withTime ( 0 , 0 , 0 , 0 ) .toDate ( ) .getTime ( ) | Older dates are parsed as summer time , even if that is not true in Java |
Java | I have a list1 containing different strings which start with a string from another list ( fooBarList ) .I would like to create a Hashmap < String , List < String > > hm which seperates the strings from the list1 depending on what they start with.Result should look like this : the fooBarList defines the different keys.h... | List < String > list1 = Arrays.asList ( `` FOO1234 '' , `` FOO1111 '' , `` BAR1 '' , `` BARRRRR '' ) ; List < String > fooBarList = Array.asList ( `` FOO '' , `` BAR '' ) ; { FOO= [ `` FOO1234 '' , FOO1111 '' ] , BAR= [ `` BAR1 '' , `` BARRRRR '' ] } | Assign all values in a Set < String > to a Map < String , String > with streams |
Java | I 'm sorting an array of `` Albums '' by the output of their method getAlbumArtist ( ) , using a custom comparator class , AlphaNumComparator , which has a method compare , which compares two strings . I have the following code , which works : This seems like the sort of code that could be simplified/made more clear wi... | AlphanumComparator comparator = new AlphanumComparator ( CaseHandling.CASE_INSENSITIVE ) ; Arrays.sort ( albumArray , ( Album a , Album b ) - > { return comparator.compare ( a.getAlbumArtist ( ) , b.getAlbumArtist ( ) ) ; } ) ; | Is there a more concise way to write this method using Lambda Expressions ? |
Java | I am new in Java 8 , and I want to get the first Phone that is not null from a list of contacts form a list of persons , but I am getting a incompatible types error | return segadors .stream ( ) .map ( c - > c.getSegadorMedium ( ) .stream ( ) .map ( cm - > Objects.nonNull ( cm.getPhoneSegador ( ) ) ) ) .findFirst ( ) .orElse ( null ) ; | Java 8 : Getting a property from a List of a List |
Java | I was trying to create a method reference to an arbitrary object , so I defined the following types : Then I declared the method reference , like below : When I call : I get a NullPointerException : Can someone explain why this happens even though the Impl reference is not used anywhere ? | interface I { boolean get ( Impl impl ) ; } static class Impl { public boolean get ( ) { return true ; } } I i = Impl : :get ; i.get ( null ) ; Exception in thread `` main '' java.lang.NullPointerException | NullPointerException when calling a method reference to an arbitrary object with null argument |
Java | I wanted to learn parallel programming for speeding up algorithms and chose Java.I wrote two functions for summing long integers in array - one simple iterating through array , second - dividing array to parts and sum up parts in separated threads.I expected to be logical a roughly 2x speed up using two threads . Howev... | import java.util.concurrent.ThreadLocalRandom ; public class ParallelTest { public static long sum1 ( long [ ] num , int a , int b ) { long r = 0 ; while ( a < b ) { r += num [ a ] ; ++a ; } return r ; } public static class SumThread extends Thread { private long num [ ] ; private long r ; private int a , b ; public Su... | Java multiple threads give very small perfomance gain |
Java | Here I 'm making a virtual proxy for a heavyweight object . Each time before calling HeavyweightObject : :operate , the program checks first whether the object is null or not . This part is checked once and only once through the entire lifetime of the object . A possible improvement maybe using the state pattern like t... | class HeavyweightObjcet { public void operate ( ) { System.out.println ( `` Operating ... '' ) ; } } class LazyInitializer { HeavyweightObjcet objcet ; public void operate ( ) { if ( objcet == null ) objcet = new HeavyweightObjcet ( ) ; objcet.operate ( ) ; } } class HeavyweightObjcet { public void operate ( ) { System... | Does it makes sense to use state pattern with virtual proxies ? |
Java | The above code will convert the the whole array of integers into an array of Strings ( containing binary format of the input string ) , but there is a caveat.For Example : If the input array is : 2 3 7 10The binary string array will be:10111111010But I want the output array to be like the following:0010001101111010 # 2... | for ( int i = 0 ; i < n ; i++ ) { arr [ i ] = scanner.nextInt ( ) ; } String [ ] bin = new String [ n ] ; for ( int i = 0 ; i < n ; i++ ) { bin [ i ] = Integer.toBinaryString ( arr [ i ] ) ; } | How do I convert an array of integers to binary ? |
Java | More precisely , if there exists a function in the call stack with the strictfp modifier , will the function at the top of the call stack also adhere to the strictfp specifier ? In this example , foo1 and foo2 appear to return the same value . In other words , it does n't look like it matters whether the function at th... | public class Main { // case 1 : strictfp not present at top of call stack private static double bar1 ( double x ) { return Math.sin ( x ) ; } strictfp private static double foo1 ( double x ) { return bar1 ( x ) ; } // case 2 : strictfp present at top of call stack strictfp private static double bar2 ( double x ) { retu... | Does Java 's strictfp modifier apply through function calls ? |
Java | Let 's say we 've got the following classes : Why does the following assignment compile without any problems : but this one : fails with this compile error : Error : java : incompatible types : invalid method reference incompatible types : Event can not be converted to Service.ServiceEvent | interface Event { } @ FunctionalInterfaceinterface EventListener < T extends Event > { void onEvent ( T event ) ; } class Service { class ServiceEvent implements Event { } public void onServiceEvent ( ServiceEvent event ) { } } Service service = new Service ( ) ; EventListener < ServiceEvent > listener = service : :onS... | In Java is it possible to assign a method reference to a variable whose class has a generic type ? |
Java | In Java , is there a generic way to embed the code of a method in a log by any means ? I am working in Cucumber and altough its tending towards ( or is ? ) bad practice , the compliance department wants to see the assertions behind a `` Then '' statement printed out in the report ( they cant access the source code ) . ... | @ Then ( `` ^my profile information is retrieved with success '' ) public void validateProfileInformation ( ) { assertThat ( .. ) .isEqualTo ( .. ) ; assertThat ( .. ) .isEqualTo ( .. ) ; assertThat ( .. ) .isEqualTo ( .. ) ; assertThat ( .. ) .isEqualTo ( .. ) ; assertThat ( .. ) .isEqualTo ( .. ) ; assertThat ( .. ) ... | Embedding contents of a method in a log or report |
Java | how to add 2 or more constructors ? ? i know the use of data class in kotlin , but i am not getting what exactly this keyword is in kotlin and why we have to put anything inside this ? I know kotlin but not that much.how i changedit gives me error to put something inside this . why we use this here and why we should pu... | public class Model { public String mId , mTitle , mDesc ; public Model ( ) { } public Model ( String mId , String mTitle , String mDesc ) { this.mId = mId ; this.mTitle = mTitle ; this.mDesc = mDesc ; } public String getmId ( ) { return mId ; } public void setmId ( String mId ) { this.mId = mId ; } public String getmTi... | Add 2 or more constructors in kotlin |
Java | I discovered that classes with default equals method has differentinstances of meta object Method . Why is it so ? At first glance it looks not optimal because method objects are immutable . | class X { } Method defaultM = Object.class.getMethod ( `` equals '' , Object.class ) Method xMethod = X.class.getMethod ( `` equals '' , Object.class ) xMethod ! = defaultMxMethod.equals ( defaultM ) | Why multiple instances of Method object are for the inherited methods |
Java | I 'm really hoping this can be solved in regex , but I fear not ... .I 'm looking for a regex that will return multiple matches of a term ONLY is another term appears in the same string . This is better explained with an example . Consider : I 'd like to match '144 ' , '424 ' and '345 ' only . ( Any 3 digit number ) - ... | The numbers are 144 , 424 , and 345 . Not 45 . The numbers we are looking for : 234 & 992 Some examples : 234 , 244 and 12 ( ? < =numbers\b ) ( ? : .|\n ) * ? \b ( \d { 3 } ) \b | Regex to match multiple occurances IFF another string occurs |
Java | I have a requirement , where I have a string which is comma separated and then I need to read the individual value and create a collection of object using them.For example my string contains value like foo , bar , baz and then I need to create three object using them likeThere might be multiple spaces before and after ... | Object foo = new Object ( `` foo '' ) ; Object bar = new Object ( `` bar '' ) ; Object baz = new Object ( `` baz '' ) ; | complex operation using stream api in java |
Java | I have list of arrays from which I am picking up a random one.I can print the random output . How to pass the output as xpath value ? ? | String [ ] Category = { `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' } ; Random random = new Random ( ) ; int index = random.nextInt ( Category.length ) ; System.out.println ( Category [ index ] ) ; driver.findElement ( By.xpath ( `` //* [ @ name='\ '' $ { Category [ index ] } \ '' ... | How to add the output to xpath |
Java | While looking at some Java 8 code I saw some use of generics that I did n't quite understand , so I wrote my own code to emulate what was going on : Running this prints : Test_Child constructed with string 'Test'What I do n't understand is : Why do n't you have to provide arguments to Test_Child : :newHow callingf.crea... | public class GenericsTest { public static void main ( String [ ] args ) { TestBuilder tb = TestBuilder.create ( Test_Child : :new ) ; Product < Test_Child > p = tb.build ( ) ; Test tc = p.Construct ( `` Test '' ) ; } static class TestBuilder < T extends Test > { private final Factory < T > f ; public TestBuilder ( Fact... | Using Generics to Construct Instances of Child Classes |
Java | I want to update values of map1 so that it has entries : '' k1 '' , `` val1 '' , '' k2 '' , `` val2 '' , '' k3 '' , `` val3 '' My solution : Is there any better way to do this ? Edit : I am using Java 7 but curious to know if there any better way in Java 8 . | Map < String , String > map1 = new HashMap < > ( ) ; map1.put ( `` k1 '' , `` v1 '' ) ; map1.put ( `` k2 '' , `` v2 '' ) ; map1.put ( `` k3 '' , `` v3 '' ) ; Map < String , String > map2 = new HashMap < > ( ) ; map2.put ( `` v1 '' , `` val1 '' ) ; map2.put ( `` v2 '' , `` val2 '' ) ; map2.put ( `` v3 '' , `` vav3 '' ) ... | Updating Values in Map on the basis of other map in Java |
Java | I 've stumbled across some code that is broadly along the following lines , but can not for the life of me fathom why the author is attempting to remove bar from bars before then adding it : All that I can come up with is that it 's in anticipation of ( or legacy from ) a different Set implementation that 's sensitive ... | import java.util.Set ; import java.util.HashSet ; class Foo { private final Set < Object > bars = new HashSet < > ( ) ; public void addBar ( final Object bar ) { bars.remove ( bar ) ; // WHY ? ? ? ? bars.add ( bar ) ; } public Object [ ] getBars ( ) { return bars.toArray ( new Object [ 0 ] ) ; } } | What possible reason could there be for removing an element from a HashSet immediately prior to re-adding it ? |
Java | I 'm studying for a Java exam and came across the `` unreachable statement '' compiler error , e.g : Am trying to understand when this would or would n't happen - e.g . it does n't happen for these cases : It seems the compiler is n't smart enough to detect when the if condition is constantly true - could someone provi... | Source.java:10 : error : unreachable statement System.out.println ( `` This code is not reachable '' ) ; // Case # 1if ( true ) { System.out.println ( `` This code is reachable '' ) ; } else { System.out.println ( `` This code is not reachable '' ) ; // Compiles OK } // Case # 2for ( i = 0 ; i < 5 ; i++ ) { if ( true )... | Why is n't unreachable code detected when an if condition is a constant ? |
Java | I have the following code and I got following output in consoleWhy does n't this call test ( Object a ) ? Can you some one explain how it took `` List as '' null ? | import java.util.List ; public class Sample { public static void main ( String [ ] args ) { test ( null ) ; } static void test ( List < Object > a ) { System.out.println ( `` List of Object '' ) ; } static void test ( Object a ) { System.out.println ( `` Object '' ) ; } } List of Object | Null value in method parameter |
Java | Say I need to store a collection of Student objects and each student has a unique id . One option is to store all of them in a list , but then when searching for a student , I 'd have to perform a linear search and check their id 's . The other option would be to use a map , of something like : Map where the keys are t... | public void add ( Student s ) { lookup.put ( s.getId ( ) , s ) ; } | Correct usage of storing objects in maps |
Java | I have a piece of code that I use to generate PDF document , it 's simplified just to demonstrate the problem.I want to convert it to functional style with Java 8 streams.I know that I javascript I can use reduce like this : I am trying to use same approach in Java , so my code is something like this : But it 's not co... | PdfPTable table = new PdfPTable ( new float [ ] { 100.0f } ) ; List < PdfPCell > cells = new ArrayList < > ( ) ; List < String > labels = Arrays.asList ( Labels.ITEM_NAME , Labels.QUANTITY , Labels.PRICE ) ; for ( String label : labels ) { PdfPCell cell = new PdfPCell ( new Phrase ( label ) ) ; cells.add ( cell ) ; } f... | Java 8 streams - use reduce with alternative accumulator return type |
Java | Can someone explain to me how to get the following method to return a value of false for the input shown ? It 's returning true , which is something I do n't expect.I think this should return false , but apparently Java does n't think so . The actual date string provided contains these extra characters at the end : `` ... | isDateValid ( `` 19/06/2012 5:00 , 21:00 '' , '' dd/MM/yyyy HH : mm '' ) public static boolean isDateValid ( String date , String dateFormat ) { try { DateFormat df = new SimpleDateFormat ( dateFormat ) ; df.setLenient ( false ) ; Date newDate = df.parse ( date ) ; System.out.println ( `` Date value after checking for ... | Why does an invalid date parses successfully as a real date ? |
Java | Synchronization works correctly in this code : Output : but not in this code : Output : I can not understand what difference wrt Synchronization does it make to initialize PrintNumbers in the Runnable MyThread and in the SyncExample class . Please explain . | class PrintNumbers { synchronized public void display ( ) { System.out.println ( `` in display '' ) ; for ( int i = 0 ; i < 3 ; i++ ) { System.out.println ( `` Thread name : `` + Thread.currentThread ( ) .getName ( ) + `` i= `` + i ) ; try { Thread.sleep ( 1000 ) ; } catch ( InterruptedException e ) { e.getMessage ( ) ... | Why does synchronization not work in the second code ? |
Java | Due to debugging reason most parts of the code in my application has this recurrent portion of code : Now , if the boolean values turn to false this becomes dead code . My question is if in this case the Android compiler would do basics optimizations such as constant folding and dead code remotion ? If the answer is no... | public static final boolean DEBUG = true ; // just created once in a `` Utility '' class if ( Utility.DEBUG ) Log.d ( `` TIMER '' , /*string message that is strictly related to context*/ ) ; | Are hardcoded conditions optimized by JVM in Android ? |
Java | While looking at the Java invokedynamic documentation , I saw the following example of a Java feature called `` exotic identifiers '' : I was unable to get this to work on an openjdk8 on my machine . Further googling found a few bug reports relating to this feature but not much else . Specifically this bug , and this o... | int # '' strange variable name '' = 42 ; System.out.println ( # '' strange variable name '' ) ; // prints 42 | Status of Java exotic identifiers |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.