text
stringlengths
46
37.3k
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 a...
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 ...
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 . <code> ...
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 ? <code> public class LogService { private final BlockingQueue < Strin...
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...
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 di...
Why do almost all Java binaries have the same size
Java : How can I do that ? <code> 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.loadUr...
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...
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 : <code> public class Sorter < T extends Enum < ? > > { public Sorter ( ) { T [ ] result = T.values ( ) ; // < - Compilation error } } enum TmpEnum { A , B } public class Tmp { void func ( ) { T...
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 <code> private String readInputStream ( InputStr...
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 ? <code> class ABC { String a ; ABC ( ) { a = `` abc '' ; } } public...
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 Comma...
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 ? <code> interface Service < T > { < R > R proce...
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 . <code> The method testSuper ( Group < ? super BClass < ? > > ) in the type Group < BClass < String > > is not applicable for the arguments ( Group < ...
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 do...
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 wha...
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 ran...
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...
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...
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 lis...
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 . <code> ...
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 ( ) ) ? <code> List < String > result = myArr .stream ( ) .filter ( line - > ! `` foo '' .equals ( line ) ) .coll...
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 ,...
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 ? <code> public class Base < E > { static void main ( String [ ] args ) { Base < ? extends Base > compound = new Base < Base > ( ) ; compound.method ...
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 ...
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 th...
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 ? <code> String text = `` new SingleSizeProduct ( 422056 , 1265858 , 5430 , '3XL ' , 75 , 0 , '14.90 ' , '16.50 ' , '29.90 ' , 'TL ' ) , ...
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 resolvi...
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 star...
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 : <code> Foo < String > foo = new Foo < > ( ) ; Foo < String > .Bar fooBar = foo.new Bar ( ) ; fooBar.doSomething ( `` thi...
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 correctl...
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 ' ...
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 wh...
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 . <code> public abstract class Validator implements Comp...
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 ? <code> @ GetMappingpublic List < String...
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 g...
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 comparis...
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 ...
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 ? <code> 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 lock...
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...
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 ...
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 ? <code> public static Map < String , List < String > > agg ( ) { List < String > list = Arrays.asList...
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 . <code> pub...
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...
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 valu...
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 whe...
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 getEle...
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 operati...
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...
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 c...
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...
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 , avoi...
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...
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 co...
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 cl...
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 ha...
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...
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 <code> < filter > < filter-name > encodingFilter < /filter-name > < filter-class > org.springframework.web.filter.CharacterEncodingFilter < /filter-...
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 ev...
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 ...
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 , Fo...
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 ! Furth...
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 in...
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 ? <code> if ( ur.contains (...
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 . <code> @ 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 ...
`` 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 ? <code> 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...
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 ...
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 s...
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 ...
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 functio...
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. ap...
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...
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 c...
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 <code> return segadors .stream ( ) .map ( c - > c.getSegadorMedium ( ) .stream ( ) .map ( cm - > Objects.nonNull ( cm.getPhoneSegador ( ) ) ) ) .fin...
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 ? <code> interface I { bo...
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 ...
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...
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:0010001101111...
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 functio...
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 <code> interface Event...
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 co...
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 sh...
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 . <code> class X { } Method defaultM = Object.class.getMethod ( `` equals '' , Object.class ) Method xMethod = X.class.getMe...
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 numb...
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...
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 ? ? <code> String [ ] Category = { `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' , `` abc '' } ; Random random = new Random ( ) ; int index = random.nextInt ...
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 callin...
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 . <code> Map < String , String > map1 = new HashMap < > ...
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 sen...
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 someon...
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 ? <code> import java.util.List ; public class Sample { public static void main ( String [ ] args ) { test ( null ) ; } static void test ( List < 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 key...
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...
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 en...
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 . <code> class PrintNumbers { synchronized public void di...
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 answe...
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...
Status of Java exotic identifiers