lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
How to split this String in java such that I 'll get the text occurring between the braces in a String array ? Output must be :
GivenString = `` ( 1,2,3,4 , @ ) ( a , s,3,4,5 ) ( 22,324 , # $ % ) ( 123,3def , f34rf,4fe ) ( 32 ) '' String [ ] array = GivenString.split ( `` '' ) ; array [ 0 ] = `` 1,2,3,4 , @ '' array [ 1 ] = `` a , s,3,4,5 '' array [ 2 ] = `` 22,324 , # $ % '' array [ 3 ] = `` 123,3def , f34rf,4fe '' array [ 4 ] = `` 32 ''
Split String in java by specified pattern
Java
I have a simple code as below to test the deadlock And Also I have another class called ClassA : So , now I have another code that calls these classes and causes a deadlock as below : As you can see the first thread locks fooB using ca.fooA ( cb ) and the second thread locks fooA using cb.fooB ( ca ) and Nobody has any...
public class ClassB { public synchronized void fooB ( Classs A ) throws InterruptedException { System.out.print ( `` Thread : `` + Thread.currentThread ( ) .getName ( ) + `` entered to fooB \n '' ) ; Thread.sleep ( 1000 ) ; System.out.print ( `` ClassB locked the fooA \n '' ) ; A.lastA ( ) ; } public synchronized void ...
How Deadlock happens in the below code ?
Java
I have a simple User class with a String and an int property . I would like to add two Lists of users this way : if the String equals then the numbers should be added and that would be its new value.The new list should include all users with proper values.Like this : User definition : My method : But it adds a whole lo...
List1 : { [ a:2 ] , [ b:3 ] } List2 : { [ b:4 ] , [ c:5 ] } ResultList : { [ a:2 ] , [ b:7 ] , [ c:5 ] } public class User { private String name ; private int comments ; } public List < User > addTwoList ( List < User > first , List < User > sec ) { List < User > result = new ArrayList < > ( ) ; for ( int i=0 ; i < fir...
Adding two lists of own type
Java
I have a source-code generator that risks generating the following type of code ( just an example ) : In the above example , Inner is ambiguously defined inside of Outer . Outer.Inner can be both a nested class , and a static member . It seems as though both javac and Eclipse compilers can not dereference Outer.Inner.H...
public class Outer { public static final Object Inner = new Object ( ) ; public static class Inner { public static final Object Help = new Object ( ) ; } public static void main ( String [ ] args ) { System.out.println ( Outer.Inner.Help ) ; // ^^^^ Can not access Help } }
How to access a member of a nested class , that is hidden by a member of the outer class
Java
Having this classi can create a Instance of Embryo only if i have a instance of Mother : Question : How to define Mother as an interface ?
public abstract class Mother { public class Embryo { public void ecluse ( ) { bear ( this ) ; } } abstract void bear ( Embryo e ) ; } new Mother ( ) { ... } .new Embryo ( ) .ecluse ( ) ;
How to implement nested non-static classes in interfaces ?
Java
This code print -46 when we cast a float to int , This is because the information was lost during the conversion from type int to type float . How can one know about loss of precision while using float and double ? How can we know the result when we analyze the code before testing it ?
int i = 1_234_567_890 ; float f = i ; System.out.println ( i - ( int ) f ) ; //print -46System.out.println ( i - f ) ; //print 0.0
Convert int to float and back does n't give initial value
Java
I am not able to understand the difference in the way obj and obj2 objects are created in the following code . In particular , I am not sure how a primitive is cast to an object . Looking at some of the other questions here , I thought this was not possible . But the following program compiles and runs fine . In the fi...
public class Test { public static void main ( String args [ ] ) { Integer num = new Integer ( 3 ) ; Object obj = num ; Integer [ ] integerArr = { 1 , 2 , 3 , 4 } ; Object [ ] objArr = integerArr ; boolean contains = false ; for ( int i = 0 ; i < objArr.length ; i++ ) { if ( objArr [ i ] == obj ) { contains = true ; bre...
== operator on objects in Java
Java
Here 's an example that demonstrates the problem I am facing : I 'm aware that objects that were instantiated in another context , are considered `` foreign '' and end up being wrapped by a ScriptObjectMirror instance . I am assuming this is why I 'm running into a problem here . I believe whenever x is dereferenced , ...
ScriptEngine engine = new NashornScriptEngineFactory ( ) .getScriptEngine ( new String [ ] { `` -strict '' } ) ; try { engine.eval ( `` function Foo ( src ) { this.src = src } ; var e = { x : new Foo ( \ '' what\ '' ) } ; '' ) ; ScriptContext c = new SimpleScriptContext ( ) ; c.setBindings ( engine.createBindings ( ) ,...
=== returns false in Nashorn when both references should be pointing to the same object
Java
For Example , Here which is the functional interface , ( sum , price ) - > sum+price is referring to ?
List < Product > productsList = new ArrayList < Product > ( ) ; productsList.add ( new Product ( 1 , '' HP Laptop '' ,25000f ) ) ; productsList.add ( new Product ( 2 , '' Dell Laptop '' ,30000f ) ) ; productsList.add ( new Product ( 3 , '' Lenevo Laptop '' ,28000f ) ) ; productsList.add ( new Product ( 4 , '' Sony Lapt...
Stream.reduce ( Float , BinaryOperator ) BinaryOperator refers which functional interface method ?
Java
for now i have got my project to run on mvn javafx : run . but a module descriptor is required to execute mvn javaFx : jlink . there are some firebase related errors after creating the module info file . some of the imports imports : requires in the module info file : errors : how can i fix this error ?
import com.google.api.core.ApiFuture ; import com.google.auth.oauth2.GoogleCredentials ; import com.google.cloud.firestore . * ; import com.google.firebase.FirebaseApp ; import com.google.firebase.FirebaseOptions ; requires com.google.api.apicommon ; requires com.google.auth.oauth2 ; requires firebase.admin ; requires ...
how to export a javafx-maven project with firebase
Java
Suppose we have the following generic classNow inside main method we have the following code snippetAs a result of executing someType.test ( list ) we will get `` 2nd method '' in our console as well as java.lang.ClassCastException . As I understand , the reason of why second test method being executed is that we do n'...
public class SomeType < T > { public < E > void test ( Collection < E > collection ) { System.out.println ( `` 1st method '' ) ; for ( E e : collection ) { System.out.println ( e ) ; } } public void test ( List < Integer > integerList ) { System.out.println ( `` 2nd method '' ) ; for ( Integer integer : integerList ) {...
Which of the overloaded methods will be called on runtime if we apply type erasure , and why ?
Java
I 'm trying to convert a List to Map without duplicates using a stream but I ca n't achieve it.I can do it using a simple loop like this : but when I try to use a stream , my mind crash.I have to say the PropertyOwnerCommunityAddress contains two object more : Community and Address and the goal of all of this is for ea...
List < PropertyOwnerCommunityAddress > propertyOwnerCommunityAddresses = getPropertyOwnerAsList ( ) ; Map < Community , List < Address > > hashMap = new LinkedHashMap < > ( ) ; for ( PropertyOwnerCommunityAddress poco : propertyOwnerCommunityAddresses ) { if ( ! hashMap.containsKey ( poco.getCommunity ( ) ) ) { List < ...
Java Stream : List of objects to HashMap without duplicates
Java
I 'm not entirely sure if this is the right place to ask this . Well , it is a programming problem I suppose.I am trying to create a simple PID Controller simulation in Java.In short , there is a target value and a current value . The current value is modified by a number . You provide the PID Controller the current va...
public class PID { private static double Kp = 0.1 ; private static double Kd = 0.01 ; private static double Ki = 0.005 ; private static double targetValue = 100.0 ; private static double currentValue = 1.0 ; private static double integral = 0.0 ; private static double previousError = 0.0 ; private static double dt = 0....
Why does a lower delta cause my PID controller to adjust with less precision ?
Java
Is it reasonable to maintain a reference to an exception for later use , or are there pitfalls involved with keeping a reference to an exception for significantly longer than the throw/catch interaction ? For example , given the code : Assuming that my program creates a Thing with a lifespan as long as the JVM , are th...
class Thing { private MyException lastException = ... ; synchronized void doSomethingOrReportProblem ( ) { try { doSomething ( ) ; } catch ( MyException e ) { if ( seemsLikeADifferentProblem ( e , lastException ) ) { reportProblem ( e ) ; } lastException = e ; } } }
What 's a reasonable lifespan to expect of a java exception ?
Java
I thought the result could be '43 ' because the type of q was 'poly 1 ' . However , the result was '44 ' . I could n't understand that . please give me the answer .
class poly1 { int a ; public poly1 ( ) { a = 3 ; } public void print_a ( ) { System.out.print ( a ) ; } } public class poly2 extends poly1 { public poly2 ( ) { a = 4 ; } public void print_a ( ) { System.out.print ( a ) ; } public static void main ( String [ ] args ) { poly2 p = new poly2 ( ) ; p.print_a ( ) ; poly1 q =...
Why the result of this java program is '44 ' ?
Java
I 've tried looking but I ca n't seem to find a solution to my justification problem . I want all the transaction amounts , which turn up with 2 decimals digits , to be all justified to the right , however , nothing I try seems to work . This is the result :
Transaction temp ; String message = `` '' ; for ( int i = 0 ; i < checkAccnt.gettransCount ( ) ; i++ ) { temp = checkAccnt.getTrans ( i ) ; message += String.format ( `` % -10d '' , temp.getTransNumber ( ) ) ; message += String.format ( `` % -10d '' , temp.getTransId ( ) ) ; message += String.format ( `` % 10.2f '' , t...
Right Justification in Java
Java
In the source code of java.util.Scanner I 've found these static utility methods : Why it was done in such a complex way and not just , say , What was the point of using a local variable ( lp ) here ? Is this some kind of optimization technique ? Or maybe precaution against a concurrent modification ? But linePattern c...
private static Pattern separatorPattern ( ) { Pattern sp = separatorPattern ; if ( sp == null ) separatorPattern = sp = Pattern.compile ( LINE_SEPARATOR_PATTERN ) ; return sp ; } private static Pattern linePattern ( ) { Pattern lp = linePattern ; if ( lp == null ) linePattern = lp = Pattern.compile ( LINE_PATTERN ) ; r...
Using a local variable when initializing a static variable
Java
I am submitting a change to JNA which has in previous releases defined a set of constants as int type , specifically : ( Since they are defined in an interface they are automatically static and final . ) These constants are used as the Condition argument in the VerSetConditionMask function , which requires a BYTE argum...
int VER_EQUAL = 1 ; int VER_GREATER = 2 ; int VER_GREATER_EQUAL = 3 ; ... etc ... byte VER_EQUAL = 1 ; byte VER_GREATER = 2 ; byte VER_GREATER_EQUAL = 3 ; ... etc ...
Can I change constant from int to byte in Java without breaking backward compatibility ?
Java
JLS 8.1.3 gives us the rule about variables which are not declared in an inner class but used in the class . Any local variable , formal parameter , or exception parameter used but not declared in an inner class must either be declared final or be effectively final ( §4.12.4 ) , or a compile-time error occurs where the...
class A { void baz ( ) { int i = 0 ; class Bar { int j = i ; } } public static void main ( String [ ] args ) { } }
Usage of a non-final local variable within an inner class
Java
I have a Dataset < Row > in java . I need to read value of 1 column which is a JSON string , parse it , and set the value of a few other columns based on the parsed JSON value . My dataset looks like this : And I need to make it like this : I am unable to figure out a way to do it . Please help with the code .
|json | name| age |======================================== | `` { ' a ' : 'john ' , ' b ' : 23 } '' | null| null | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | `` { ' a ' : 'joe ' , ' b ' : 25 } '' | null| null | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- | `` { ' a ' : 'zack ' } '' |...
Need to set values in columns of dataset based on value of 1 column
Java
I 've run into a case where I thought the JIT should have an easy time optimising , but it does not seem to.I 've reduced the problem to a minimal example : Consider a class IntArrayWrapper : The only difference between the two methods is that x is an Integer ( boxed ) or an int ( primitive ) .I 've written some JMH be...
class IntArrayWrapper { private int [ ] data = new int [ 100000 ] ; public void setInteger ( int i , Integer x ) { data [ i ] = x ; } public void setInt ( int i , int x ) { data [ i ] = x ; } } @ Benchmarkpublic void bmarkSetIntConst ( ) { final IntArrayWrapper w = new IntArrayWrapper ( ) ; for ( int i = 0 ; i < 100000...
Odd Performance ( Boxed Integers )
Java
I have just moved my application from Java8 to Java10 , as part of that I now need to add -- add-modules java.xml.bindto avoid java.lang.NoClassDefFoundError : javax/xml/bind/JAXBExceptionexception.And this works fine in my batch filebut I can not get my equivalent winrun4j .ini file to work I have tried addingand then...
JVM64\bin\java -- add-modules java.xml.bind -cp lib ; lang -Xms150m -Xmx400m -jar lib/SongKong-5.7.jar % 1 % 2 % 3 % 4 % 5 % 6 % 7 % 8 % 9 vmarg.1= -- add-modules java.xml.bind vmarg.1= -- add-modulesvmarg.2=java.xml.bind
Unable to get vmargs identified in winrun4j ini file
Java
I 'm looking for a non-blocking way to sum a Stream of CompleteableFuture < BigDecimal > .I already found topics closely related to this problem , like this.But unfortunately in my case I do have the BigDecimal packed into a CompleteableFuture and therefore I need to wait for completion first.In the end I would like to...
Stream < CompletableFuture < BigDecimal > > lotOfWork ; CompletableFuture.supplyAsync ( ( ) - > lotOfWork.map ( CompletableFuture : :join ) .reduce ( BigDecimal.valueOf ( 0.0 ) , BigDecimal : :add ) ) ;
How to sum a Stream of CompleteableFuture < BigDecimal > conveniently ?
Java
I am trying to search for a String inside a file content which I got into a String.I 've tried to use Pattern and Matcher , which worked for this case : Then , I tried to use the same code to find how many tags I have : which in this case , the return value was always 0 .
Pattern p = Pattern.compile ( `` ( < /machine > ) '' ) ; Matcher m = p.matcher ( text ) ; while ( m.find ( ) ) //if the text `` ( < /machine > ) '' was found , enter { Counter++ ; } return Counter ; Pattern tagsP = Pattern.compile ( `` ( < / '' ) ; Matcher tagsM = tagsP.matcher ( text ) ; while ( tagsM.find ( ) ) //if ...
Look for a certain String inside another and count how many times it appears
Java
Please consider the following example : In order to make this class immutable , I must defensively copy any mutable parameter passed to the constructor and create copies of internal mutable objects returned by public methods . Is this possible ? If not , is there any workaround ?
public final class ImmutableWrapper < T extends Number > { private final T value ; public ImmutableWrapper ( T value ) { // a subclass of Number may be mutable // so , how to defensively copying the value ? this.value = value ; } public T getValue ( ) { // the same here : how to return a copy ? return value ; } }
Defensive copying of Number subclass
Java
What actually means using brackets in brackets while initializing e.g . new List ? Does it mean that after creating new reference method is invoking ?
new ArrayList < String > ( ) { { add ( `` A '' ) ; } } ;
Brackets in Bracket in Java
Java
I am doing an exercise from an introduction to Object Oriented Programming with Java C. Thomas Wu.Page 73 provides the code to request the full name , tokenize it using delimiter and print it back.Problem is , mine doesnt seem to want to print it back , and it freezes the program , forcing the use of task manager to cl...
import java.util . * ; class Scanner1 { public static void main ( String [ ] args ) { String name ; Scanner scanner = new Scanner ( System.in ) ; scanner.useDelimiter ( System.getProperty ( `` line.separator '' ) ) ; System.out.print ( `` Enter full name ( first , middle , last ) '' ) ; name = scanner.next ( ) ; System...
Delimiter usage , why does Scanner not return ?
Java
say I have 2 instances of the same class , but they behave differently ( follow different code paths ) based on a final boolean field set at construction time . so something like:2 instances of Foo with different values for flag could in theory be backed by 2 different assemblies , thereby eliminating the cost of the i...
public class Foo { private final boolean flag ; public Foo ( boolean flagValue ) { this.flag = flagValue ; } public void f ( ) { if ( flag ) { doSomething ( ) ; } else { doSomethingElse ( ) ; } } }
can moderm JVMs optimize different instances of the same class differently ?
Java
I 'm playing around with predefined Identity filters for use with the stream api . Unfortunately I 'm unable to properly return a generic predicate that is compliant with the stream api documentation.According to the de-compiler here is the Stream : :filter definition : I 'm facing the issue with any Java version that ...
public interface Stream < T > extends BaseStream < T , Stream < T > > { Stream < T > filter ( Predicate < ? super T > var1 ) ; Collection < String > result = Stream.of ( `` A '' , `` B '' , `` C '' ) .filter ( new Object ( ) : :equals ) .filter ( Integer.valueOf ( -1 ) : :equals ) .collect ( Collectors.toSet ( ) ) ; Pr...
Force Stream : :filter method to fail compile time when Predicate < ? super Object > is passed rather than Predicate < ? super T >
Java
A little know feature of the Eclipse 's Java compiler is that you can run it from the command line.This works well ( after patching plexus-compiler to use the latest release ) .My problem : The stack traces are different when I compile the code from the command line . For example , when I run the compiler in the IDE , ...
at com.some.Foo.method ( Foo.java:312 ) at com.some.Foo.method ( com.some.Foo:312 ) ^^^^^^^^^^^^ SourceFile : `` Foo.java '' SourceFile : `` com.some.Foo ''
Eclipse 's Java Compiler produces different stack traces when run from the command line
Java
I see the following code in a Java/Swing GUI project : In the code above , MyDialog extends JDialog . So clearly , a child dialog is being constructed ( and somehow shown to the end user ) , and then when the user exits the dialog ( by clicking OK or some other button ) , a results bean is used to fire a new event on t...
MyDialog dlg = new MyDialog ( parent , isFizz ) ; MyDialogResults results = dlg.getResults ( ) ; eventBus.fireEvent ( new MyDialogEvent ( results ) ) ; public class MyDialog extends JDialog { private boolean isFizz ; private MyDialogResults results ; // Getters and setters for all properties ... public MyDialog ( Frame...
How is this Swing code working ?
Java
I have a list of Items where each Item can belong to one or more category . For a limited set of categories ( string ) I want to create a map with category as key and list of Items as value . Assume my Item class is defined as shown below : and a list of Items : How can i fill myMap from myList ? I thought Stream API c...
public static class Item { long id ; List < String > belongsToCategories ; public List < String > getBelongsToCategories ( ) { return belongsToCategories ; } public void setBelongsToCategories ( List < String > belongsToCategories ) { this.belongsToCategories = belongsToCategories ; } public Item ( long id , List < Str...
How to group objects from a list which can belong to two or more groups ?
Java
I want to generate a random number to apply to some arrays in order to get different elements in each execution.The arrays contain names of sport products ( product , size , price , etc ) . By doing this , I want to make random products that would go into a String , but in each execution of the program , I get the same...
public void generaProductos ( ) { int num ; for ( int i=0 ; i < 3 ; i++ ) { num = ( int ) Math.random ( ) * 3 ; String cliente = tipoProducto [ num ] + `` `` + deporte [ num ] + `` `` + destinatario [ num ] + `` `` + color [ num ] + `` `` + tallaRopaAdulto [ num ] + `` `` + preciosIVA [ num ] ; System.out.println ( cli...
Getting the same random number
Java
The below code is in Class String in java . I do n't understand why the characters from two different strings are compared twice.at first by doing upper case and if that fails by doing lower case.My Question here is , is it required ? If yes , why ?
public static final Comparator < String > CASE_INSENSITIVE_ORDER = new CaseInsensitiveComparator ( ) ; private static class CaseInsensitiveComparator implements Comparator < String > , java.io.Serializable { // use serialVersionUID from JDK 1.2.2 for interoperability private static final long serialVersionUID = 8575799...
Why is the same character compared twice by changing its case to UPPER and then to lower ?
Java
Reading the Java language specs , I found this excerpt about final fields : The usage model for final fields is a simple one : Set the final fields for an object in that object 's constructor ; and do not write a reference to the object being constructed in a place where another thread can see it before the object 's c...
public class Test { private static final ConcurrentLinkedQueue < A > myAs = new ConcurrentLinkedQueue < > ( ) ; private static long timer = System.nanoTime ( ) + 3000000000L ; // 3 seconds into the future public static void main ( String ... args ) { B myB = new B ( `` thread # 1 '' ) ; // Set in thread 1 new Thread ( ...
If you assign an Object to a final field , will other threads see previous updates of that Object 's non-final/non-volatile fields ?
Java
I have created a MWE where changing a single line by adding < ? > solves a compiler error.The following code does not compile : The compiler error is : Changing the definition in the offending line from MyEntity myEntity to MyEntity < ? > myEntity solves the issue . I wonder why is the return type of this for-each trea...
import java.util.List ; public class MainClass { public void traverse ( ) { List < MyEntity > list = null /* ... */ ; for ( MyEntity myEntity : list ) { for ( String label : myEntity.getLabels ( ) ) { // < -- Offending Line /* ... */ } } } interface MyEntity < T > { T get ( ) ; List < String > getLabels ( ) ; } } Error...
Omitting < ? > unintuitively breaks this code
Java
We 've started getting compile errors on code that used generics and that compiled successfully under Java 6 . Here 's a simple class to reproduce : The resulting error is : Does anybody have any ideas ?
class Test { static class Foo < T > { T t ; Foo ( T t ) { this.t = t ; } T get ( ) { return t ; } } static class Bar extends Foo < Long > { Bar ( Long t ) { super ( t ) ; } } static class Foobar < N extends Number > extends Bar { Foobar ( ) { super ( 5L ) ; } } public static void main ( String [ ] args ) { Bar bar = ne...
Java generic compile time error migrating from Java 6 to 7 or 8
Java
I am pretty new to Java , and I am trying to write the below logic in functional way.I have a list of Objects , which have many fields . List < someObject > The fields of interest for now are long timestamp and String bookTypeThe problem statement is - I want to find the count of number of Objects in given list which h...
n.stream ( ) .sorted ( Comparator.comparingLong ( someObject : :timestamp ) ) .collect ( Collectors.toList ( ) ) ;
Java 8 : functional way to write sort , filter and count at same time
Java
I have such hashmapThen I add new pair into it.How can I retrieve this pair from this map ? I tried to do : But as a result I have null while I expected 5 .
HashMap < Man , Double > d = new HashMap < > ( ) ; d.put ( new Man ( `` John '' ) , 5 . ) ; Man man = new Man ( `` John '' ) ; System.out.println ( d.get ( man ) ) ;
Get value from Hashmap by user object
Java
I have the following : This is what it looks like : The ParametricEQView is the component with the white background filling most of the window . In this image its coordinates are ( 0,0 ) in the containing frame and everything is great . However , if I resize the window so that the ParametricEQView moves over a bit ( it...
public class ParametricEQView extends JPanel implements PluginView { private static final int BAND_WIDTH = 3 ; private static final int THROW_HEIGHT = 64 ; private static final int WIDTH = 128*BAND_WIDTH + 2*MARGIN ; private static final int HEIGHT = 2*THROW_HEIGHT + 2*MARGIN ; private static final int MID_HEIGHT = THR...
AffineTransform seeming to ignore component bounds
Java
why I can not check the same radiobutton after I uncheck it programmatically , when I click next button , unless I check another radiobutton.This is the code that unchecks radiobuttons : And this is where I try to check it :
if ( q.trim ( ) ! = null || q.trim ( ) ! = `` '' ) { questionView.setText ( q ) ; r1.setChecked ( false ) ; r2.setChecked ( false ) ; r3.setChecked ( false ) ; r1.clearFocus ( ) ; r2.clearFocus ( ) ; r3.clearFocus ( ) ; r1.setText ( varNames.get ( `` ra0 '' ) ) ; r2.setText ( varNames.get ( `` ra1 '' ) ) ; r3.setText (...
Can not check radiobutton
Java
When I right-klick on a package - > new - > package , check the `` create package-info.java '' , Eclipse 4.4.2 puts a template for a package-info.java into that directory . That 's good . It looks like this : As you can see , there are two blocks of comments . My question is : what is the purpose of the upper block ? I...
/** * *//** * @ author John Doe * */package name.of.pkg ;
Why does Eclipse generate two comment blocks into a package-info.java
Java
With this code : new Test ( ) will print `` Test '' twice . As a beginner I was expecting the output to be `` SuperTest / Test '' . I understand now why this is not possible , and why the implicit this will refer to child type only.However I ca n't find what whoAmI ( ) should be to actually print the output SuperTest /...
class SuperTest { SuperTest ( ) { whoAmI ( ) ; } void whoAmI ( ) { System.out.println ( getClass ( ) .getName ( ) ) ; } } class Test extends SuperTest { Test ( ) { whoAmI ( ) ; } }
Inheritance : Is there a way to discover the class a method was called from ?
Java
When I try to push an element into a Java array where I take the array size from a constructor argument , it throws an ArrayIndexOutOfBoundsException exception . However , when I set the size while declaring the array adding an element works . Here is my code : The following throws the exception :
public class Stack { public int size ; public Stack ( int size ) { this.size = size ; } public int [ ] arr = new int [ size ] ; public int top = -1 ; // Methods public void push ( int value ) { top++ ; arr [ top ] = value ; } } new Stack ( 10 ) .push ( 123 ) ;
ArrayIndexOutOfBoundsException from array initialized with field value
Java
I 'm trying to collapse several streams backed by huge amounts of data into one , then buffer them . I 'm able to collapse these streams into one stream of items with no problem . When I attempt to buffer/chunk the streams , though , it attempts to fully buffer the first stream , which instantly fills up my memory . It...
import java.util . * ; import java.util.stream.LongStream ; import java.util.stream.Stream ; import java.util.stream.StreamSupport ; public class BreakStreams { // @ see https : //stackoverflow.com/questions/47842871/buffer-operator-on-java-8-streams /** * Batch a stream into chunks */ public static < T > Stream < List...
Java Streams - Buffering huge streams
Java
Sometime output is `` Result 1 '' and sometime output is `` Result 2 '' . Can you explain why ? I am using JDK 1.6_33 .
public class Main { public static void main ( String [ ] args ) { System.out.println ( X.Y.Z ) ; } } class X { static class Y { static String Z = `` Result 1 '' ; } static C Y = new C ( ) ; } class C { String Z = `` Result 2 '' ; }
Different output after execution main class
Java
I am trying to create a LinkedList of LinkedLists in Java . The following code segment is giving an error . I am using java 11 and util.ListNo idea why I am getting this error..It gives the following errors : How should I go on resolving this ? Okay , so just to test I created a dummy class just to create LinkedList of...
N = in.read ( ) ; List < List < Integer > > L ; L = new LinkedList < > ( ) ; for ( i = 0 ; i < N ; i++ ) L.add ( new LinkedList < > ( ) ) ; A.java:25 : error : can not infer type arguments for LinkedList L = new LinkedList < > ( ) ; ^ reason : can not use ' < > ' with non-generic class LinkedListA.java:26 : error : can...
Error while creating LinkedList of LInkedLists
Java
I 'm having trouble understanding why I 'm getting a compilation error here . Let me share some simple code . The following block of code works fine : The problem arises when I add a new generic List parameter to MethodB , calling it from MethodA : Which gives me the following error : Exception in thread `` main '' jav...
public class Test { public static void main ( String [ ] args ) { String [ ] arr = new String [ 0 ] ; MethodA ( arr ) ; } public static < E > void MethodA ( E [ ] array ) { Integer [ ] intArray = new Integer [ 0 ] ; MethodB ( array , intArray ) ; } public static < E > void MethodB ( E [ ] array , E [ ] secondArray ) { ...
Java Generics - Confusing behavior
Java
I want to know how to extract a List < D > from a HashMap < E , R > considering these constraints : E is a custom class ; R is a custom class containing a Set < D > of custom objects ; What I have tried : I tried addressing the issue in this question.In that previous case , I had a simple Map < E , List < R > > , but i...
Map < E , R > map = new HashMap < E , R > ( ) ; public List < D > method ( String countryname ) { return map.values ( ) .stream ( ) .filter ( ( x ) - > { return x.getSet ( ) .stream ( ) .anyMatch ( ( t ) - > { return t.getCountry ( ) .equals ( countryname ) ; } ) ; } ) .map ( R : :getSet ) .flatMap ( List : :stream ) ....
How to extract a List < D > from a HashMap < E , R > using stream
Java
Comming from a Java background , when developing services connected by JMS I used to process messages and distinguish them by checking their type , e.g ( simplified ) : So now I am building a messaging front-end for some Python modules in RabbitMQ ( topic communication ) . I am planing on using one queue for each consu...
Object object = myQueue.consume ( ) ; if ( object instanceof MessageA ) { processMessageA ( ( MessageA ) object ) } else if ( object instanceof MessageB ) { processMessageB ( ( MessageB ) object ) } ...
What is the most Pythonic way of processing messages like this Java `` instance-filtering '' [ RabbitMQ ]
Java
I have connected the oracle to my Java program , and it is working fine but it gives a problem on a primary key field , when I try to access it it throws an java.sql.SQLException : The query works , when ran in the sqlDeveloper.Here is the code : It give exception and does n't identify the field USER_ID.USERS table and...
select user_id from users where users.user_name = ' '' +username+ '' ' and ` users.user_role = ( select user_roles.role_id FROM user_roles where ` user_roles.role_name = ' '' +role+ '' ' ) '' Statement st = null ; ResultSet rs = null ; Integer userMovedTo = new Integer ( 0 ) ; Integer userMovedBy = new Integer ( 0 ) ; ...
Accessing a oracle sql field through java
Java
In Java , I am generating a string with letters A and B with a COMBINING OVERLINE U+0305 character in between.I get this in IDEA : But if I copy to here , it will become A̅B.This one is from the Chrome console : I was confused by the combining character 's combining order . Which one is correct ? I was writing this in ...
@ Testpublic void test ( ) { System.out.println ( `` A\u0305B '' ) ; }
Why is Unicode combining character order different between IDEA and Chrome ?
Java
I am confused about how are the methods and constructors called at runtime , since the derived constructor is printed 3 times and the height is printed 0I have tried printing some messages inside methods and constructors as to know what exactly is happeningI expected the output to be instead I am getting
public class Derived extends Base { public static void main ( String args [ ] ) { System.out.println ( `` Hello World '' ) ; Derived d = new Derived ( ) ; } protected Derived ( ) { System.out.println ( `` Inside Derived Const '' ) ; showAll ( ) ; } protected void showAll ( ) { System.out.println ( `` Inside Derived sho...
Why does the program print the height value 0 instead of the one I set ?
Java
Say I have the following code : My question is , do the following versions of the add method need to have number as volatile in the below cases : I understand that these are both atomic operations , but my question is , is the value of number guarennteed to be pushed out to global memory and visible to all threads with...
private Integer number ; private final Object numberLock = new Object ( ) ; public int get ( ) { synchronized ( number or numberLock ) { return Integer.valueOf ( number ) ; } } public void add ( int num ) { synchronized ( number ) number = number + num ; } public void add ( int num ) { synchronized ( numberLock ) numbe...
Does the actual lock matter when deciding to use volatile ?
Java
Say I have two arrays of DoubleUsing Java streams , how do I create a map ( Map < Double , Double > myCombinedMap ; ) that combines the two arrays for example in the following way : I guess am looking for something similar to Python zip with Java streams , or an elegant workaround . I think this question differs from t...
Double [ ] a = new Double [ ] { 1.,2.,3 . } ; Double [ ] b = new Double [ ] { 10.,20.,30 . } ; System.out.println ( myCombinedMap ) ; { 1.0=10.0 , 2.0=20.0 , 3.0=30.0 }
How to create a map out of two arrays using streams in Java ?
Java
I faced with code , which compilation result was surprised for me.Always I supposed that if I pass value to method it means that method argument assigns to passed value.Is it wrong ratification ?
public class Test3 { public static < K , V > Map < K , V > map ( ) { return new HashMap < K , V > ( ) ; } } class A { static void f ( Map < String , Integer > bcMap ) { } public static void main ( String [ ] args ) { f ( Test3.map ( ) ) //not valid Map < String , Integer > m = Test3.map ( ) ; //valid } }
Different behaviour for generic method return value to method and to assignment
Java
I have this class : I 'm instantiating it like this and somehow it 's working , even though I 'm inserting an ArrayList < String > into a constructor that accepts List < Integer > : This is what I see after instantiation : How can this be possible ? Also , how can I make sure from the instantiation code that the correc...
public class TestSubject { public TestSubject ( List < Integer > list ) { } } List < String > strings = new ArrayList < > ( ) ; strings.add ( `` foo '' ) ; Constructor < TestSubject > constructor = TestSubject.class.getConstructor ( List.class ) ; TestSubject test = constructor.newInstance ( strings ) ;
How am I able to insert an ArrayList < String > into a constructor that accepts List < Integer > ?
Java
Ca n't figure out how to read out average weight of animals in a list for a specific building . I 've written another method that gets the names of the animals per kind of animal , so I know my persistency is working.Zoo : Animal : Building : I want to get the average weight of the animals per building , so the idea is...
public class Zoo { private List < Animal > animals ; private List < Building > buildings ; public Zoo ( ) { this.animals = new PersistencyController ( ) .giveAnimals ( ) ; this.gebouwen = new PersistencyController ( ) .giveBuildings ( ) ; } public List < Animal > giveAnimalsByKind ( String kindName ) { return animals.s...
Average specific values from a list within a list using Java stream
Java
Lets suppose we have the following code : The question is about public static < T > T testMe ( List < ? super T > list1 , List < ? extends T > list2 ) . How does the compiler determine the T type if if have three classes : A , B , C , ? This question arose when I analysed Collections.copy .
class A { } class B extends A { } class C extends B { } public static < T > T testMe ( List < ? super T > list1 , List < ? extends T > list2 ) { return null ; } public static void main ( String [ ] args ) { List < B > listB = new ArrayList < > ( ) ; List < C > listC = new ArrayList < > ( ) ; // All three variants are p...
How is type inferred where return type is also upper and lower bound for method parameters
Java
I 'm analyzing the LongAdder algorithm in detail . LongAdder extends the class Striped64 and in that class the essential method is retryUpdate . The following piece of code is taken from this method ; in the linked source code it occupies lines 212–222 : Question : How can this try block fail ? Note that the array acce...
try { // Recheck under lock Cell [ ] rs ; int m , j ; if ( ( rs = cells ) ! = null & & ( m = rs.length ) > 0 & & rs [ j = ( m - 1 ) & h ] == null ) { rs [ j ] = r ; created = true ; } } finally { busy = 0 ; } rs [ j = ( m - 1 ) & h ]
LongAdder : How can the try block fail ?
Java
Please correct me if I am wrong somewhere.I have been taught , that Every time a class is loaded , a class object is created in heap memory , and its reference by the name of Class is kept in class areaEach and every field , like string , int whatsoever is the is also stored in as objects and its reference is given in ...
class b { String s= '' sdnla '' ; }
Please correct me on this , its very confusing
Java
Why am I getting this compiler error on FuzzyWuzzyContainer ? Bound mismatch : The type FuzzyWuzzy is not a valid substitute for the bounded parameter < T extends Fuzzy & Comparable < T > > of the type FuzzyContainerFuzzyWuzzy does in fact implement both interfaces that are defined in the bounded generic .
public interface Fuzzy { boolean isFuzzy ( ) ; } public class FuzzyWuzzy implements Fuzzy , Comparable < Fuzzy > { public boolean isFuzzy ( ) { return true ; } public int compare ( Fuzzy o ) { return 0 ; ) } public abstract class FuzzyContainer < T extends Fuzzy & Comparable < T > > { : } public class FuzzyWuzzyContain...
Getting compile error on type parameter with multiple bounds
Java
I 'm testing with this code : I compiled it with javac 1.8.0_05 , and then inspected the bytecode : Apparently , leftComparison is compiled to push and pop 1 variable on the stack while rightComparison pushes and pops 2 . I speculate that leftComparison is therefore slightly more efficient than rightComparison ? I 'm w...
public class TestNull { public void leftComparison ( String s ) { if ( s == null ) ; } public void rightComparison ( String s ) { if ( null == s ) ; } } public class TestNull { ... . public void leftComparison ( java.lang.String ) ; Code : 0 : aload_1 1 : ifnonnull 4 4 : return public void rightComparison ( java.lang.S...
why does n't the java compiler rewrite this code ?
Java
In a Java source , I do n't want use some package . For instance , I do n't want any reference to swing , or io , or other.Is there a system to check that , at compile time , or at test time ? For instance , with supposed annotationWhy I need this ? Because I have an application with swing , and I want refactor it with...
@ NoPackage ( `` javax.swing '' ) class Foo { private JFrame fram ; // NOT OK . }
How to check if there is no reference to a package in a Java source
Java
I know that run method should not be called to start a new thread execution , but i was referring this article where they have called runnable.run ( ) ; inside another run method and it seems to be implying that it starts a new thread or its not at all creating threads , it just creates a new thread and runs all runnab...
public class ThreadPool { private BlockingQueue taskQueue = null ; private List < PoolThread > threads = new ArrayList < PoolThread > ( ) ; private boolean isStopped = false ; public ThreadPool ( int noOfThreads , int maxNoOfTasks ) { taskQueue = new BlockingQueue ( maxNoOfTasks ) ; for ( int i=0 ; i < noOfThreads ; i+...
is it possible to start a thread by calling run ( ) inside a run ( ) method ?
Java
In a java library I came across a method which uses a generic return type that is not used in any way in the parameters : ( ResponseCallBack is an interface here ) What is the difference with this signature :
< T extends ResponseCallBack > T sendData ( @ Nonnull final OrderIf checkoutOrder , @ Nullable final List < NameValueIf > ccParmList ) throws Exception ; ResponseCallBack sendData ( @ Nonnull final OrderIf checkoutOrder , @ Nullable final List < NameValueIf > ccParmList )
Java generic return type not used in parameters
Java
I need to build a regular expression that finds the word `` int '' only if it 's not part of some string.I want to find whether int is used in the code . ( not in some string , only in regular code ) Example : thanks !
int i ; // the regex should find this one.String example = `` int i '' ; // the regex should ignore this line.logger.i ( `` int '' ) ; // the regex should ignore this line . logger.i ( `` int '' ) + int.toString ( ) ; // the regex should find this one ( because of the second int )
Help building a regex
Java
orBoth these perform the same operation.Input : [ [ 7,0 ] , [ 4,4 ] , [ 7,1 ] , [ 5,0 ] , [ 6,1 ] , [ 5,2 ] ] Output : [ [ 7,0 ] , [ 7,1 ] , [ 6,1 ] , [ 5,0 ] , [ 5,2 ] , [ 4,4 ] ] I know the code is sorting it in groups but I do n't understand how . I was similarly confused about PriorityQueue in Java : This one sorts...
Arrays.sort ( people , ( n1 , n2 ) - > ( n2 [ 0 ] == n1 [ 0 ] ) ? n1 [ 1 ] - n2 [ 1 ] : n2 [ 0 ] - n1 [ 0 ] ) ; Arrays.sort ( people , new Comparator < int [ ] > ( ) { @ Override public int compare ( int [ ] n1 , int [ ] n2 ) { return ( n2 [ 0 ] == n1 [ 0 ] ) ? n1 [ 1 ] - n2 [ 1 ] : n2 [ 0 ] - n1 [ 0 ] ; } } ) ; Priori...
How does this @ Override for Arrays.sort work in Java ?
Java
I wish to implement something looks like this : Is it possible ? If its impossible by Java itself , can I do it by JNI ?
if ( isJavaVirtualMachine ( ) ) { System.out.println ( `` You are running on a JVM '' ) ; } else if ( isDalvikVirtualMachine ( ) ) { Log.i ( `` env '' , '' You are running on an android . `` ) ; }
is it possible to determine whether the current VM is Java SE or Dalvik ?
Java
Suppose you have an enum with 3 values : You switch over all values of it in some method , thinking you 've handled all cases : Then later , you add a new value to the enum : And everything still compiles fine , except you 're silently missing a case for YELLOW in the method . Is there a way to raise a compile-time err...
enum Colors { RED , GREEN , BLUE } switch ( colors ) { case RED : ... case GREEN : ... case BLUE : ... } enum Colors { RED , GREEN , BLUE , YELLOW }
Is there a way to enforce that you 're switching over all defined values of an enum in Java ?
Java
I have a List of objects of the following class : This list is fetched from a database with order by date asc , number desc , but the part that need to be retained all the time is the ordering by date asc . Example of the result ( Dateformat = MM/dd/yyyy ) : Now I want to order that list so that it results in : As you ...
public class Foo { private Date date ; private String name ; private Long number ; } 01/01/2016 Name1 92856201/01/2016 Name2 91078501/01/2016 Name3 81129001/01/2016 Name4 81128901/01/2016 Name5 500000002/01/2016 Name3 87770202/01/2016 Name1 85296002/01/2016 Name2 74964002/01/2016 Name4 74950002/01/2016 Name5 5000000 01...
`` Partially '' sorting list of POJO
Java
I 'm implementing an app using a webview . For the urls loaded in the webview I 'd need to perform a replacement over the html code loaded in the url.How can I do this in a efficient way ? Explanation : I need to replace an specific script script from the source : In example : I want to I want to display the user this ...
< html > < script > SCRIPT A < /script > < p > Hello World < /p > < /html > < html > < script > SCRIPT B < /script > < p > Hello World < /p > < /html >
How to make a replacement over the webs loaded in a Webview
Java
I do know that when you make a method final in java , it can not be overridden . When a method is private , it can only be accessed by methods and members of that given class in which the method exists . So , does it mean that since the method can not be accessed it is no use trying to check if it can be overridden bec...
private final void addCode ( String code ) { //codes here ... }
ca n't I have both keywords on the same line : private final ... ( ) ?
Java
I was trying my hands on vectors and wrote a simple code to access its elements through enumeration.Working with raw types produces results as expected ( prints the elements ) . But , when I use generic type of enumerator , it gets tricky.With String as type parameter : Output : Some StringException in thread `` main '...
Vector v = new Vector ( ) ; v.add ( `` Some String '' ) ; v.add ( 10 ) ; Enumeration e = v.elements ( ) ; while ( e.hasMoreElements ( ) ) System.out.println ( e.nextElement ( ) ) ; Vector v = new Vector ( ) ; v.add ( `` Some String '' ) ; v.add ( 10 ) ; Enumeration < String > e = v.elements ( ) ; while ( e.hasMoreEleme...
I get ClassCast exception when I enumerate vector with String type parameter , but no exception is there with Integer as type parameter
Java
I have a desktop java application that uses Swing as a GUI library . There is an installer that I have to install inside this application , but it must have administrative privileges.I am usingto install the program . But it has this error when running it without administrator privilege : Is there a way to get Run as a...
Process p = Runtime.getRuntime ( ) .exec ( pathToTheExeInstaller ) ;
how to get 'Run as administrator ' in jar applications
Java
I am setting this variableThen I execute this programBut I have this strange errorI even tried using with the same resultanother test :
set srcDir = C : \Developpement\Workspaces\Eclipse\MyAuthenticationProvider\src java -DMJF=MyAuthentication.jar -Dfiles= % srcDir % weblogic.management.commo.WebLogicMBeanMaker The specified input files directory , `` % srcDir % '' , does not exist . java -DMJF=MyAuthentication.jar -Dfiles= $ srcDir weblogic.management...
Setting a Windows variable to execute a Java program
Java
How to best print 2 float numbers in scientific-notation but with same exponent ? eg : I 'd like to print numbers like this : And I would like some function to detect automatically best exponent - that is smaller number always start at first decimal digit and bigger number prints how it must with same exponent.eg : 0.1...
1.234e-6 11.234e-6 1.000e-11000.000e-1
Best way to print 2 doubles with same exponent
Java
I have been reading Effective Java , 3/E.While reading the part regarding hashcode , ( page 51 ) I noticed the book sayingA nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance on some architectures : 31 * i == ( i < < 5 ) - i . Modern VMs do this sort of op...
fun main ( ) { val num = Random.nextInt ( ) val a = num * 30 val b = num * 31 val c = num * 32 println ( `` $ a , $ b , $ c '' ) } L1 LINENUMBER 5 L1 ILOAD 0 BIPUSH 30 IMUL ISTORE 1 L2 LINENUMBER 6 L2 ILOAD 0 BIPUSH 31 IMUL ISTORE 2 L3 LINENUMBER 7 L3 ILOAD 0 BIPUSH 32 IMUL ISTORE 3 int test ( int num ) { int n = rand ...
Multiply an int by 30 , 31 , 32 - are these really optimized by the compiler ? ( effective java says so )
Java
I have the following code where I 'm creating an array and trying to store objects in it . At run time , I get an ArrayStoreException.I somehow understand that this is because of the statementWhy is this wrong ? A.getClass ( ) at runtime returns a String , so temp should be an array of strings . In that case , why is t...
import java.lang.reflect.Array ; public class GenericsArrayCreation < T > { public static < T > void Test ( T [ ] A ) { @ SuppressWarnings ( `` unchecked '' ) T [ ] temp = ( T [ ] ) Array.newInstance ( A.getClass ( ) , A.length ) ; for ( int i = 0 ; i < temp.length ; i++ ) { temp [ i ] = A [ i ] ; System.out.println ( ...
Why is this generics array creation not working as expected ?
Java
I have a character `` Unicode value is U+1F62D binary equivalent is 11111011000101101 . Now I want to convert this character to byte array . My steps1 ) As binary representation is bigger than 2 bytes I use 4 bytesXXXXXXXX XXXXXXX1 11110110 001011012 ) Now I replace all ' X ' with ' 0'00000000 00000001 11110110 0010110...
@ Test public void testUtf16With4Bytes ( ) throws Exception { assertThat ( new String ( new byte [ ] { 0,1 , -10,45 } , StandardCharsets.UTF_16BE ) , is ( `` '' ) ) ; } ava.lang.AssertionError : Expected : is `` '' but : was ``  ''
Wrong bytes from UTF-16 encoding
Java
Here I want to convert sting array values into integer array , Need to store all string values into integer array , Here is the string array :
private String [ ] aa = { `` 70 '' , '' 80 '' , '' 99 '' , '' 140 '' , '' 150 '' , '' 199 '' , '' 200 '' , '' 300 '' , `` 349 '' , '' 350 '' , '' 400 '' , '' 499 '' , '' 500 '' , '' 501 '' , '' 900 '' , '' 1000 '' , '' 1100 '' , '' 1200 '' } ;
How to convert values stored in the String array to Integer array in Java
Java
I have been testing some different ways to multiply array items with a constant.I have produced different results depending on how I loop through the array and I 'm having trouble understanding this ( I 'm fairly new to Java and still getting my head around how things are passed or referenced ) .Test 1Resulting in arra...
int [ ] array = { 1 , 2 , 3 , 4 } ; for ( int number : array ) { number *= 2 ; } { 1 , 2 , 3 , 4 } Integer [ ] array = { 1 , 2 , 3 , 4 } ; for ( Integer number : array ) { number *= 2 ; } { 1 , 2 , 3 , 4 } int [ ] array = { 1 , 2 , 3 , 4 } ; for ( int i = 0 ; i < array.length ; i ++ ) { array [ i ] *= 2 ; } { 2 , 4 , 6...
Java Array loop behaviour
Java
I want to create a regular expression in java using standard libraries that will accommodate the following sentence : Obviously the numbers can be anything though ... From 1 digit to manyAlso , I 'm not sure how to accommodate the word `` of '' but I thought maybe something along the lines of :
12 of 128 [ \d\sof\s\d ]
Regular Expression of a Specific Word
Java
Consider the following : } The out put is ALF : ARIAN has bowed to me ! ARIAN : ALF has bowed to me ! LOCK situation ... ..When Thread 1 runs , it requires a lock on the object Friend . Immediately after that Thread 2 requires lock on the second object . Now the method bow is lock by thread 1 and thus prints `` ALF : A...
public class Deadlock { static class Friend { private final String name ; public Friend ( String name ) { this.name = name ; } public String getName ( ) { return this.name ; } public synchronized void bow ( Friend bower ) { System.out.format ( `` \n % S : % S has bowed to me ! '' , this.name , bower.getName ( ) ) ; bow...
DeadLock process Which one locks first ?
Java
I have the following code , which works fine on Java 8 : But when I try to use the Java 7 compiler , I get an error : Why ? Is there some way to use such wildcards in Java 7 ?
List < Class < ? > > KEY_NAME_CLASSES = Collections.singletonList ( String.class ) ; incompatible types : java.util.List < java.lang.Class < java.lang.String > > can not be converted to java.util.List < java.lang.Class < ? > >
Java wildcard difference in 7 and 8
Java
I have a string like this -And I want the following result -All the content between the word in quotes `` and , should be deleted.How do I achieve this ? Thanks !
[ 'name ' { d763e18f-1719-480b-bcd6-8fea7bad894e } Parameter , 'class ' { 8471633e-4a54-4c86-bd2b-56d58baf2fbb } Parameter , 'id ' { 23471633e-4a54-4c86-bd2b-56d58baf2fbb } Parameter ] [ 'name ' , 'class ' , 'id ' ]
Delete the content of a string between a word and special character in java
Java
I 'm reading a lot of articles about javadoc , but still ca n't menage when the `` boilerplate '' begins . In this example : Can I perform them somehow to be less boilerplate or I should just remove them ? Why in 75 % of articles called `` best practices for Javadoc we have repetitions ? For example : Is n't it writing...
/** * Returns a list of tasks for specific user * @ param userId * @ return Selected list of tasks */List < Task > getTasksForUser ( Integer userId ) ; /** * Returns a list of tasks in chosen month and year * @ param month * @ param year * @ return selected list of tasks */List < Task > getTasks ( Integer month , Integ...
Performing javadoc comments
Java
I am following the example for the Undertow Client API . How do I add cookies to the request ?
final ClientRequest request = new ClientRequest ( ) ; request.setMethod ( new HttpString ( requestMethod ) ) ; request.getRequestHeaders ( ) .put ( Headers.TRANSFER_ENCODING , `` chunked '' ) ; connection.sendRequest ( request , new ClientCallback < ClientExchange > ( ) { @ Override public void completed ( ClientExchan...
How to add cookies to Undertow 's ClientRequest ?
Java
I have the following piece of code-This compiles fine , implying that the variable definitions are executed before the instance blocks.However , if I use the following code instead , it does not compile ( `` error : illegal forward reference '' ) .So it is not possible to use the value of 's ' on the right-hand side of...
{ s = `` Hello '' ; } String s ; { s = `` Hello '' ; String ss = s ; } String s ;
instance variable definitions and instance blocks
Java
A few days ago , I ran into a fascinating scenario that I could n't find any documentation on how or why Java lets the following happen . ( This snippet is just a simplified form of the bug . ) in the snippet above : if the bool = true , then you get the value ' 5 ' ; but if bool = false , then you get a null pointer e...
@ Test public void test ( ) { boolean bool = false ; Integer intVal = Integer.valueOf ( 5 ) ; Long longVal = null ; Long result = bool ? intVal : longVal ; System.out.println ( `` > `` + result ) ; } Long result = bool ? Long.valueOf ( intVal ) : longVal ; longVal = intVal ;
Odd Java ternary behavior when assigning value . What is Java doing behind the scenes for this to happen ?
Java
Say you have a class A and a class B extends A and a class C extends B.Is there any IDE or any sort of plug-in for any idea , where in the file C.Java , on line I can see something like ( and Class A ) for example like a tooltip or like a comment under the line ?
Class C extends B
See all super classes in Java
Java
What are the rules for the characters that can be used in Java variable names ? I have this sample code : which will not compile : So why is the Java compiler throwing an error for `` ? ( \uD834\uDD1E ) Same in ideone.com : http : //ideone.com/fnmvpG
public class Main { public static void main ( String [ ] args ) { int k = 4 ; System.out.println ( s ) ; } } javac Main.javaMain.java:3 : error : illegal character : '\udd1e ' int k = 4 ; ^1 error
Why am I not allowed to use the character in a Java source code file as a variable name ?
Java
Fast-Fail : meaning that if they detectthat the collection has changed since iteration began , they throw the uncheckedConcurrentModificationException.I have written a test example to demonsterate this : the output is : which is expected . However , when an element is removed , the exception is not thrown : Output : Wh...
String hi = `` Hi '' ; list.add ( hi ) ; list.add ( `` Buy '' ) ; System.out.println ( `` list before : `` + list ) ; for ( Iterator < String > iterator = list.iterator ( ) ; iterator.hasNext ( ) ; ) { String string = iterator.next ( ) ; list.add ( `` Good '' ) ; } list before : [ Hi , Buy ] Exception in thread `` main...
Fast-fail - Exception only happens when adding an Element not when removing
Java
I am trying to write a code that computes the following for a given integer n : This is the code I have written so far : However , it always outputs : What is the problem and how can I fix it ? Thank you
1/1 + 1/2 + 1/3 ... + 1/n public class RecursiveSum { public static double Sumto ( int n ) { if ( n == 0 ) { return 0.0 ; } else if ( n > 0 ) { return 1/n + 1/Sumto ( n - 1 ) ; } else { throw new IllegalArgumentException ( `` Please provide positive integers '' ) ; } } public static void main ( String [ ] args ) { Syst...
Arithmetic Recursion
Java
Here I 'm working with a Java to C # sample app translation that involves cryptography ( AES and RSA and so on ... ) At some point in Java code ( the one that actually works and being translated to C # ) , I 've found this piece of code : After some googling ( here ) , I 've seen that this is a common behaviour mainly ...
for ( i = i ; i < size ; i++ ) { encodedArr [ j ] = ( byte ) ( data [ i ] & 0x00FF ) ; j++ ; } // where data variable is a char [ ] and encodedArr is a byte [ ]
Why the need of a bitwise `` and '' for some char to byte conversions in Java ?
Java
I have two very large ArrayList , each containing millions of data . I want to filter out data from List1 which is not present in List2 and / or vice-versa.I 've tried Apache CollectionUtils , Java 8 stream API without any success . Java 8 parallel streaming is consuming all the CPU and CollectionUtils keeps on compari...
public DataVO { private String id ; private String value ; ... // getters / setters @ Override public int hashCode ( ) { final int prime = 31 ; int result = 1 ; result = ( prime * result ) + ( ( id == null ) ? 0 : id.hashCode ( ) ) ; return result ; } @ Override public boolean equals ( final Object obj ) { ... ... fina...
Compare large lists and extract missing data
Java
I have written a same program in two different way and both are giving me different output . i am not able to understand why.please correct me.In first program i am getting this outputOriginal : UmeshChanged : XmeshAnd in second program i am getting this output.Original : UmeshChanged : UmeshProgram-1 Program-2
import java.lang.reflect.Field ; public class SomeClass { public static void main ( final String [ ] args ) throws Throwable { final String s = `` Umesh '' ; changeString ( s ) ; } // We need a method so the compiler wo n't inline `` s '' : static void changeString ( final String s ) throws Throwable { System.out.print...
Is it possible to re-reference any final String variable . Please clear me what is happening in given program
Java
After reading a bunch of questions / articles on this topic there is still one thing unclear to me.From what I understand ( and please correct me if I 'm wrong ) is that the value of a variable can be cached locally to a thread so if one thread updates the value of that variable this change may not be visible to anothe...
volatile int x ; ... int y = x ; final Object lock = new Object ( ) ; int x ; ... synchronized ( lock ) { int y = x ; }
Concerning volatile and synchronized
Java
For example , if I have a function likeMy classmate told me , we should use List as return type because return type should be as broad as possible . His reason here is we can change to return a LinkedList or another type later if we currently return an ArrayList . It increases the flexibility.But the function parameter...
public List < E > sort ( ArrayList < E > list ) { ... } public List < E > sort ( ArrayList < E > list ) { ... } public < E > SuperClass < E > sort ( SubClass < E > object ) { ... }
How to define Java function 's return type and parameters , using subclass or superclass ?
Java
I have a use case where the input is set of parameters ( say A , B , C , D ) and data ( say XYZ ) . Based on the parameters ( A , B , C , D ) i have to process the data ( XYZ ) and respond back . The processing logic can be unique or common based on parameters ( say do something # 1 only when A , do something # 2 when ...
if ( A == A1 ) { //dosomething-A1 if ( B == B1 ) { //dosomething-B1 if ( C == C2 ) { //dosomething-C2 } } else if ( B == B2 ) { //dosomething-B2 } if ( C == C2 ) { //dosomething-C2 if ( D == D1 ) { //dosomething-D1 } else if ( D == D3 ) { //dosomething-D3 } } } else if ( A == A2 ) { //dosomething-A2 ... } else if ( A =...
Which design pattern to use for my use case ?