lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
How do I do to overwrite a method with the one i just selected ? For example : First I typebut then , I reminded that the method was another one , and the cursor was after the word some and before Method , when I press Ctrl+Space again , it shows up some methods , when i hit enter , my method now is something like this...
SomeClass.someMethod ( ) : SomeClass.someOneElsesMethod ( ) someMethod ( ) ;
Ctrl+Space overwrite method with the one selected
Java
I was trying to replicate a bug by using the same instance of SimpleDateFormat across multiple threads . However I got stuck with another problem and did not find any answers to it . This simple code block replicates the issues I am seeing.The results of this operations under java 7 ( 1.7_0_21 ) is as follows As you ca...
DateFormat d1 = new SimpleDateFormat ( `` ddMMyyyy '' ) ; DateFormat d2 = new SimpleDateFormat ( `` ddMMyyyy '' ) ; DateFormat d3 = new SimpleDateFormat ( `` ddMMyy '' ) ; System.out.println ( `` d1 = `` + d1 ) ; System.out.println ( `` d2 = `` + d2 ) ; System.out.println ( `` d3 = `` + d3 ) ; d1 = java.text.SimpleDate...
new SimpleDateFormat always returns same reference for a given dateFormat
Java
Do you need to call remove on a thread local if you are not deploying in a server environment , even if the app uses a cached thread pool ?
public static ThreadLocal < Integer > i = new ThreadLocal < Integer > ( ) { { public Integer initialValue ( ) { return 3 ; } } ;
thread local remove method
Java
See Update below to show potential workaroundOur application consumes 2 topics as KTables , performs a left join , and outputs to a topic . During testing , we found that this works as expected when our output topic has only 1 partition . When we increase the number of partitions , we notice that the number of messages...
@ Beanpublic BiFunction < KTable < MyKey , MyValue > , KTable < MyOtherKey , MyOtherValue > , KStream < MyKey , MyEnrichedValue > > process ( ) { return ( topicOne , topicTwo ) - > topicOne .leftJoin ( topicTwo , value - > MyOtherKey.newBuilder ( ) .setFieldA ( value.getFieldA ( ) ) .setFieldB ( value.getFieldB ( ) ) ....
KTable-KTable foreign-key join not producing all messages when topics have more than one partition
Java
I am new to java and trying to understand the following . The length of the arrays is not same . The code still executes without any errors . I dont understand why . If someone could clarify .
public class Practice { public static void main ( String [ ] args ) { int [ ] [ ] a = { { 1,2,3 } , { 4,5 } } ; a [ 0 ] = a [ 1 ] ; } }
Why does the following code compile without error ?
Java
I have searched and searched and this is destroying me . I have this : The emailFormUrl returns the URL correctly but the parameters have been stripped.Which speaks of : For some reason , the id is being stripped , this leaves me with a validation error and does n't complete the action that I require . As I am aware we...
< s : form method= '' post '' action= '' % { methodOne } '' cssClass= '' buttons '' > public String methodOne ( ) { return anotherClass.methodTwo ( id ) ; } public static String methodTwo ( String id ) { return fastEncode ( `` '' , `` longurl/view.jsp '' , new ParameterPairing ( `` id '' , id ) ) ; }
s : form tag action parameters being removed
Java
Help me optimize the algorithm . I have a heap in the array.Each number in the array indicates a parent . Root is -1.I need to find the depth of heap.Example : Array is 4 -1 4 1 1The answer is 3.It 's my codeWhere pos - position of root.I also solved this problem with recursion . But tests give me `` Time limit exceede...
static int findMax ( int [ ] mas ) { int a [ ] = new int [ mas.length ] ; a [ pos ] = 1 ; int max = 0 ; for ( int j = 0 ; j < mas.length ; j++ ) { for ( int i = 0 ; i < a.length ; i++ ) { if ( a [ i ] == 0 & & a [ mas [ i ] ] ! = 0 ) { a [ i ] = a [ mas [ i ] ] + 1 ; if ( a [ i ] > max ) max = a [ i ] ; } } } return ma...
Find heap depth faster than O ( n^2 )
Java
Take a look at this code ( from here ) There are two parallel inheritance trees , for a parent class and an associated class . The problem is with line 23 : ( ( AssocAConcrete ) myA ) .salute ( ) ; It is a pain and I have that kind of thing all over my code . Even though that line is part of the concrete implementation...
abstract class EntityA { AssocA myA ; abstract void meet ( ) ; } abstract class AssocA { int something ; abstract void greet ( ) ; } class AssocAConcrete extends AssocA { void greet ( ) { System.out.println ( `` hello '' ) ; } void salute ( ) { System.out.println ( `` I am saluting . '' ) } } class EntityAConcrete exte...
Inheritance and casting : is this good java ?
Java
I 'm currently using Roaster to generate interfaces , but my interface has generic types bound to it.Here 's what I was trying to generate them to begin with : But the above results in generated code that looks ( something ) like this : What I actually want is for the generic to be bound to JpaRepository . How do I acc...
String entityName = `` SimpleEntity '' ; JavaInterfaceSource repository = Roaster.create ( JavaInterfaceSource.class ) .setName ( entityName + `` Repository '' ) ; JavaInterfaceSource jpaInterface = repository.addInterface ( JpaRepository.class ) ; jpaInterface.addTypeVariable ( entityName ) ; jpaInterface.addTypeVaria...
Using Roaster , how can I generate an interface with a specific generic type ( or types ) ?
Java
I have a class that contains a cache ( Set ) , and the cache is built on instantiation . I 'm confused which exception/error should I throw if building cache fail ( can not connect to database or some ) .One exception comes in my mind is ExceptionInInitializerError , but javadoc says it is thrown on initialize static m...
class Provider { public Provider ( ) { buildCache ( ) ; } private void buildCache ( ) { try { this.cache = getDataFromDb ( ) ; } catch ( Exception ex ) { throw new ? ? ? } } }
Which exception should I throw when building cache fail ?
Java
I am looking for a clean and safe way to ensure tha a field of a class will never be set to null . I would like the field value to be set once in the class constructor and never modified later . I think that he readonly keyword in C # allows this . Is there a way to do the same in Java ?
class foo { private Object bar ; public foo ( Object pBar ) { if ( pBar == null ) { bar = new Object ( ) ; } else { bar = pBar } } // I DO NOT WANT ANYONE TO MODIFY THE VALUE OF bar OUT OF THE CONSTRUCTOR }
How to ensure that a field will never be null in a Java class
Java
Long story short : Why is the following not possible in Java ? Note : I do n't have any specific use case right now , rather I am just trying to understand why this is not allowed.At first I thought because the compiler can not assert if A can accept generics parameter because after compiling A , due to type erasure th...
public class Test < A < B > > { } // A and B both being generic parameters . public class com.Test < T > { public com.Test ( ) ; Code : 0 : aload_0 1 : invokespecial # 12 // Method java/lang/Object . `` < init > '' : ( ) V 4 : return }
Why is second level generics not possible in Java
Java
I 've been staring at the screen the last 5 minutes and ca n't seem to figure out what I 'm doing wrong : I 'm surprised why the String [ ] can not be converted to List < String > to initialize the HashSet < String > with it.I 'm getting the build error : What 's wrong with my assignment ?
class Example { private final Set < String > values ; public Example ( String ... values ) { values = new HashSet < String > ( Arrays.asList ( values ) ) ; } } incompatible types : java.util.HashSet < java.lang.String > can not be converted to java.lang.String [ ]
Can not create Set from String array
Java
From the Matrix Chain Multiplication page on Wikipedia , there is this fragment of Java code : Is n't m = new int [ n ] [ n ] ; already allocating memory space of size n in both its dimensions so this step in the loop m [ i ] = new int [ n ] ; is actually redundant because all it does is reallocate the second dimension...
public void matrixChainOrder ( int [ ] p ) { int n = p.length - 1 ; m = new int [ n ] [ n ] ; s = new int [ n ] [ n ] ; for ( int i = 0 ; i < n ; i++ ) { m [ i ] = new int [ n ] ; m [ i ] [ i ] = 0 ; s [ i ] = new int [ n ] ; } ...
Is this a redundant allocation of memory space in a multi dimensional array ?
Java
I came across the following code , a simple example of adding elements to ListI expected it to throw an ClassCastException , but rather it wrote this to the console which looks weird . When i tried : I got a compile time error . I would be grateful if someone could explain how the String objects are added to the ArrayL...
List list = new ArrayList < Integer > ( ) ; ListIterator < Integer > litr = null ; list.add ( `` A '' ) ; list.add ( `` 1 '' ) ; list.add ( 5 ) ; litr = list.listIterator ( ) ; while ( litr.hasNext ( ) ) { System.out.println ( `` UIterating `` + litr.next ( ) ) ; } A15 List < Integer > list = new ArrayList < Integer > ...
Does ArrayList < Integer > allow adding of String ?
Java
I 'm working on an assignment dealing with class inheritance and have everything done and working properly except for a string format method . The output of the program should look like this : but it is printing like this : The problem is that in the output , `` Earnings : $ 450.00 '' is printing before `` with Base Sa...
Base Salary Plus Commissioned Employee : Sue Smith with ssn : 222-22-2222Gross Sales : $ 3000.00 Commission Rate : 0.05 with Base Salary : $ 300.00 Earnings : $ 450.00 Base Salary Plus Commissioned Employee : Sue Smith with ssn : 222-22-2222Gross Sales : $ 3000.00 Commission Rate : 0.05 Earnings : $ 450.00with Base Sal...
Java : Is it possible to exclude taking something from a super class
Java
I got simple code , maybe the problem relies on the given format string or on the timezone . So here is the code : The result is : Thu Jan 01 00:00:00 EET 1970-10800000 -- > should be 0 as we give 00:00 hours in and the other time elements remain default.//EditYes the problem is with timezone to fix this use df.setTime...
public static void main ( String [ ] args ) { SimpleDateFormat df = new SimpleDateFormat ( `` HH : mm '' ) ; try { Date added = df.parse ( `` 00:00 '' ) ; System.out.println ( added ) ; System.out.println ( added.getTime ( ) ) ; } catch ( ParseException e ) { // TODO Auto-generated catch block e.printStackTrace ( ) ; }...
Date parsing from string to long gives wrong result
Java
Possible Duplicate : Java - boolean primitive type - size I 've designed this program to calculate the size of a boolean in Java.When I run the program , it says that the size is 1.0000016 bytes . Now , the Oracle Java documentation says that the size of a boolean is `` not defined '' . [ See link ] .Why is this so ? A...
public class BooleanSizeTest { /** * This method attempts to calculate the size of a boolean . */ public static void main ( String [ ] args ) { System.gc ( ) ; //Request garbage collection so that any arbitrary objects are removed . long a1 , a2 , a3 ; //The variables to hold the free memory at different times . Runtim...
Program to calculate the size of a boolean variable
Java
Here is a java snippet : And It behave different according to different JDKsin Oracle JDK 1.7 output is : in OpenJDK 1.6 output is also : but in Oracle JDK 1.6 output is : as the JavaDoc for this String # intern method indicates the output : should be expected , but neither three JDKs produce this . and Why Oracle JDK1...
public class TestIntern { public static void main ( String [ ] argvs ) { String s1 = new StringBuilder ( `` ja '' ) .append ( `` va '' ) .toString ( ) ; String s2 = new StringBuilder ( `` go '' ) .append ( `` lang '' ) .toString ( ) ; System.out.println ( s1 == s1.intern ( ) ) ; System.out.println ( s2 == s2.intern ( )...
Why String.intern ( ) behave differently in Oracle JDK 1.7 ?
Java
I am trying to send some work from IntentService to BroadcastReceiver by using .putExtra ( ) and sendBroadcast ( ) , so I have own class called `` Message '' , which extends HashMap < String , String > and implements Serializable.And I am sending it like this : And receiving like this : But here I always get this : `` ...
public class Message extends HashMap < String , String > implements Serializable { public MessageID ID ; public int Encode ( byte [ ] buff , int off ) ; public int Decode ( byte [ ] buff , int off ) ; // ... } public static void ProcessMessage ( Message msg ) { Intent broadcastIntent = new Intent ( ) ; broadcastIntent....
Casting Serilizable to derivation of HashMap
Java
I recently learned that there are Class representations for the primitive types in the JVM . For example , int.class , double.class , and even a void.class.What I do n't understand is why these are there . They do n't seem to serve any functional role . Using reflection , I searched through the classes , and they have ...
int a = 3 ; int.class.isInstance ( a ) ;
What is the use/purpose of primitive type classes ?
Java
I am using the org-netbeans-lib-cvsclient.jar to execute various cvs commands in a java class that communicates with CVS . I am able to do a cvs checkout command , add , commit , etc . However , I need to find out which command is equivalent to the cvs ls -R command.Here is the code I wrote that allows to do a cvs chec...
CheckoutCommand command = new CheckoutCommand ( ) ; command.setBuilder ( null ) ; command.setRecursive ( true ) ; command.setModule ( module ) ; if ( revision ! =null ) { command.setCheckoutByRevision ( revision ) ; } command.setPruneDirectories ( true ) ; command.setUseHeadIfNotFound ( true ) ; executeCommand ( comman...
Is it possible to checkout only the directory structure in cvsclient in Java ?
Java
Hi i am attempting to discover why my program 's usually run slower than i want them so thank you in advance for your help ! I have for example a piece of code that i would like some insight intoin Line # 2 . I create a new Object . This will happen thousands of times in my program . Do i specifically have to null the ...
1. while ( conditionIsTrue ) { 2 . Object object = new Object ( ) ; 3 . } 1 . Object object = null ; 2. while ( conditionIsTrue ) { 3. object = new Object ( ) ; 4 . }
Must you set references to null for garbage collection to work
Java
I 'm trying to write a program that in the Main class one can initiate unknown amount of new threads.Each thread in turn should call to a Singleton Copier class which should call a file transfer action.My goal is , regardless the amount of threads requests , is to limit the number of concurrent transfers to 2 transfers...
public class Copier { private static final int POOL_SIZE = 2 ; private static volatile Copier instance = null ; private static Semaphore semaphore ; private Copier ( ) { } public static Copier getInstance ( ) { if ( instance == null ) { synchronized ( Copier.class ) { if ( instance == null ) { instance = new Copier ( )...
Semaphore - why my threads are running one after the other and not in concurrent ?
Java
I found out , that for example this line has a very very long execution time : If I reduce the amount of dots at the start of the String the execution time gets lower ( seems like it 's exponential ) . Here is the suspended thread 's stack trace : Why does this happen ?
System.out.println ( `` .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. ... . .. .. '' .matches ( `` ( ? i ) ( ? : . * ) ? \\W ? ( [ a-z0-9-_\\. ] + ( ( ? : * ) \\. ( ? : * ) ) + ( ? : DE ) ) ( ? : [ 0-9 ] { 1,5 } ) ? `` ) ) ; [ Repeating text ] ... Pattern $ GroupTail.match ( Matcher , int , CharSequence )...
Why does this regex take a long time to execute ?
Java
Possible Duplicate : NullPointerException through auto-boxing-behavior of Java ternary operator The following code uses simple conditional operators.This code compiles fine . All the expressions ultimately attempt to assign null to Integer type variables exp1 , exp2 and exp3 respectively.The first two cases do n't thro...
public class Main { public static void main ( String [ ] args ) { Integer exp1 = true ? null : 5 ; Integer exp2 = true ? null : true ? null : 50 ; System.out.println ( `` exp1 = `` +exp1+ '' exp2 = `` +exp2 ) ; Integer exp3 = false ? 5 : true ? null : 50 ; //Causes the NullPointerException to be thrown . System.out.pri...
Conditional operators in Java throw an unexpected NullPointerException
Java
Please help me understand this code . I am new to java .
// C.javaclass C { public static void main ( String arg [ ] ) { System.out.println ( `` A '' +new C ( ) ) ; } public String toString ( ) { System.out.print ( `` B '' ) ; return `` C '' ; } } // output : // BAC
Java - Why the following code print out `` BAC '' , instead of `` ABC '' ?
Java
I learned that if I have two classes : I can cast from a List < A > to List < B > by doing this : This would generate a warning , but it works . However , I read that this is not recommended . Is it true in that case ? If I know it 's returning me a List < B > , why making this cast is such a bad practice ? Please note...
public class A { } public class B extends A { } List < B > list = ( List < B > ) ( List < ? > ) collectionOfListA ;
Why is casting from List < A > to List < B > not recommended ?
Java
Which of these is more performant , or ( if equivalent ) which one reads better ? I 'm trying to match everything inside a pair of parentheses.To me , the second reads better but uses the possibly confusing reluctant quantifier , and I 'm unsure if that causes a performance loss.EDITDo n't miss the answer which shows t...
Pattern p1 = Pattern.compile ( `` \\ ( [ ^ ) ] *\\ ) '' ) ; Pattern p2 = Pattern.compile ( `` \\ ( . * ? \\ ) '' ) ; Pattern p3 = Pattern.compile ( `` \\ ( [ ^ ) ] *+\\ ) '' ) ;
Java Regex Performance : Reluctant Quantifier or Character Class ?
Java
In RandomAccess marker interface description it is written : In collection class synchronisedList method there is a check for RandomAccess & if success create SynchronizedRandomAccessList object but their also no details regarding algorithm . When does this algorithm apply and where ( is it a native code ) ?
* < p > The best algorithms for manipulating random access lists ( such as * < tt > ArrayList < /tt > ) can produce quadratic behavior when applied to * sequential access lists ( such as < tt > LinkedList < /tt > ) . Generic list * algorithms are encouraged to check whether the given list is an * < tt > instanceof < /t...
When does algorithms for manipulating random access lists is applied ?
Java
I 'm working on a project using rxjava1 and I have an Observable chain that occasionally will contain thousands of observables merged or concatted together . When this happens a StackOverflow exception will occur and we will get something like this : And the stacktrace will continue for hundreds of lines . The only rel...
java.lang.StackOverflowError at java.util.HashMap.putVal ( HashMap.java:631 ) at java.util.HashMap.put ( HashMap.java:612 ) at rx.internal.operators.OnSubscribeToMap $ ToMapSubscriber.onNext ( OnSubscribeToMap.java:127 ) at rx.internal.operators.OnSubscribeFilter $ FilterSubscriber.onNext ( OnSubscribeFilter.java:76 ) ...
RxJava1 StackOverflow Exception With Too Many Observables
Java
I have a class contains 10 methods which are doing almost the same things apart from one key event . Two examples are given below : As you can see from the above methods , they are similar apart from calling different methods provided by requestBuilder . The rest 8 are similar too . There is a lot duplicated code here ...
Public String ATypeOperation ( String pin , String amount ) { doSomething ( ) ; doMoreStuff ( ) ; requestBuilder.buildATypeRequest ( pin , amount ) ; doAfterStuff ( ) ; } Public String BTypeOperation ( String name , String sex , String age ) { doSomething ( ) ; doMoreStuff ( ) ; requestBuilder.buildBTypeRequest ( name ...
remove duplication
Java
I 'm reading HTTP request from socket input streamIt 's working but findbugs gives the following bug : Dereference of the result of readLine ( ) without nullcheck . Request ends with `` '' not eof . So how can I check null value here ?
StringBuilder request = new StringBuilder ( ) ; String inputLine ; while ( ! ( inputLine = in.readLine ( ) ) .equals ( `` '' ) ) { request.append ( inputLine + `` \r\n '' ) ; }
Reading http request from socket with null check java
Java
I know that java compiler can actually reorder code instructions . But can java reorder function calls ? For example :
... //these lines may be reordereda=7 ; b=5 ; ... //but what about this ? callOne ( ) ; callTwo ( ) ;
Could a Java compiler reorder function calls ?
Java
Question : Is it possible to access elements annotated with a @ Target ( ElementType.TYPE_USE ) annotation via an annotation processor ? Is it possible to access the annotated type bounds via an annotation processor ? Links to related documentation I missed are highly appreciated.Context : The annotation : An example c...
@ Target ( ElementType.TYPE_USE ) @ Retention ( RetentionPolicy.SOURCE ) public @ interface TypeUseAnno { } public class SomeClass extends HashMap < @ TypeUseAnno String , String > { } @ SupportedSourceVersion ( SourceVersion.RELEASE_8 ) @ SupportedAnnotationTypes ( `` base.annotations.TypeUseAnno '' ) public class Pro...
How to access TypeUse annotation via AnnotationProcessor
Java
This prints Number Class Type.I understand the rules of wrapper class method overloading : If you are passing a primitive data type as an argument to the methodcall , the compiler first checks for a method definition which takes thesame data type as an argument.If such a method does not exist , then it checks for a met...
public class WrapperClasses { void overloadedMethod ( Number N ) { System.out.println ( `` Number Class Type '' ) ; } void overloadedMethod ( Double D ) { System.out.println ( `` Double Wrapper Class Type '' ) ; } void overloadedMethod ( Long L ) { System.out.println ( `` Long Wrapper Class Type '' ) ; } public static ...
Why does n't my primitive-type-argumented method override the wrapper-type-argumented super class method ?
Java
I want to compile my code down to Java version 1.0.I managed to compile down to 1.1 : But the target option does not seem to accept 1.0 : How do I target JDK 1.0 ? I want my .class and .jar file to work as many systems as possible , including very old ones , including JDK 1.0 . ( I do n't have access to a system runnin...
$ java -versionopenjdk version `` 1.8.0_181 '' OpenJDK Runtime Environment ( build 1.8.0_181-8u181-b13-2~deb9u1-b13 ) OpenJDK 64-Bit Server VM ( build 25.181-b13 , mixed mode ) $ javac -target 1.2 -source 1.2 MyClass.java ( works with some warnings ) $ javac -target 1.1 -source 1.2 MyClass.java ( works with some warnin...
How to compile to target Java 1.0
Java
I found cache mechanism is improved in jdk 1.6 or above jdk versions.In jdk 1.5 the cache array in Integer is a fixed one , seeIn jdk 1.6 or above version , an method named getAndRemoveCacheProperties and an IntegerCache.high property have been added to Integer class , like , // value of java.lang.Integer.IntegerCache....
static final Integer cache [ ] = new Integer [ - ( -128 ) + 127 + 1 ] ; private static String integerCacheHighPropValue ; static void getAndRemoveCacheProperties ( ) { if ( ! sun.misc.VM.isBooted ( ) ) { Properties props = System.getProperties ( ) ; integerCacheHighPropValue = ( String ) props.remove ( `` java.lang.Int...
What is the advantage of cache mechanism change of Integer class in JDK 1.6 or above ?
Java
I 'm following the spring tutorial.In section `` 3.2 . Add some classes for business logic '' an interface ProductManager is created : Then a SimpleProductManager implementation class is created : The implementation class adds an extra method setProducts ( ) . Should the interface ProductManager not also have a setProd...
package springapp.service ; import java.io.Serializable ; import java.util.List ; import springapp.domain.Product ; public interface ProductManager extends Serializable { public void increasePrice ( int percentage ) ; public List < Product > getProducts ( ) ; } package springapp.service ; import java.util.List ; import...
Bad practice in this spring tutorial ?
Java
My question may be basic , but I am wondering how the pipe operator works in the following contexts in Android : We can set multiple input types in layout : We can set multiple flags to an intent as follows : Also we can set some properties as follows : There are multiple instances where we can see such examples in And...
android : inputType = `` textAutoCorrect|textAutoComplete '' intent.setFlags ( Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_ACTIVITY_CLEAR_TOP ) ; tvHide.setPaintFlags ( tvHide.getPaintFlags ( ) | Paint.UNDERLINE_TEXT_FLAG ) ;
How does the pipe ( | ) operator work in Android while setting some properties ?
Java
We have a class in our codebase currently that uses the synchronized keyword at the method level to ensure data consistency in multithreaded operations . It looks something like this : The nice thing about this is that anyone using the class gets the synchronization for free . When you create an instance of Foo , you d...
public class Foo { public synchronized void abc ( ) { ... } public synchronized void def ( ) { ... } //etc . } Foo foo = new Foo ( ) ; //this got created somewhere//somewhere else entirelysynchronized ( foo ) { //do operation on foo foo.doStuff ( ) ; foo.doOtherStuff ( ) ; } @ EnsureSynchronizedpublic class Foo { //etc...
Is there any compile-time mechanism in Java to attempt to ensure that use of a particular class is always synchronized ?
Java
I 'm examining a source code written by someone else . I 've encountered something like this : What does this expression object._ ( `` a string here '' ) mean ?
x = new MyObject ( ) ; x._ ( `` somestring '' )
What does object._ ( `` a string here '' ) mean ?
Java
Looking at the JDK source code for LinkedHashMap , I noticed that this class is declared as : why the redundant `` implements Map < K , V > '' ( since HashMap already implements Map ) ? I can not imagine this is a typo ... Thanks .
public class LinkedHashMap < K , V > extends HashMap < K , V > implements Map < K , V > { ...
LinkedHashMap signature
Java
This I read from the threads : :shared description : By default , variables are private to each thread , and each newly created thread gets a private copy of each existing variable . This module allows you to share variables across different threads ... ( more ) Let 's say I have a shared variable like this : This mean...
my $ var : shared ; $ var = 10 ; $ var = 11 ;
Perl shared variables atomicity and visibility
Java
I have these entities : Now , this statement inside Room ... ... will cause that entire Player entity to be fetched from the database . However , I just need its primary key , id , which it should already have ( otherwise how can it fetch the data ? ) .How can I access the lazy Player proxy 's id without triggering dat...
@ Entitypublic class Room { @ ManyToOne ( optional=true , fetch=FetchType.LAZY ) private Player player1 ; ... } @ Entitypublic class Player { @ Id @ Column ( updatable=false ) private long id ; public long getId ( ) { return id ; } ... } player1.getId ( ) ;
Hibernate loading a lazy proxy , but I only need the PK
Java
While investigating a stack trace discrepancy when composing another answer , I came across a behavior I do not understand . Consider the following test program ( this is as far down as I could narrow it ) : Lines 11 and 13 are labelled in the above snippet and it can be run on ideone . The output of that program is : ...
interface TestInterface < U > { void test ( U u ) ; } static class Test < T extends Test < T > > implements TestInterface < T > { // line 11 @ Override public void test ( T t ) { throw new RuntimeException ( `` My exception '' ) ; // line 13 } } static class TestA extends Test < TestA > { } static class TestB extends T...
Mysterious line in stack trace
Java
Part of a Java program I 'm making asks the user their home country . Another part uses a switch statement , and I get an error . The error is : The operator || is undefined for the argument type ( s ) java.lang.String , java.lang.String . Here 's the method where the problem occurs : How does one use & & and || in a J...
public static String getCountryMessage ( String countryName ) { switch ( countryName ) { case `` USA '' : return `` Hello , `` ; case `` England '' || `` UK '' : return `` Hallo , `` ; case `` Spain '' : return `` Hola , `` ; case `` France '' : return `` Bonjour , `` ; case `` Germany '' : return `` Guten tag , `` ; d...
Using `` || '' in switch statements in java
Java
I 'm using ph-schematron , a Java library that validates XML documents via ISO Schematron : This library provides 2 ways of XML document validation : Validation via XSLTValidation via Pure SchematronI would love to use the second type , but my Schematron files contain XSLT functions so we MUST use the validation using ...
< xsl : when test= '' count ( hl7 : confidentialityCode [ concat ( @ code , @ codeSystem ) =doc ( 'include/voc-1.3.6.1.4.1.12559.11.10.1.3.1.42.31-DYNAMIC.xml ' ) //valueSet [ 1 ] /conceptList/concept/concat ( @ code , @ codeSystem ) or @ nullFlavor ] ) > =1 '' / > java.io.FileNotFoundException : C : \LocalData\Develop...
Resolving relative paths when using ph-schematron
Java
I am wondering about JDK9 modules . Say you have the following 3 packages : Classes in package product.impl_a and product.impl_b can only be accessed by classes in package product . The user should only use classes from product package . You can imagine that passing certain flags or properties will decide whether impl_...
com.company.productcom.company.product.impl_acom.company.product.impl_b
How will JDK9 modules help for 'package-scoped sub-packages ' ?
Java
I know that you can change the position of a circle in an animation like this ( see also here ) : But is there also a possibility ( this means a Property ) to change the points of a polygon in an animation ? And if not : Which other possibilities do I have to morph a polygon in an animation using JavaFX ?
timeline.getKeyFrames ( ) .addAll ( new KeyFrame ( Duration.ZERO , // set start position at 0 new KeyValue ( circle.translateXProperty ( ) , random ( ) * 800 ) , new KeyValue ( circle.translateYProperty ( ) , random ( ) * 600 ) ) , new KeyFrame ( new Duration ( 40000 ) , // set end position at 40s new KeyValue ( circle...
JavaFX : How can I change the points of a polygon in an animation ?
Java
What classes do you use to make string placeholders work ?
String template = `` You have % 1 tickets for % d '' , Brr object = new Brr ( template , { new Integer ( 1 ) , new Date ( ) } ) ; object.print ( ) ;
What classes do you use to make string templates ?
Java
Possible Duplicate : intern ( ) behaving differently in Java 6 and Java 7 While doing example for this questionI noticed a strange behaviour of intern ( ) method when I call intern ( ) method on String thereafter I can use == operator for the Original String.JavaDoc of intern ( ) method : Returns a canonical representa...
import java.util.Scanner ; public class Test { public static void main ( String [ ] args ) { Scanner user_input = new Scanner ( System.in ) ; String username ; System.out.print ( `` username : `` ) ; username = user_input.next ( ) ; // Even if I do not assign returned string for comparison still it compares // okay els...
Does String.intern ( ) change reference of Original String JDK7
Java
I solve algorithmic problems on codeforces and I tried pushing the same solution using java 7 and java 8 and to my surprise using java 8 I got much worse solution.On the last test : Java 7 : time : 373 ms. , memory : 112 KBjava 8 : time : 623 ms. , memory : 3664 KBMy codeWhy is that ?
public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; int n = in.nextInt ( ) ; int m = in.nextInt ( ) ; List < Integer > list1 = new ArrayList < > ( n ) ; List < Integer > list2 = new ArrayList < > ( m ) ; for ( int i=0 ; i < n ; i++ ) { list1.add ( in.nextInt ( ) ) ; } for ( int i = 0 ...
Java 8 bad performance , sorting
Java
I have some text encrypted and stored in a db using PBE AES_256 . This was initially done using java 1.8.0_65 . After upgrading to latest java , I can no longer decrypt these fields . I have pinpointed the incompatibility to 1.8.0_71 . The release notes state the following : Problem with PBE algorithms using AES crypto...
SecretKey keyFromPassword = SecretKeyFactory.getInstance ( algorithm ) .generateSecret ( new PBEKeySpec ( password.toCharArray ( ) ) ) ; Cipher cipher = Cipher.getInstance ( algorithm ) ; cipher.init ( Cipher.ENCRYPT_MODE , keyFromPassword , new PBEParameterSpec ( salt , iterations , new IvParameterSpec ( iv ) ) ) ; IO...
PBE AES_256 encryption incompatible between java 8 u65 and u71
Java
In javax.annotation.processing package there is a interface Processor in which there is a function : The Java API AbstractProcessor implements above interface . Now I created my own processor class : My questions : The API doc tells me the annotations in the process function are the the annotation types requested to be...
/** * Processes a set of annotation types on type elements * originating from the prior round and returns whether or not * these annotation types are claimed by this processor . If { @ code * true } is returned , the annotation types are claimed and subsequent * processors will not be asked to process them ; if { @ cod...
About the parameter defined in process ( ... ) method of Processor interface
Java
I 'm writing a program that displays flight information as seen bellow : The problem I have is when using the method : It does n't execute for some reason when normally running , but when I step though the program using the debugger everything executes fine and I get a meaningful output ( not very well formatted , but ...
package d.airlineData.engine ; import java.time.Duration ; import java.time.LocalTime ; import java.util.ArrayList ; import java.util.HashMap ; import java.util.HashSet ; import java.util.Iterator ; import java.util.Map.Entry ; import a.airlineData.exceptions.NoFlightsException ; import c.airlineData.exceptions.NoAirpo...
program works when stepping through but does n't when running
Java
I am in process of migrating a java project from weblogic 8.1 to weblogic 12c.As per oracle document i have converted below things.After all above changes did generate war file and deployed in weblogic 12c server which throws error like belowCode :
1 . Servicegen converted to jwsc task 2. deployment descriptor has been modified 3 . Below annotations added in service implementation file @ WebService @ SoapBinding @ SoapMessageHandler Unable to invoke annotation processor < BEA-160228 > App merge failed your applicationweblogic.utils.compiler.ToolFailureException :...
Unable to invoke annotation processor - while deploying in Weblogic 12.2.1.2.0
Java
Here is my sample code . The query is encoded to UTF-8 : After I run this example I get the following exception : char=324 means decoded ń from queryWhen I read stack trace I found jdk.incubator.http.Stream < T > this method in the class : In this method uri.getQuery ( ) is used which gives us the decoded query and cau...
HttpRequest request = HttpRequest.newBuilder ( ) .header ( `` content-type '' , `` application/json ; charset=UTF-8 '' ) .uri ( URI.create ( `` http : //localhost:8080/test ? param1=test % C5 % 84 '' ) ) .GET ( ) .build ( ) ; HttpClient.newBuilder ( ) .version ( HttpClient.Version.HTTP_2 ) .build ( ) .send ( request , ...
Java 9 HttpClient exception when using certain characters in URL query parameters
Java
How do I use Collectors in order to convert a list of DAOs , to a Map < String , List < Pojo > > daoList looks something like this : I want to groupBy 'team ' attribute and have a list for each team , as follows : Pojo looks like this : This is how I 'm trying to do that , obviously the wrong way :
[ 0 ] : id = `` 34234 '' , team = `` gools '' , name = `` bob '' , type = `` old '' [ 1 ] : id = `` 23423 '' , team = `` fool '' , name = `` sam '' , type = `` new '' [ 2 ] : id = `` 34342 '' , team = `` gools '' , name = `` dan '' , type = `` new '' `` gools '' : [ `` id '' : 34234 , `` name '' : `` bob '' , `` type '...
Use Collectors to convert List to Map of Objects - Java
Java
I am reading an article about the Java Volatile keyword , got some questions . click hereThe udpate ( ) method writes three variables , of which only days is volatile.The full volatile visibility guarantee means , that when a value is written to days , then all variables visible to the thread are also written to main m...
public class MyClass { private int years ; private int months private volatile int days ; public void update ( int years , int months , int days ) { this.years = years ; this.months = months ; this.days = days ; } }
Full volatile Visibility Guarantee
Java
Why ismore strict then This is a follow up on Why is lambda return type not checked at compile time.I found using the method withX ( ) likeproduces the wanted compile time error : The type of getLength ( ) from the type BuilderExample.MyInterface is long , this is incompatible with the descriptor 's return type : Strin...
public < R , F extends Function < T , R > > Builder < T > withX ( F getter , R returnValue ) { ... } public < R > Builder < T > with ( Function < T , R > getter , R returnValue ) { ... } .withX ( MyInterface : :getLength , `` I am not a Long '' ) import java.util.function.Function ; public class SO58376589 { public sta...
Why is a type parameter stronger then a method parameter
Java
I 'm trying to understand add operation of ArrayList Class in Java from here . Here is a portion of code : Steps for the elements insertion are : verify if it does exist enough space before inserting a new element by calling ensureCapacityInternal , in case there is no enough space we call grow operation to increase el...
//Proprties : 107 /** 108 * The array buffer into which the elements of the ArrayList are stored . 109 * The capacity of the ArrayList is the length of this array buffer . 110 */ 111 private transient Object [ ] elementData ; 112 113 /** 114 * The size of the ArrayList ( the number of elements it contains ) . 115 * 116...
Add an element to ArrayList when there is no space left
Java
Consider a Dagger module : Context is an object may be connected to e.g . an HTTP sessionthat can not be known at startup , when one would normally create agraph : Given that Module is sufficiently long , it would seem to makesense to first create a graph for Module : and then , on processing a particular request , to ...
@ Module ( library = true , complete = false ) public static class Module { @ Provides public Contextualized providesContextualized ( Context ctx ) { return new Contextualized ( ctx.getUsername ( ) ) ; } // ... and many more such provides . } @ Module ( library = true , complete = false ) public static class ContextMod...
Traceback on Dagger .plus ( ) on incomplete parent
Java
I have an abstract class called sessions . Lectures and tutorials extend sessions . Then I have a class called enrollment which holds a list of sessions ( Lectures & tutorials ) . How can I loop through the session list in Enrolment and return a list of Lectures only from the session list ? My next question is should I...
public class Enrolment { private List < Session > sessions ; public Enrolment ( ) { this.sessions = new ArrayList < > ( ) ; } public addSession ( Session session ) { this.sessions.add ( session ) ; } } public class Session { private int time ; public Session ( int time ) { this.time = time ; } } public class Lecture ex...
How to figure out what object is in a abstract list ?
Java
My standard AppEngine application needs to perform changes in a Google Sheet documents ( among others ) .To achieve this , I need to obtain a credential for service account , and somehow configure that it should act in behalf of a user.This method allows gives me default service account credentials : but it does not wo...
private static GoogleCredential getDefaultServiceAccountCredential ( ) throws IOException { return GoogleCredential.getApplicationDefault ( ) .createScoped ( MY_SCOPES ) ; } private static GoogleCredential getNonDefaultServiceAccountCredential ( ) throws IOException { return GoogleCredential.fromStream ( IncomingMailHa...
How can I impersonate a user of AppEngine java application operating in G-Suite domain ?
Java
i try to android 3.0. i upgrade my android project to android studio 3.0 after that i cant run my project and i have this error . i use MultiDex and use java 8. this is my build.gradle and this is my compile error
dependencies { compile fileTree ( include : [ '*.jar ' ] , dir : 'libs ' ) compile `` com.android.support : appcompat-v7 : $ { project.APP_COMPACT_VERTION } '' compile `` com.android.support : cardview-v7 : $ { project.APP_COMPACT_VERTION } '' compile `` com.android.support : design : $ { project.APP_COMPACT_VERTION } ...
Error : Error converting bytecode to dex : Cause : not found : Ljava/lang/Object ;
Java
Looking at the example above , it seems the main point of generics is to enforce type on a collection . So , instead of having an array of `` Objects '' , which need to be cast to a String at the programmer 's discretion , I enforce the type `` String '' on the collection in the ArrayList . This is new to me but I just...
private ArrayList < String > colors = new ArrayList < String > ( ) ;
Are Java generics mainly a way of forcing static type on elements of a collection ?
Java
I have the following class : I want to change it to the following definition : Is this change binary compatible ? I.e. , will code that is compiled against the old version of the class work with the new version without reocmpilation ? I know that I need to change SomePrivateSubclassOfFoo , this is ok . I also know that...
public abstract Foo { Foo ( ) { } public abstract Foo doSomething ( ) ; public static Foo create ( ) { return new SomePrivateSubclassOfFoo ( ) ; } } public abstract Foo < T extends Foo < T > > { Foo ( ) { } public abstract T doSomething ( ) ; public static Foo < ? > create ( ) { return new SomePrivateSubclassOfFoo ( ) ...
Is making return type generic with same erasure binary compatible ?
Java
So I have a random question when coding the image processing function that involves time complexity . The following is my original snippet of code : And after coming out with that code , I was wondering whether it would be faster not to create 4 temporary variables for floor and ceiling values but , instead , calculate...
long start = System.currentTimeMillis ( ) ; for ( int i = 0 ; i < newWidth ; i++ ) { for ( int j = 0 ; j < newHeight ; j++ ) { double x = i * scaleX ; double y = j * scaleY ; double xdiff = x - ( int ) x ; double ydiff = y - ( int ) y ; int xf = ( int ) Math.floor ( x ) ; int xc = ( int ) Math.ceil ( x ) ; int yf = ( i...
Difference in time complexity in array addressing in Java
Java
I was trying to parse a date string using jodatime with a leading '+ ' before the yyyy part . I expected an error to be thrown , but it actually did not throw an error . I got outputs that do n't make any sense instead : Can anyone explain why this is happening ? I expect either an exception , which means '+ ' sign is ...
System.out.println ( DateTimeFormat.forPattern ( `` yyyyMMdd '' ) .parseDateTime ( `` 20130101 '' ) ) ; // 2013-01-01T00:00:00.000+05:30 ( Expected ) ( case 1 ) System.out.println ( DateTimeFormat.forPattern ( `` yyyyMMdd '' ) .parseDateTime ( `` +20130101 '' ) ) ; // 20130-10-01T00:00:00.000+05:30 ( ? ? ? Notice that ...
Weird behaviour of jodatime in parsing some date formats
Java
Starting with Java 8 so need a bit of time to get used to it . It 's a classical problem , I 've an array of objects that I want to transform.Before Java8 the ideal code would be ( no null pointers ) : What is the best version in Java8 ?
P [ ] outputArray = new P [ inputArray.length ] ; for ( int i =0 ; i < inputArray.length ; i++ ) { outputArray [ i ] = inputArray [ i ] .transformToP ( ) ; }
Java 8 - best way converting array elements
Java
I 'm battling to understand why this is possible . I 'm a java newbie and do n't understand how you can have a collection of any type ( lists or sets ) be of type Example . I 'm battling to understand both the recursive nature of this as well as why this is used .
class Example { private Set < Example > setExample ; // ... . }
Why can you have a HashSet of objects of that class
Java
So , I have a root process ( running as root ) , and I want it to load another process with a non-root uid.At the moment , I 'm calling seteuid , and setegid , then resettting to root after the process has been created . I found that the process still loads with a uid of root . What should I be using to do this ? Java ...
public boolean loadVHost ( String java , File sockfile ) throws IOException { if ( CLib.INSTANCE.setegid ( suid ) ! = 0 ) { log ( `` setegid C call failed ! @ `` + id ) ; return false ; } if ( CLib.INSTANCE.seteuid ( suid ) ! = 0 ) { log ( `` seteuid C call failed ! @ `` + id ) ; return false ; } if ( CLib.INSTANCE.get...
Loading a process as another user ?
Java
In the function below , what can I use to replace < typedefinition > to make the program print `` O noes ! `` ?
public static void main ( String [ ] args ) { Object o = null ; story ( o ) ; } private static void story ( < typedefinition > o ) { if ( o ! = null ) System.out.println ( `` O noes ! `` ) ; else System.out.println ( `` O yes '' ) ; }
Is it possible to call a method with a null parameter but have the argument not be null ?
Java
I think that question is pretty straight . but here is an examples.Example below is OK . I can take rounding and no truncating was done here.Output : And now number out of range of long : Output : This one troubles me . I can not continue work with completely different number . I would rather get an error or an excepti...
public static void main ( String [ ] args ) { double d = 9.9 ; long l = ( long ) d ; System.out.println ( l ) ; } 9 public static void main ( String [ ] args ) { double d = 99999999999999999999999999999999.9 ; long l = ( long ) d ; System.out.println ( l ) ; } 9223372036854775807
How to test if value stored in double fit in long ? ( rounding yes , but truncating no )
Java
I receive a AbstractMethodError when invoking a method that , I think , should have a default implementation in the target instance.I create a functional interface in three parameters but also derive from java.util.function.Function and provide a default implementation of Function # apply ( .. ) . I then create an inst...
package spike ; import java.util.function.BiFunction ; import java.util.function.Function ; public class ReductionProblem { interface F3 < T , U , V , R > extends Function < T , BiFunction < U , V , R > > { default BiFunction < U , V , R > apply ( final T t ) { return ( U u , V v ) - > apply ( t , u , v ) ; } R apply (...
Java 8 default implementation is not available when instance is passed as its superinterface
Java
I 'm making application that requires to get data from Facebook.To avoid duplicating code I decided to create a class for GraphRequest . To call the class I useThe problem is GraphApiRequest method always returns object=null and only after that executes request . What should I change to get actual object on call ? EDIT...
public class FacebookRequest { private static JSONObject object ; private FacebookRequest ( JSONObject object ) { this.object = object ; } private static JSONObject GraphApiRequest ( String path , AccessToken token ) { new GraphRequest ( token , path , null , HttpMethod.GET , new GraphRequest.Callback ( ) { public void...
Calling Facebook GraphRequest from another class returns null
Java
I 've done a lot of searching through generic type questions and just have n't found anything that has helped me figure out what I am doing wrong here . I have an interface as follows : Now , the next step is making a class that implements this interface . This particular class is going to use an insertion sort and I n...
public interface SortAnalysis < E extends Comparable < ? super E > > { public long analyzeSort ( ArrayList < E > list ) ; } public class InsertionSort < E extends Comparable < ? super E > > implements SortAnalysis { @ Overridepublic long analyzeSort ( ArrayList list ) { // TODO Auto-generated method stub return 0 ; } A...
Keeping generic types when implementing in class
Java
I 'm preparing myself to a Java exam , and I 'm reading `` OCA Java SE 8 Programmer Study Guide ( Exam 1Z0-808 ) '' . In operators section I found this sentence : Shift Operators : A shift operator takes two operands whose type must be convertible to an integer primitive.I felt odd to me so I tested it with long : and ...
public class HelloWorld { public static void main ( String [ ] args ) { long test = 3147483647L ; System.out.println ( test < < 1 ) ; } }
Shift operators - operands must be convertible to an integer primitive ?
Java
Just removed the following code from a colleague 's code : I just want to make sure I did the right thing . Why would someone intentionally write this ? This is exactly what the compiler inserts by default is n't it ? Edit : To clarify : that 's the only constructor.Also , this is not a trick question . The guy who wro...
public ClassName ( ) { super ( ) ; }
Why would someone intentionally implement the default implementation of the default constructor ?
Java
I recently discovered the `` assert '' statement in Java , and have been littering my software with them as I debug it . My initial instinct was to avoid making control flow statements just to handle assert statements , but then I realized that these control statements would probably be removed during a production buil...
for ( T obj : Collection ) { assert obj.someProperty ( ) ; } TreeMap < Integer , T > map = new TreeMap < > ( ) ; int i = 0 ; for ( T obj : Collection ) { map.put ( i , obj ) ; assert obj.someProperty ( ) ; i++ ; } // assert something about map , then never use it again
Will an iterator surrounding an assert statement affect performance of production build ?
Java
I have two example class files , one from an example Java app and one from an example C app ( compiled to bytecode using LLJVM ) .Looking at their outputs , I can see through javap -c -p that for initializing the ( static ) fields , the Java app shows the following block : Which is basically the < clinit > method , if ...
static { } ; Code : 0 : sipush 13393 : putstatic # 7 //Field SRV_IDetc public { } ; Code : 0 : sipush 13393 : putstatic # 7 //Field SRV_IDetc
Javap output : difference static { } and public { }
Java
I can add abstract keyword inside static initialization block , but I ca n't add abstract method as So I can only add abstract class inside static block , as follows : But it does n't sound realistic to add classes hierarchy inside static block which will be in lower access level than private , is there other usage of ...
abstract void draw ( ) ; static { abstract class Abstract { abstract String test ( ) ; } class Extends extends Abstract { @ Override String test ( ) { return null ; } } new Extends ( ) .test ( ) ;
abstract class inside static block usage
Java
I want the GUI to change the title of a button from `` Go '' to `` Working ... '' before an object is instantiated and actually does the work . When finished , I want the title of the button to switch back to `` Go . `` Here 's the code : What actually happens in practise is name is instantiated , methodName gets calle...
private class convert implements ActionListener { public void actionPerformed ( ActionEvent e ) { JButton button = ( JButton ) e.getSource ( ) ; button.setText ( `` Working ... '' ) ; button.setEnabled ( false ) ; anObject name = new AnObject ( ) ; boolean result = name.methodName ( chooser.getSelectedFile ( ) , encodi...
Operation priority in Java . ( An object instantiates and runs before the GUI is updated ? )
Java
I need to declare an instance of Map.class , but the Map is typed ... So I need something like this : This line causes a compile error . What is the clean way of expressing this ?
Class < Map < String , String > > clazz = Map.class ;
How to declare a Typed Class in Java ?
Java
I have seen examples on the site that deal with generics with multiple parameters but none that work for my situation.So here is the deal : I am trying to learn Java generics and have decided to create a simple binary array search utility function . I am testing it out using custom objects and integers . To get feedbac...
public static int binarySearch ( Comparable [ ] array , Comparable item , int start , int end ) { if ( end < start ) { return -1 ; } int mid = ( start + end ) / 2 ; if ( item.compareTo ( array [ mid ] ) > 0 ) { return binarySearch ( array , item , mid + 1 , end ) ; } else if ( item.compareTo ( array [ mid ] ) < 0 ) { r...
Java generics with multiple parameters
Java
I have the following sealed interface ( Java 15 ) : This interface is implemented by 2 classes : Can someone tell me the difference between final and non-sealed ? final stops me from creating other sub-classes but what behavior does non-sealed apply to Duck ?
public sealed interface Animal permits Cat , Duck { String makeSound ( ) ; } public final class Cat implements Animal { @ Override public String makeSound ( ) { return `` miau '' ; } } public non-sealed class Duck implements Animal { @ Override public String makeSound ( ) { return `` quack '' ; } }
What is the difference between a final and a non-sealed class in Java 15 's sealed-classes feature ?
Java
The method of the Arrays class in its implementation navigates through the array argument a following the binarySearch algorithm and converts the elements of a into Comparable and invokes compareTo ( key ) until it either finds a match or runs out of possibilities . I 'm stumped by the implementation however , if it 's...
public static int binarySearch ( Object [ ] a , Object key ) public static int binarySearch ( Comparable [ ] a , Object key )
Why Arrays.binarySearch ( Object [ ] , Object ) takes Object args ?
Java
This question is probably language-agnostic , but I 'll focus on the specified languages.While working with some legacy code , I often saw examples of the functions , which ( to my mind , obviously ) are doing too much work inside them . I 'm talking not about 5000 LoC monsters , but about functions , which implement p...
void WorriedFunction ( ... ) { // Of course , this is a bit exaggerated , but I guess this helps // to understand the idea . if ( argument1 ! = null ) return ; if ( argument2 + argument3 < 0 ) return ; if ( stateManager.currentlyDrawing ( ) ) return ; // Actual function implementation starts here . // do_what_the_funct...
General function question ( C++ / Java / C # )
Java
I 'm having a problem with RxJava , Retrofit and Multi-Window mode ... I 'm calling our own api with Retrofit inside an Activity ( the actual code is a little bit more complex than this ) : When the app is in `` normal '' mode ( full-screen ) everything runs fine ... I can put the app in bg , put it back to foreground ...
api.getEvent ( ... ) .subscribeOn ( Schedulers.io ( ) ) .observeOn ( AndroidScheduler.mainThread ( ) ) .subscribe ( event - > setupUI ( event ) , throwable - > showSnackbar ( throwable ) ) ; Retrofit : java.io.InterruptedIOException : thread interrupted at okio.Timeout.throwIfReached ( Timeout.java:145 ) at okio.Okio $...
Strange lifecycle callbacks ordering when entering multi-window mode
Java
I 've read a lot of posts and tried many solutions , but the common point of all posts was that they were all outdated and at least I could n't find a solution that would work on newer versions of Android.Post 1 , Result : intent.getExtras ( ) .getInt ( `` simId '' , -1 ) always returns -1Post 2 , Result : intent.getEx...
String [ ] array = new String [ ] { `` extra_asus_dial_use_dualsim '' , `` com.android.phone.extra.slot '' , `` slot '' , `` simslot '' , `` sim_slot '' , `` subscription '' , `` Subscription '' , `` phone '' , `` com.android.phone.DialingMode '' , `` simSlot '' , `` slot_id '' , `` simId '' , `` simnum '' , `` phone_t...
Detecting target SimCard of incoming call in Multi-Sim devices
Java
I wrote a simple Util method to convert a String in Java to util.Date . What I am not able to figure out is why the method works for the first input , and fails for the second one , given that the inputs are identical : Code : Output : Logically , the output should 've been Sat Feb 04 13:17:00 CET 2012 going by the fir...
package util ; import java.text.DateFormat ; import java.text.ParseException ; import java.text.SimpleDateFormat ; import java.util.Date ; public class StringToDate { public Date getDateFromString ( String strDate , String dateFormat ) { DateFormat df = new SimpleDateFormat ( dateFormat ) ; Date date = null ; try { dat...
Inconsistent ParseExeption with Data Format in Java
Java
Would it be considered worsening the future readability of the code if I used them throughout the code ? For example using : so I can use this code
import static java.lang.Integer . * ; int a = parseInt ( scanner.nextLine ( ) ) ;
Using static imports and code readability quality ?
Java
For example : When e.printStackTrace ( ) executes , are we guaranteed to own the object 's monitor ? The reference says that when wait ( ) returns after a notify ( ) or notifyAll ( ) call , the thread waits until it acquires the object 's monitor . But what about the case when wait ( ) throws an exception ?
public synchronized Object get ( ) { while ( result == null ) { try { wait ( ) ; } catch ( InterruptedException e ) { e.printStackTrace ( ) ; // Do we own the monitor of this object ? } } return result ; }
If wait ( ) throws an InterruptedException , does the thread wait until it acquires the object 's monitor ?
Java
Consider the following codeWhen are these Strings created ? I assume the Strings will get created when an Exception occurs at run time . The string gets created at run time and is displayed . A peer of mine tells me that since these are constant Strings they will get created as soon as the Class loads . Is that correct...
public static void method ( String [ ] srgs ) { try { } catch ( ) { System.out.println ( `` Hello World '' + `` one '' ) ; } catch ( .. ) { System.out.println ( `` Hello World '' + `` two '' ) ; } catch ( .. ) { System.out.println ( getString ( ) ) ; } }
When are constant Strings created/destroyed ?
Java
In java , I use the function all the time . Is there an equivalent function in python ?
variable = something == 1 ? 1 : 0
Equivalent for ? in Java for Python ?
Java
now i get some logs like below ( log-1 ) line 1010I think , the log should be like this ( log-2 ) I wannna know that why do i get log-1 , is it right ? If log-1 is right , then how can i write code to create an exception like that ? ps : I know that ClassA $ 1 is an anonymous class.ps : I get this log in a monkey test ...
java.lang.ClassCastException : android.widget.LinearLayout $ LayoutParams can not be cast to ClassA $ 1at android.widget.LinearLayout.measureHorizontal ( LinearLayout.java:1010 ) ... final LinearLayout.LayoutParams lp = ( LinearLayout.LayoutParams ) obj.method ( ) ; //line 1010 java.lang.ClassCastException : ClassA $ 1...
a ClassCastException about anonymous class ( java )
Java
I need to validate a user given String and validate that it is a valid Set , possibly a set that contains inner sets . Examples : This is the regex I am using ( broken up for readability ) : Currently the it accepts Sets with optional opening and closing brackets , but I need it to only accept if they are both there , ...
1 ) { 1 , 2 , 3 , 4 } = valid 2 ) { 1 , 2 , { 3 , 4 } , 5 } = valid 3 ) 1 , 2 , 3 , 4 = invalid ( missing brackets ) 4 ) { 1 , 2 , { 3 , 4 , 5 } = invalid ( missing inner bracket ) String elementSeparator = `` ( , \\s ) ? `` ; String validElement = `` ( \\ { ? [ A-Za-z0-9 ] *\\ } ? '' + elementSeparator + `` ) * '' ; S...
Mathematical Set Validation with regular-expression
Java
I am in the following situation ... I am used to being able to check out a Subversion server subproject into JBoss as an exploded war : in my case , I call a directory Blah.war , put it in C : \jboss-6.1.0.Final\server\default\deploy\Blah.war , and JBoss picks it right up.I 'm having trouble doing this with Git . The S...
... /Project/trunk/Services ... /Project/trunk/Web
How to use a Git repository as an exploded war ?
Java
I am hoping to get some help debugging this problem.If I send the following JSON to my backend it works correctly : However , if I now send the following : I get the above error . In my backend code I have the following : And the API method signature looks like this : I believe the problem I am having is that the JSON ...
{ `` approvalRequired '' : false , `` location '' : { `` locationName '' : `` < +37.33233141 , -122.03121860 > +\/- 5.00m ( speed 0.00 mps \/ course -1.00 ) @ 9\/16\/18 , 9:24:59 PM Pacific Daylight Time '' , `` longitude '' : -122.0312186 , `` latitude '' : 37.332331410000002 } } { `` approvalRequired '' : false , `` ...
The request sent by the client was syntactically incorrect Java ZonedDateTime backend