lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have an annotation that can be added on METHOD and TYPE and is used in thousands of places in our project . Is it possible to make the annotation deprecated only on methods while keeping it non-deprecated on types ? I want other developers to be notified by IDE that it should not be used on methods any more , until w...
@ Retention ( java.lang.annotation.RetentionPolicy.RUNTIME ) @ Target ( { METHOD , TYPE } ) @ Inheritedpublic @ interface RequiredStore { Store value ( ) ; }
How to make annotation deprecated only on one target
Java
If I add @ Builder to a class . The builder method is created.I have a requirement where a particular field is mandatory . In this case , the name field is mandatory . Ideally , I would like to declare it like so.When googling i found many alternatives like overriding the builder implementation as below : And then use ...
Person.builder ( ) .name ( `` john '' ) .surname ( `` Smith '' ) .build ( ) ; Person.builder ( `` john '' ) .surname ( `` Smith '' ) .build ( ) ; @ Builderpublic class Person { private String name ; private String surname ; public static PersonBuilder builder ( String name ) { return new PersonBuilder ( ) .name ( name ...
Lombok 's builder with mandatory parameters
Java
Please consider the following two functions : While composite ( first , second ) computes the composition of first and second , iterate ( function , n ) computes the nth iterate of function.While the restriction Y extends X suffices for any n > 0 , we 've got some problem with n == 0 . Mathematically , iterate should y...
public static < X , Y , U , V extends X > Function < U , Y > composite ( Function < X , Y > first , Function < U , V > second ) { Objects.requireNonNull ( first ) ; Objects.requireNonNull ( second ) ; return ( U arg ) - > first.apply ( second.apply ( arg ) ) ; } public static < X , Y extends X > Function < X , ? > iter...
How to write a generic iteration of a function using Java 8 ?
Java
i have a complex problem with Java 8.ProblemWith nested lambda compiler crash with a NullPointerException ! I know that lambdas must be stateless indeed in this case the codes that have state are Supplier implementations that however are anonymous classes and not lambdas.CodeStacktraceTestsI did several attempts with d...
import java.util.function.Function ; import java.util.function.Supplier ; public class Test { public static Function < String , Supplier < String > > A = aVal - > new Supplier < String > ( ) { @ Override public String get ( ) { return B.apply ( aVal ) .get ( ) ; } private Function < String , Supplier < String > > B = b...
Java 8 nested lambdas break compiler
Java
I am new to Java and using a code given by someone . There , at the end of the code , they interrupt a thread if it has not finished . I am measuring the timing of the code.The problem is that the Java code first issues all the threads , and then at the end it interrupts . Is interrupting necessary ? Ca n't we wait til...
String commandString = `` ./script.scr `` ; process = Runtime.getRuntime ( ) .exec ( commandString ) ; BufferedReader bufferedReader = new BufferedReader ( new InputStreamReader ( process.getInputStream ( ) ) ) ; while ( ( lsString = bufferedReader.readLine ( ) ) ! = null ) { System.out.println ( lsString ) ; } try { p...
java : is interrupting thread absolutely necessary
Java
I tend to use ( or even overuse ) double braces object intialization in GWT . For me it looks more readable and more declarative.Before today I was not aware that this syntax is not just instantiate object but also create AnonymousInnerClass for it . Now I am concerned how GWT deal with them . How this syntax affects p...
new FastMap < Object > ( ) { { put ( `` Value '' , 12 ) ; put ( `` Unit '' , `` Kg '' ) ; } } ;
How harmful are double braces in GWT ?
Java
This is probably a really stupid question , but I 'm having problems calling methods in java . For my computer science class I am instructed to write a single program with multiple methods . In one method I am to prompt the user to enter an integer , return that integer and store it in a variable . The next method is t...
import java.util.Scanner ; public class MethodlabPractice { public static void main ( String [ ] args ) { printBanner ( ) ; getInput ( ) ; isOdd ( number ) ; } // end main public static void printBanner ( ) { for ( int count = 0 ; count ! = 10 ; count++ ) System.out.println ( `` Beth Tanner '' ) ; } // end printBanner ...
Calling Methods
Java
I ran into this logic that someone had implemented at work today and it just feels wrong to be creating locks this way . Do you guys have a better solution for this ? The problem with not using synchronized block on myObj is that it can be null . Any other suggestions ? ?
public class myClass { private Object myObj ; private Object lock = new Object ( ) ; public void method1 ( ) { synchronized ( lock ) { // has logic to read myObj } } public void method2 ( ) { synchronized ( lock ) { // has logic to update myObj } } }
Is this an acceptable way to create a lock in Java ?
Java
First of all to prevent mark question as duplicate by guys who do n't like read to the end I have read Producer-Consumer Logging service with Unreliable way to shutdown question . But it is not fully answer the question and answer contradicts the book text.In book provided following code : Now we should to understand h...
public class LogWriter { private final BlockingQueue < String > queue ; private final LoggerThread logger ; private static final int CAPACITY = 1000 ; public LogWriter ( Writer writer ) { this.queue = new LinkedBlockingQueue < String > ( CAPACITY ) ; this.logger = new LoggerThread ( writer ) ; } public void start ( ) {...
Why can race condition in LogWriter cause the producer to block ? [ Concurrency in practice ]
Java
In terms of memory used and impact on garbage collector , I would like to know if there is a difference between those two implementations : Also , if there is any functional difference , please tell me !
protected List < T > _data = new ArrayList < T > ( ) ; // I want to reset this list using another one . First try : public void set ( List < T > newData ) { _data = newData ; } // I want to reset this list using another one . Second try : public void set ( List < T > newData ) { _data.clear ( ) ; _data.addAll ( newData...
Memory management : how to reset a list correctly
Java
Some of our code is auto-generated ( by Apache Axis ) and it reports a ton of warnings . An example would be : Here , the warning would be HashMap is a raw type . References to generic type HashMap should be parameterized.Of course it makes no sense to actually address these warnings , as we have to trust Apache Axis a...
private java.util.HashMap faultExceptionNameMap = new java.util.HashMap ( ) ;
Java - Ignore warnings on directory/package level
Java
In my scenario , a string is given to my function and I should extract only the numbers and get rid of everything else.Example inputs & their expected array output : In Qt/C++ I 'd just do it as follows : So with java I tried something similar but it did n't work as expected.So , what would be the best way to escape al...
13/0003337/99 // Should output an array of `` 13 '' , `` 0003337 '' , `` 99 '' 13-145097-102 // Should output an array of `` 13 '' , `` 145097 '' , `` 102 '' 11 9727 76 // Should output an array of `` 11 '' , `` 9727 '' , `` 76 '' QString id = `` 13hjdhfj0003337 90 '' ; QRegularExpression regex ( `` [ ^0-9 ] '' ) ; QSt...
Split string to get an array of digits only ( escaping white & empty spaces )
Java
Does anyone know how I can do a common `` OR '' like in a where clause , in firebase ? I need to do that in the query , because I am sending the query to an adapter . So , i mean , I can not add a listener and check one value and then another . I need to have the complete query pointing to that result in my query.What ...
chat1 : user1Id : `` 1 '' user2Id : `` 2 '' bothUsers : `` 1_2 '' chat2 : user1Id : `` 2 '' user2Id : `` 4 '' bothUsers : `` 2_4 '' userLogged = 2 ; Query queryRef = firebase.orderByChild ( `` user2Id '' ) .equalTo ( userLogged ) ;
OR clause in firebase java android
Java
Introducing some of the goodness of collection operations to our codebase without adding a new external library dependency , we are adding these methods to our utility package.With the attendant interfacesSo the questions : Is Filters a good name for the class containing the extensions ? If not , a better ? Is Mutator ...
static public List < T > filter ( List < T > source , Predicate < T > filter ) ; static < Y , T > public List < Y > transform ( List < T > source , Mutator < Y , T > filter ) ; static public boolean exists ( List < T > source , Predicate < T > filter ) ; static public T findFirst ( List < T > source , Predicate < T > f...
Naming Collection Extensions for clarity
Java
I have a container running a Spring Boot microservice . I am using openjdk version `` 1.8.0_212 '' under OpenJDK Runtime Environment ( IcedTea 3.12.0 ) ( Alpine 8.212.04-r0 ) When I use -XX : +PrintFlagsFinal flag and print the JVM parameters I expected to see -XX : +UseParallelGC as trueBut to my surprise none of the ...
FROM openjdk:8-jdk-alpineADD ./demo-0.0.1-SNAPSHOT.jar /usr/src/factorial/WORKDIR /usr/src/factorialEXPOSE 8080CMD java $ JAVA_OPTIONS -jar demo-0.0.1-SNAPSHOT.jar docker run -d -- rm -- name factorialorialContainer -- memory='512m ' -- cpus=2 -p 8080:8080 -e JAVA_OPTIONS= '' $ ( cat /Users/sulekahelmini/Documents/fyp/...
In Java 8 it is shown as none of the available 4 collectors ( GC ) are selected by default
Java
I know when we are passing objects we are passing its reference as a value . But this value you get is using the hashcode ( ) method right ( according to my tests it 's the same ) ? Since hashcode ( ) is not the memory address and not guaranteed to get unique values all the time , can there be strange things happen lik...
Object o = new Object ( ) ; System.out.println ( o ) ; System.out.println ( o.toString ( ) ) ; //both prints same thing - java.lang.Object @ 10385c1
what really happens when passing objects in java ?
Java
I have a CustomDialogFragment like thisAnd from outside where I call the DialogFragment.I got the crash saying Any thoughts ?
public class CustomDialogFragment extends DialogFragment { private LinearLayout containerView ; public static CustomDialogFragment newInstance ( ) { CustomDialogFragment fragment = new EDActionSheet ( ) ; return fragment ; } @ Override public Dialog onCreateDialog ( Bundle savedInstanceState ) { final Dialog dialog = n...
Custom Dialog Fragment Crashes when Setter Method is Called
Java
I have a question on how to proceed with my code . My project is a tool which runs configurations one by one in the background . I would like to add a limit to it for the number of running configurations.For example , if I have 13 configurations I would like to run 5 configurations each time , so the order will be : Th...
- Running 5 configurations- All 5 configurations done running- Running 5 configurations- All 5 configurations done running- Running 3 configurations- All 3 configurations done running public void runConfigurations ( List < ConfigStruct > configurations ) { for ( ConfigStruct configuration : configurations ) { try { con...
Running configurations with a limit
Java
i have a question to Java Overload Methods . Suppose i have an overload methods foo : How can I implement to functions like of which one uses the overloaded string method , and one the overloaded object method ? The call of the foo-Method should use an String input . ( that means i do not want to work with a cast like ...
public static String foo ( String x ) { return `` foo-String : `` + x ; } public static String foo ( Object x ) { return `` foo-Object : `` + x ; } public static String useString ( ) { return ( foo ( `` useString '' ) ) ; } public static String useObject ( ) { return ( foo ( `` useObject '' ) ) ; } return ( foo ( ( Obj...
How to select which overloaded version of a method to call without using a cast ?
Java
I 'm new in programming in Java and I do not understand what 's going on in my code.It tells me : My main.java is simple : this is addMine method : and Mine.java is : As You can see I wrote 2 println-s and both of them were false , so the object exists ! I do n't understand why it shows NullPointerException : (
Exception in thread `` main '' java.lang.NullPointerException at Main.Country.addMine ( Country.java:37 ) at Main.Main.main ( Main.java:21 ) Java Result : 1 Continent Europe = new Continent ( `` Europe '' ) ; Country asd = new Country ( `` asd '' , Europe ) ; Mine mine = new Mine ( 100,100,100,100 ) ; System.out.printl...
Java NullPointerException - Short Program
Java
Possible Duplicate : Compiler complains about “ missing return statement ” even though it is impossible to reach condition where return statement would be missing The following method in Java compiles fine.The method has an explicit return type which is java.lang.String with no return statement though it compiles fine ...
public String temp ( ) { while ( true ) { if ( true ) { // Do something . } } } public String tempNew ( ) { if ( true ) { return `` someString '' ; } } public String tempNew ( ) { if ( true ) { return `` someString '' ; } else { return `` someString '' ; } } public String tempNew ( ) { if ( true ) { return `` someStrin...
Why is an error issued with an if statement in Java even though it is always true ?
Java
I wanted to know if this is an implementation detail ... In Java , used local variables are captured for anonymous classes , and lambdas . For anonymous classes , the this is also captured in a non static context whether needed or not . It appears , however , any local variable referenced is captured even if not used f...
public static void main ( String [ ] args ) { Thread t = Thread.currentThread ( ) ; Runnable run = new Runnable ( ) { @ Override public void run ( ) { t.yield ( ) ; } } ; Runnable run2 = ( ) - > t.yield ( ) ; run.run ( ) ; run2.run ( ) ; } // access flags 0x1 public run ( ) V L0 LINENUMBER 8 L0 ALOAD 0 GETFIELD UnusedL...
Unused referenced variables always captured in Java
Java
So I have a piece of code where I 'm iterating over a list of data . Each one is a ReportData that contains a case with a Long caseId and one Ruling . Each Ruling has one or more Payment . I want to have a Map with the caseId as keys and sets of payments as values ( i.e . a Map < Long , Set < Payments > > ) .Cases are ...
rowData.stream ( ) .collect ( Collectors.groupingBy ( r - > r.case.getCaseId ( ) , Collectors.mapping ( r - > r.getRuling ( ) , Collectors.mapping ( ruling- > ruling.getPayments ( ) , Collectors.toSet ( ) ) ) ) ) ;
Elegant way to flatMap Set of Sets inside groupingBy
Java
I am using the library Apache-POI for my app . Specifically , POIshadow-all ( ver . 3.17 ) for reading a Word document.I am successfully extracting every paragraph as follows : what I actually need is extract every line , as follows : The code to extract every paragraph is this : The variable currentParagraph returns a...
try { val fis = FileInputStream ( path.path + `` / '' + document ) val xdoc = XWPFDocument ( OPCPackage.open ( fis ) ) val paragraphList : MutableList < XWPFParagraph > = xdoc.paragraphs private val newParagraph = paragraph.createRun ( ) ... for ( par in paragraphList ) { var currentParagraph = par.text Log.i ( `` TAG ...
Getting the lines of each paragraphs of a docx with Apache-POI
Java
I 'm wondering to know which program variant are better runtime ? Both variants looks easy to implement . But what are better to use and in which cases ? String reverse : StringBuilder reverse :
public static String reverse ( String s ) { String rev = `` '' ; for ( int i = s.length ( ) - 1 ; i > = 0 ; i -- ) rev += s.charAt ( i ) ; return rev ; } public static String reverse ( String s ) { StringBuilder rev = new StringBuilder ( ) ; for ( int i = s.length ( ) - 1 ; i > = 0 ; i -- ) rev.append ( s.charAt ( i ) ...
Which variants string reverse are better ?
Java
I have two methods in a class ... When I make the following call ... obj.method ( `` string '' , `` string '' , obj ) the correct method is called , however , when I try to call obj.method ( `` string '' , `` string '' , obj [ ] ) the first incarnation of that method is called . Is there any annotation or `` hint '' I ...
public void method ( String var1 , String var2 , Object var3 ) { //do stuff } public void method ( String var1 , String var2 , Object [ ] var3 ) { //do stuff }
Java method overload choice
Java
I have a tasks list object which I am iterating and appending each task object into StringBuilder followed by new line as shown below . Now I will keep appending task object in same string builder until it reaches a size limit of 60000 bytes . Once it reaches the limit , I will populate this string as a value in the ma...
public void populate ( final List < Task > tasks ) { Map < String , String > holder = new HashMap < > ( ) ; int size = 0 ; int index = 0 ; StringBuilder sb = new StringBuilder ( ) ; for ( Task task : tasks ) { sb.append ( task ) .append ( System.getProperty ( `` line.separator '' ) ) ; size = sb.toString ( ) .getBytes ...
Populate string value in a map only if matches the threshold bytes
Java
I have a code something like this and I want to make it scoped . But I found that this is not working and it seems only possible through in a module . I was n't able to find a proper question for this and is it possible to scope a constructor injection ? Does not workScope works ! !
@ AppScope @ Injectpublic StackOverflow ( ) { } @ Modulepublic InternetModule { @ AppScope @ Provides public StackOverflow provideStackOverflow ( ) { return new StackOverflow ( ) ; } }
Is it possible to scope constructor injection in dagger 2 ?
Java
First , some environment : this is Oracle 's 1.6.0_45 JDK , and IDEA 13.1.I have stumbled upon a most bizarre compiler error : Funnel and PrimitiveSink are from Guava ; as to FieldNode , it is from ASM 5.0.1 ( org.objectweb.asm.tree.FieldNode ) .Note that I use IDEA ( 13.1 if that matters at all ) . Now , at first , I ...
public final class AsmFunnels { private AsmFunnels ( ) { } // ... public static void funnelFieldNode ( final FieldNode node , final PrimitiveSink into ) { FieldNodeFunnel.INSTANCE.funnel ( node , into ) ; } // ... @ ParametersAreNonnullByDefault private enum FieldNodeFunnel implements Funnel < FieldNode > { INSTANCE { ...
Bug in compiler or am I doing something wrong ?
Java
I'am currently working in a java project which I have a list of strings and I want them to have a specific format using streams .For exampleInput : [ nom , contains , b , and , prenom , contains , y , and , age , > = , 1 , and , age , < = , 100 ] Ouput : I wrote a very basic code without using streams : SearchCriteria ...
[ { key : '' nom '' , operation : '' contains '' , value : '' b '' } , { key : '' prenom '' , operation : '' contains '' , value : '' y '' } , { key : '' age '' , operation : '' > = '' , value : 1 } , { key : '' age '' , operation : '' < = '' , value : 1000 } ] List filter = [ nom , contains , b , and , prenom , contai...
forming a specific list with Java 8 streams
Java
I 'm trying to do some pre-shutdown cleanup when a SIGINT is sent to my Java application , using the sun.misc.Signal and sun.misc.SignalHandler classes.It appears when I register my handler the default behavior no longer occurs . But there is a SignalHandler.SIG_DFL field containing `` The default signal handler '' . F...
SignalHandler handler = new SignalHandler ( ) { public void handle ( Signal sig ) { ... // handle SIGINT SignalHandler.SIG_DFL.handle ( sig ) ; } } ;
Should I trigger the default signal handler when I define my own handler ?
Java
Hi all I was browsing through some of the Java source code when I came across this ( java.lang.Character ) : I was wondering why did the writer added 1 to the higher limit and doing a lesser-than compare , instead of simply doing a lesser-than-or-equal compare ? I can understand if it helps readability , but in this ca...
public static boolean isHighSurrogate ( char ch ) { return ch > = MIN_HIGH_SURROGATE & & ch < ( MAX_HIGH_SURROGATE + 1 ) ; } public static boolean isLowSurrogate ( char ch ) { return ch > = MIN_LOW_SURROGATE & & ch < ( MAX_LOW_SURROGATE + 1 ) ; } public static boolean isHighSurrogate ( char ch ) { return ch > = MIN_HIG...
char_x < ( char_y + 1 ) == char_x < = char_y ?
Java
Not sure if I am wording this correctly . Please let me know if you require more information.We have a requirement where we need to determine the type of variable based on a system environment variable.So , say we have a the following classThe DUMMY_TYPE is determined based on a system variable . So when Java compiles ...
class Test { DUMMY_TYPE testVariable ; }
Primitive variable type in compile time
Java
I have been digging into spring security yaml a little bit yesterday to make it work with Okta SAML . Logging in works , but the response XML contains user attributes that apparently can not be extracted automatically into an attribute map . The response contains a fields like thisOnce an authentication is successful ,...
< saml2 : Attribute Name= '' user.lastName '' NameFormat= '' urn : oasis : names : tc : SAML:2.0 : attrname-format : unspecified '' > < saml2 : AttributeValue xmlns : xs= '' http : //www.w3.org/2001/XMLSchema '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : type= '' xs : string '' > Surname < /sa...
Spring Security SAML : Extract Attributes from a saml2p : Response as user attributes
Java
I 'm struggling with this aspect of Generics in Java . Hopefully someone can help me see the ways.I have a class that holds a List of objects . This code works , but I want to get rid of the cast . How can I make this more generic ?
public class Executor { List < BaseRequest < BaseObj > > mRequests = new ArrayList < BaseRequest < BaseObj > > ( ) ; public Executor ( ) { } @ SuppressWarnings ( `` unchecked '' ) public < T extends BaseObj > void add ( final BaseRequest < T > request ) { mRequests.add ( ( BaseRequest < BaseObj > ) request ) ; } public...
Java Generics and unchecked cast
Java
Keeping stacktrace out of it , lets say that the idea of 'error ' is a problem that you did n't want to occur , but did.If I were to use a boolean system to check if the action successfully completed , it would look something like this : If I were to use Exceptions , it would look like this : The only thing that matter...
String [ ] array = new String [ 10 ] ; int i = 0 ; public boolean accessValue ( int id ) { if ( id < array.length ) { //do something return true ; } return false ; } while ( true ) { if ( ! accessValue ( i++ ) ) { //tend to situation } } class InvalidAccessException extends Throwable { } public boolean accessValue ( in...
Recommended way to handle problems/errors in algorithms
Java
Let 's say I have a Shelf class and each Shelf has multiple Books.Now , let 's say from some method I have a List of Shelfs , each containing some books . How do I use stream to collect all the books to this list ? I 'm thinking something likebut it does n't seem to work , throwing a compilation error .
public class Shelf { private String shelfCode ; private ArrayList < Book > books ; //add getters , setters etc . } public class Book { private String title ; } List < Shelf > shelves = new ArrayList < Shelf > ( ) ; Shelf s1 = new Shelf ( ) ; s1.add ( new Book ( `` book1 '' ) ) ; s1.add ( new Book ( `` book2 '' ) ) ; Sh...
Agregate nested list with Stream api
Java
After running a recursive function to obtain an employee/manager family tree - a further requirement has come up to reserve an overall manager structure.So I would imagine the input array to look something like thisand the output array would need to look like thisThe hierachy needs to be sorted in this manner to show t...
[ [ `` Employee A '' , `` 1000 '' , `` Employee B '' , `` 1001 '' , `` Employee C '' , `` 1002 '' ] , [ `` Employee D '' , `` 1003 '' , `` Employee C '' , `` 1002 '' ] ] [ [ `` Employee A '' , `` 1000 '' , `` Employee B '' , `` 1001 '' , `` Employee C '' , `` 1002 '' ] , [ `` Employee D '' , `` 1003 '' , null , null , ...
Hierarchy Data shift
Java
How do I enable `` -- enable-preview '' for tests in Kotlin-based Gradle script ? I tried literally everything I could find online with https : //stackoverflow.com/a/61849770/226895 being the closest to correct answer.I still get following error on : test taskby script isWhat am I missing ?
org.gradle.api.internal.tasks.testing.TestSuiteExecutionException : Could not execute test class 'com.blabla.playground.AppTest ' . at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass ( SuiteTestClassProcessor.java:53 ) Caused by : java.lang.UnsupportedClassVersionError : Preview features ...
How do I enable `` -- enable-preview '' for tests ?
Java
Let 's say I have this hierarchy : This works fine , I can do : but I have to do a manual typecast.Is there a way to use java Generics in order to have the clone ( ) method return the actual type of the subclass ? Thank you !
public abstract class AbstractEntity implements Cloneable { ... public AbstractEntity clone ( ) { Cloner cloner = new Cloner ( ) ; AbstractEntity cloned = cloner.deepClone ( this ) ; return cloned ; } } public class EntityA extends AbstractEntity { ... } EntityA e1 = new EntityA ( ) ; EntityA e2 = ( EntityA ) e1.clone ...
Using generics to implement a common method in an abstract class
Java
What is the Java equivalent of these traits in Scala ? I translate the Strategy trait to : I try translating trait Visitor to : As you can see , I do n't know how to understand/translate type R in the Visitor trait . What is a similar Java equivalent ?
trait Visitor { type X type S < : Strategy type R [ v < : Visitor ] = ( S { type X = Visitor.this.X ; type V=v } ) # Y } trait Strategy { type V < : Visitor type X type Y } public interface Strategy < V extends Visitor < ? , ? , ? > , X , Y > { } public interface Visitor < X , S extends Strategy < ? , ? , ? > , R ? ? ?...
What is the Java equivalent of this Scala code ?
Java
I 've tried to use buildpack in a maven project with Spring Boot 2.3.0 running : Image was created just fine , but I see the following info for it : Why does it say the image ( along with the builder ) was created 40 years ago ?
mvn spring-boot : build-image REPOSITORY TAG IMAGE ID CREATED SIZEgcr.io/paketo-buildpacks/builder base-platform-api-0.3 daceb4f909b7 40 years ago 690MBmyimage master a482a4a34379 40 years ago 285MB
Spring Boot 2.3.0 buildpack builds image with creation date 40 years ago
Java
as per my understanding , 1st call to intern method should have created a 'string intern pool ' with a single string `` hello '' . second call to intern method would have done nothing ( as `` hello '' string is already present in pool ) . Now , when i say s1 == s2 i am expecting JVM to compare `` hello '' string from s...
public static void main ( String [ ] args ) { String s1 = new String ( `` hello '' ) ; String s2 = new String ( `` hello '' ) ; s1.intern ( ) ; s2.intern ( ) ; System.out.println ( s1 == s2 ) ; // why this returns false ? }
Why intern method does not return equal String in java
Java
I understand that == operator checks for equal references ( addresses ) but I am not getting how the compiler is throwing below error when comparing Thread and String object.java : incomparable types : java.lang.Thread and java.lang.StringHere is my code : Why is it allowing comparison between Thread and Object but not...
public static void main ( String [ ] args ) { Thread t = new Thread ( ) ; Object o = new Object ( ) ; String s = new String ( `` '' ) ; System.out.println ( t == o ) ; //no issues here System.out.println ( t==s ) ; // but this throws above error }
Understanding == operator for Object Comparison in Java
Java
I have one program in java..i am confused about the output.here output is 0 0 0 0 0But if i write , then output is 1 2 3 4 5Why it is coming like this ? ? ?
public static void main ( String args [ ] ) { int n=0 ; for ( int m=0 ; m < 5 ; m++ ) { n=n++ ; System.out.println ( n ) ; } } public static void main ( String args [ ] ) { int n=0 ; for ( int m=0 ; m < 5 ; m++ ) { n++ ; System.out.println ( n ) ; } }
Difference in the output in Java
Java
I made a java.net.HttpURLConnection and it hang on the line connection.connect ( ) even though I ’ ve set a connect timeout . “ b4 connect ” gets logged and “ after connect ” never gets logged . I ’ ve tested on API 21 and above and things work , but I get this issue with my test on API 16-19 . Here is my code below . ...
URL url = new URL ( urlString ) ; HttpURLConnection connection = ( HttpURLConnection ) url.openConnection ( ) ; try { connection.setRequestMethod ( `` GET '' ) ; connection.setRequestProperty ( `` charset '' , `` utf-8 '' ) ; connection.setRequestProperty ( `` User-Agent '' , `` Mozilla/5.0 ( Macintosh ; Intel Mac OS X...
HTTPS request hangs only on Android APIs below 20 even with a connect timeout set
Java
This answer shows Java 's visibility modifiers and their meaning : My question is , why does allowing visibility to all subclasses imply that you must give visibility to all other classes in your package ? In other words , why did the Java creators make it like this , as opposed to :
Modifier | Class | Package | Subclass | World————————————+———————+—————————+——————————+———————public | y | y | y | y————————————+———————+—————————+——————————+———————protected | y | y | y | n————————————+———————+—————————+——————————+———————no modifier | y | y | n | n————————————+———————+—————————+——————————+———————priva...
Why is package visibility given priority over subclass visibility ?
Java
I 'm trying to figure out how to map data coming in on a request to a Hibernate object , and the issue is that the data coming in could be on the object or the child objects , and the field data is not necessarily known - the forms are user configured to contain and collect the desired data.Roughly , the objects are li...
Job { String title ; @ ManyToOne @ JoinColumn ( name = `` location_id '' ) JobLocation location ; } JobLocation { int id ; String description ; double latitude ; double longitude ; } { jobLocationDescription : 'Santa Fe ' } String [ ] field = requestField.split ( `` . `` ) ; Entity ent = ( get object from field [ 0 ] )...
Hibernate data mapping into child objects
Java
Why does this code print 97 ? I have not previously assigned 97 to ' a ' anywhere else in my code .
public static void permutations ( int n ) { System.out.print ( ' a ' + 0 ) ; }
Do chars have intrinsic int values in Java ?
Java
I 'm running this code with a Twitter handle I 'm pretty sure does n't exist in order to test error handling . The breakpoints on the Callback are never hit , neither for success nor failure.Any pointers on why this is ? Just as a note , this code works fine with a valid Twitter handle , but does n't call the Callback ...
final Callback < Tweet > actionCallback = new Callback < Tweet > ( ) { @ Override public void success ( Result < Tweet > result ) { int x = 1 ; x++ ; // This code is just so I can put a breakpoint here } @ Override public void failure ( TwitterException exception ) { DialogManager.showOkDialog ( context , R.string.twit...
Twitter Android SDK not executing Callback
Java
Consider the following interface : Which is implemented by the following class : Although meth ( ) is a method that throws an exception , the caller of the method meth ( ) is not having to handle or declare the exception and yet the program runs successfully . Why is this the case ? Does it not violate the rule that wh...
package hf ; public interface BadInterface { void meth ( ) throws Exception ; } package hf ; public class apples implements BadInterface { public static void main ( String [ ] args ) { new apples ( ) .meth ( ) ; } public void meth ( ) { System.out.println ( `` Ding dong meth . `` ) ; } }
Why does the caller of the method that throws an exception not have to handle the exception in this situation ?
Java
When using JColorChooser , entered CMYK values translate to a specific RGB color . When that color is entered manually on the RGB side , the CMYK valuesare not the same as before.The following program can be used to demonstrate the behavior I am encountering.In both panels , select CMYK and type in any valid numbers fo...
import java.awt . * ; import javax.swing . * ; public class ColorChooserProblem { JFrame f = new JFrame ( `` Testing Color Chooser '' ) ; public static void main ( String [ ] args ) { new ColorChooserProblem ( ) .start ( ) ; } public void start ( ) { f.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; JColorChooser j...
Anomalous behavior ( or possible bug ) in JColorChooser
Java
Doing Java REST service performance test I see a pattern that was unexpected : a method that creates and returns always the same value object in each invocation runs faster than another version that just returns the value object stored in a class or object field.Code : Byte code : Inline ( faster ) : getstatic , invoke...
@ POST @ Path ( `` inline '' ) public Response inline ( String s ) { return Response.status ( Status.CREATED ) .build ( ) ; } private static final Response RESP = Response.status ( Status.CREATED ) .build ( ) ; @ POST @ Path ( `` staticfield '' ) public Response static ( String s ) { return RESP ; } private final Respo...
What JVM optimization is causing these performance results ?
Java
So ... basically I have a docx file . And I have to do some formatting changes in few paragraphs and then save in a new file . What I am doing is essentially following.For most part everything is working fine . The output docx is opening allright in LibreOffice on my Ubuntu.But , when I transfer this output docx to a W...
import scala.collection.JavaConversions._import org.apache.poi.xwpf.usermodel._def format ( sourceDocumentPath : String , outputDocumentPath : String ) { val sourceXWPFDocument = new XWPFDocument ( new FileInputStream ( sourcePath ) ) // lets say I have a list of paragraph numbers ... I want to format val parasToFormat...
Infinite bogus pages in outpout docx using Apache Poi
Java
This is an assignment question I received from school . The question says , write a method called capitalizer which will take the string `` ownage '' and then displays ( does n't have to return ) all the possible capitalization of it , such as `` OwNaGE '' or `` OWnAGE '' . It does n't have to work for every string , j...
import java.util . * ; class MethodAssign2 { static void capitalizer ( String a , int b ) { if ( b==-1 ) { System.out.println ( `` worked ? `` ) ; } else { char [ ] achars = a.toCharArray ( ) ; achars [ b ] -= 32 ; String caplet = new String ( achars ) ; System.out.println ( caplet ) ; System.out.println ( a ) ; capita...
Basic recursion
Java
I have a Long string that I have to parse for different keywords . For example , I have the String : And my keywords areI have tried a lot of combination of regex but i am not able to recover all the strings . the code i have tried :
`` ==References== This is a reference ==Further reading== * { { cite book|editor1-last=Lukes|editor1-first=Steven|editor2-last=Carrithers| } } * ==External links== '' '==References== ' '==External links== ' '==Further reading== ' Pattern pattern = Pattern.compile ( `` \\=+ [ A-Za-z ] \\=+ '' ) ; Matcher matcher = patte...
Pattern Matching for java using regex
Java
I 'm trying to create a very simple grammar to learn to use ANTLR but I get the following message : `` The following alternatives can never be reached : 2 '' This is my grammar attempt : I 'm using ANTLRWorks plugin for IDEA :
grammar Robot ; file : command+ ; command : ( delay|type|move|click|rclick ) ; delay : 'wait ' number ' ; ' ; type : 'type ' id ' ; ' ; move : 'move ' number ' , ' number ' ; ' ; click : 'click ' ; rclick : 'rlick ' ; id : ( ' a'.. ' z'| ' A'.. ' Z ' ) + ; number : ( ' 0'.. ' 9 ' ) + ; WS : ( ' ' | '\t ' | '\r ' | '\n ...
The following alternatives can never be reached : 2
Java
I am working on a small helper that is supposed to invoke arbitrary code ( passed in as lambda ) . The helper should catch certain exceptions , and throw them inside some wrapper . My `` own '' exceptions should not be wrapped but just re-thrown . I came up with this code : The above gives a compile error : Unreachable...
@ FunctionalInterfaceinterface Processable < T , X extends Throwable > { public T apply ( ) throws X ; } class MyCheckedException extends Exception { ... } class MyCheckedExceptionWrapper extends MyCheckedException { ... } public class MyExceptionLogger < T , X extends Throwable > { public T process ( Processable < T ,...
Why ca n't I have a catch for a checked exception for a call that throws a generic ?
Java
I am trying to run a spring batch on application deployed on websphere . When I run the batch using eclipse all runs fine but when I run the same batch in deployed application on websphere it gives errorI checked source code of paranamer BytecodeReadingParanamer class and it saysI believe it means that the java class w...
com.thoughtworks.paranamer.ParameterNamesNotFoundException : Parameter names not found for executeMethod at com.thoughtworks.paranamer.BytecodeReadingParanamer $ TypeCollector.getParameterNamesForMethod ( BytecodeReadingParanamer.java:209 ) if ( ! collector.isDebugInfoPresent ( ) ) { if ( throwExceptionIfMissing ) { th...
Paranamer error due to missing debug information in compiled class files
Java
I have the following codeOP : Why am i getting `` false '' when i check s==s3 ? ..
public static void main ( String ... args ) { String s = `` abc '' ; System.out.println ( s.hashCode ( ) ) ; String s1 = `` abc `` ; System.out.println ( s1.hashCode ( ) ) ; String s2 = s.trim ( ) ; System.out.println ( s2.hashCode ( ) ) ; String s3 = s1.trim ( ) ; System.out.println ( s3.hashCode ( ) ) ; System.out.pr...
Why does `` == '' sometimes work with String.trim ?
Java
Why Integer ii = ' a ' invalid , but int i = ' a ' valid ? Why Short ss = ' a ' valid , but Integer ii = ' a ' invalid ? another set question : Why b = L ; invalid , while b = s ; valid ? Please , do n't say it is all because JLS said so . I want to know why JLS has these inconsistent and non-intuitive rules . What did...
short s = ' a ' ; // validShort ss = ' a ' ; // validint i = ' a ' ; // validInteger ii = ' a ' ; // invalid byte b ; final short s = 1 ; final Short ss = 1 ; final int i =1 ; final Integer ii = i ; final long L = 1 ; final Long LL =1L ; b = s ; // validb = ss ; // invalidb = i ; // validb = ii ; // invalidb = L ; // i...
java weird assignment rules
Java
** SOLVED **I 'm fairly new to Java and so far I love it ! So I 'm just asking if someone has a idea that could help me out . So here 's what I would like to do . What I 'm working on right now is a application that can interact with my local website ( change titles , content , etc ) . So what I like to do is show a JO...
import javax.swing . * ; import java.awt . * ; import java.awt.event . * ; import java.sql . * ; public class javaTesting extends JFrame { public JFrame mrFrame ; public int enter ; public JPanel mrPanel ; public javaTesting ( ) throws Exception { Class.forName ( `` com.mysql.jdbc.Driver '' ) ; try { Connection con = D...
Java concept idea
Java
I am studying the workings of Inner Class and inside its bytecode , I was tracing the stack and could n't understand why is the getClass ( ) called ? I found a similar question for Lambda function but could n't understand it.I did try to understand that is required for no null check , after JDK 8 it 's been replaced by...
class Outer { class Inner { } public static void main ( String args [ ] ) { Outer.Inner obj = new Outer ( ) .new Inner ( ) ; } } public static void main ( java.lang.String [ ] ) ; Code : 0 : new # 2 // class Outer $ Inner 3 : dup 4 : new # 3 // class Outer 7 : dup 8 : invokespecial # 4 // Method `` < init > '' : ( ) V ...
Why is getClass ( ) called when we create an object for Inner class ?
Java
I am trying to sort the following stringsI currently have these values in an array of strings . I am trying to have an output where if there is no `` - '' then those values go to the end of my array in a sorted order . I am trying to have an output as follows : I have tried Arrays.sort ( arrays ) but I am not sure as t...
1.0.0.0-00000000-000002.1.0.02.2.0.02.3.0.0-00000000-00000 String [ ] arrays = { `` 1.0.0.0-00000000-00000 '' , `` 2.1.0.0 '' , `` 2.2.0.0 '' , `` 2.3.0.0-00000000-00000 '' } ; 1.0.0.0-00000000-000002.3.0.0-00000000-000002.1.0.02.2.0.0 import java.util.Arrays ; import java.util.Comparator ; import java.util.Collections...
How to sort strings such that values with extra information appear first ?
Java
I 'm studing for the Java Certification 1Z0-803 and I hava a doubt about garbage collection : x is referencing the object X created at the position 1.This class X has a instance variable of the type List . If I referenced the instance variable list on x of the type X in a local variable list and then set x to null , th...
import java.util . * ; class X { List < String > list = new ArrayList < > ( ) ; } public class TestGC { // Is an Object eligible for GC even if its instance variable is references to another variable public static void main ( String [ ] args ) { X x = new X ( ) ; // 1 List < String > list = x.list ; x = null ; // 2 , I...
Is an Object eligible for GC even if its instance variable is references to another variable ?
Java
In C , the printf function has a great wildcard feature , where you can use an asterisk where you would normally place an int that specifies minimum column width . So you can goup in the preprocessor directives , and then later you can putto print myString in a 20 character column.This asterisk trick does n't seem to b...
# DEFINE COL_WIDTH 20 ; printf ( `` % *s '' , COL_WIDTH , myString ) ; printf ( `` % 20s '' , myString ) ;
Losing magic numbers in Java printf format specifiers to generate columns
Java
I have a to rewrite a part of an existing C # /.NET program using Java . I 'm not that fluent in Java and am missing something handling regular expressions and just wanted to know if I 'm missing something or if Java just does n't provide such feature.I have data likeThe Regex pattern I 'm using looks like : In .NET I ...
2011:06:05 15:50\t0.478\t0.209\t0.211\t0.211\t0.205\t-0.462\t0.203\t0.202\t0.212 ? ( \d { 4 } : \d { 2 } : \d { 2 } \d { 2 } : \d { 2 } [ : \d { 2 } ] ? ) \t ( ( - ? \d* ( \.\d* ) ? ) \t ? ) { 1,16 }
Regex Captures in Java like in C #
Java
I am trying to use Apache Sling logging in an Equinox project . It is working fine , but I ca n't make Sling to use my config file . I am using a standard logback configuration xml , which should work according to the Sling documentation . But no matter where I put the configuration file Sling just does n't use it.My l...
< ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < configuration > < appender name= '' CONSOLE '' class= '' ch.qos.logback.core.ConsoleAppender '' > < ! -- encoders are assigned the type ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -- > < encoder > < pattern > % d { dd.MM.yyyy HH : mm : ss.SSS } *...
Sling logging configuration in Equinox
Java
I 'm encountering this bizarre problem : the same code produces different results in Native Java than in Android . Given the following Inputstream ( read from a file ) Native Java prints out as expected . But in Android I got : Why does it behave differently in Android Java ? In Android , somehow the character ' ] ' is...
InputStreamReader reader = new InputStreamReader ( in , `` UTF-8 '' ) ; BufferedReader m_reader = new BufferedReader ( reader ) ; StreamTokenizer m_tokenizer = new StreamTokenizer ( m_reader ) ; m_tokenizer.nextToken ( ) ; System.out.println ( m_tokenizer.toString ( ) ) ; m_tokenizer.nextToken ( ) ; System.out.println ...
Unexpected StreamTokenizer behavior in Android
Java
The overloaded functions compute1 ( ) , compute2 ( ) , and compute5 ( ) cause compilation errors if you try to use them below : After reading the JLS section 15.12 , I think I understand ... in phase 2 ( boxing/unboxing allowed , no varargs ) of matching overloaded methods , when determining the `` most specific method...
package com.example.test.reflect ; class JLS15Test2 { int compute1 ( Object o1 , Integer i , Integer j ) { return 1 ; } int compute1 ( String s1 , Integer i , int j ) { return 2 ; } int compute2 ( Object o1 , Integer i , int j ) { return 3 ; } int compute2 ( String s1 , Integer i , Integer j ) { return 4 ; } int comput...
Java : compile-time resolution and `` most specific method ''
Java
We 've been using maven dependencies to specify the libraries so far , i.e . : However , we are now running the exact same .war file on different machines , and would like to keep the same One-war-file-to-rule-them-all , but do n't want to hit issues by using an older driver on a postgres 9.1 installation ( especially ...
< dependency > < groupId > org.hibernate < /groupId > < artifactId > hibernate-core < /artifactId > < version > 3.6.10.Final < /version > < /dependency > < dependency > < groupId > org.hibernate < /groupId > < artifactId > hibernate-c3p0 < /artifactId > < version > 3.6.10.Final < /version > < type > jar < /type > < sco...
Can one .war file be built with both 8.4 and 9.0 postgres ( hibernate ) libraries ?
Java
I wrote this line of code in eclipse mars for messing purposes : And I got the following compiler error message : Can not invoke toString ( ) on the primitive type nullWhich is very strange since null is not a primitive type nor an object reference as explained here : Is null an Object ? So , just to be sure , I tried ...
null.toString ( ) ; null.toString ( ) ; ^
Why does eclipse say that null is a primitive type ?
Java
I am currently trying to wrap my head around bitwise and bit shift operators in Java . Although they make sense to me in simplified toy examples ( basically positive integers ) , my understanding falls apart as soon as negatives are involved , and in some other cases . I tried searching all over the Internet with two s...
/** * Converts the argument to a { @ code long } by an unsigned * conversion . In an unsigned conversion to a { @ code long } , the * high-order 32 bits of the { @ code long } are zero and the * low-order 32 bits are equal to the bits of the integer * argument . */public static long toUnsignedLong ( int x ) { return ( ...
How , exactly , do bitwise operators work in Java ?
Java
As I tried to see if I could answer this question earlier today . I realized that I do n't fully understand the Event Dispatch Thread ( EDT ) . Googling both confirmed and helped with that and clarified why I do n't . ( This might also be relevant to understanding . ) The code sets up a GUI and later ( as in the earlie...
import static java.awt.EventQueue.invokeLater ; import java.awt.event . * ; import javax.swing . * ; public class Whatever { static boolean flag = true ; static JTextField tf = new JTextField ( `` Hi '' ,20 ) ; static JPanel p = new JPanel ( ) ; static JFrame f = new JFrame ( ) ; static JButton b = new JButton ( `` End...
How does ignoring the event dispatch thread allow this program to work ?
Java
I 've got an internal storage layer in my application , which handles Foo objects . During Get operations , the data layer has significant benefits to clustering gets , but I only actually do multiple gets about 10 % of the time . Here are various approaches I 've considered : Approach A : Approach B : Approach C : The...
interface FooStorage { Foo getFoo ( String name ) ; List < Foo > getFoos ( List < String > names ) ; } interface FooStorage { List < Foo > getFoos ( List < String > names ) ; } class StorageUtility { public static < T > T firstOrNull ( List < T > data ) { ... } } interface FooStorage { List < Foo > getFoos ( String ......
What 's the Ideal Way to Define Singular vs Plural Gets in a Storage API ?
Java
I 'm reading OCP Java SE7 , certification guide from Mala Gupta . On page 297 , the following code snippetis compiling with java 8 but with java 7 the compiler complains : My question is : What change in type inference algorithm causes this behavior ?
import java.util.HashMap ; import java.util.Map ; public class TestGenericTypeInference { Map < String , Double > salaryMap = new HashMap < > ( ) ; Map < String , Object > copySalaryMap = new HashMap < > ( salaryMap ) ; } TestGenericTypeInference.java:8 : error : incompatible types : HashMap < String , Double > can not...
What change in type inference algorithm causes this behavior ?
Java
I 'm exploring a Java grammar parser and I came across this strange piece of code that I would n't normally use in ordinary code . Taken from https : //code.google.com/p/javaparser/source/browse/branches/mavenized/JavaParser/src/main/java/japa/parser/ASTParser.java # 1998It has many functions that contains code such as...
final public NameExpr Name ( ) throws ParseException { NameExpr ret ; jj_consume_token ( IDENTIFIER ) ; ret = new NameExpr ( token.beginLine , token.beginColumn , token.endLine , token.endColumn , token.image ) ; label_23 : while ( true ) { if ( jj_2_17 ( 2 ) ) { ; } else { break label_23 ; } jj_consume_token ( DOT ) ;...
Uncommonly used Java syntax ( JavaParser ) ?
Java
I have a set of entities and I need to group this entities in groups called specie . The set of all species defined calls Universe and an entity must belong to one and only one specie . For this I have a boolean intransitive function called f that returns if two entities , passed by parameters , are compatible . A spec...
public class Specie { private List < Entity > individuals ; public Specie ( ) { this.individuals = new ArrayList < > ( ) ; } public boolean matches ( Entity e ) { for ( Entity s : this.individuals ) { if ( ! f ( s , e ) ) { return false ; } } return true ; } public void add ( Entity i ) { this.individuals.add ( i ) ; }...
Algorithm to find the optimal group of compatible elements
Java
I 'm having trouble fixing this problem ; it 's been plaguing me since yesterday ( sorry , I posted this earlier then deleted it because I thought I solved it but it turned out to be another bug I fixed ) . I 'm trying to simply take a list of items and a range and to find combinations that would allow all items to be ...
good : apples = 22 pears = 24 peach = 25 orange = 29 total : 100 % bad : apples = 0 pears = 0 peach = 40 orange = 60 total : 100 % // Although total is correct , the example fails because // the minimum of 20 % per item was not obeyed . private static void recursion_part ( int k , int sum , int [ ] coeff ) { //k is num...
Trouble designing recursion with limited results
Java
Is it good practice to start a thread within a thread ? I have searched around but have not found much information.I have a TimerTask which gets a list of users every day at a certain time . I then want to get some data about the user , but this requires user input . Because it requires user input , I do n't want my Ti...
class UserThread extends TimerTask { @ Override public void run ( ) { log.debug ( `` Get a list of members ! `` ) ; List < String > users = userManager.getUsers ( ) ; retrieveInitialData ( users ) ; } public void retrieveInitialData ( List < String > users ) { for ( String user : users ) { new Thread ( new GetData ( us...
Create Thread within a thread - good practice ?
Java
How would I get this data structure using Java 8 API ? This is my object structure : I 'm trying to aggregate it tofrom
class A { B b ; public A ( B b ) { this.b = b ; } } class B { List < A > as ; private int i ; public B ( int i ) { this.i = i ; } } Map < A , List < B > > bs ; List < A > as = new ArrayList < > ( ) ; as.add ( a1 ) ; as.add ( a2 ) ; as.add ( a3 ) ;
Java 8 Streams groupingBy collector
Java
I 'm trying to add log4j to a legacy software using eclipse search/replace . The idea is to find all class declarations and replace them by , the declaration itself plus the definition of the logger in the next line.search replace : How can I prepend the matched pattern ( the class definition ) to the replace string ?
`` . *class ( [ A-Z ] [ a-z ] + ) . *\ { `` `` final static Logger log = Logger.getLogger ( $ 1.class ) ; ''
How to repeat text matched by a regex ?
Java
I am new to Android and I started making my first application following tutorials and such . However , when I click the run button it gives me following error on the logcat from which I count not identify where the error is . Hence , here is my code in hope of some advice . Thanks in advance.LogCat after fixing the ren...
public class MainActivity extends AppCompatActivity { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.activity_main ) ; Button btn = ( Button ) findViewById ( R.id.btn ) ; btn.setOnClickListener ( new View.OnClickListener ( ) { @ Overr...
My first app is n't working and it crashes : UnsupportedOperationException
Java
Declaration of a character : When I do this i am getting the error 'empty character literal'.Declaration of a String : I see no error in doing that to a String.The question is , why does n't a similar error show up for the declaration of a String , or why declaration of empty character generating such error where empty...
char ch = `` ; String str = `` '' ;
Declaration of characters and Strings
Java
Java has special markers on methods called synthetic and bridge . JLS 13.1.7 , `` Any constructs introduced by a Java compiler that do not have a corresponding construct in the source code must be marked as synthetic ... '' So synthetic methods are anything generated by the compiler and not represented in the source co...
public int getHealth ( ) ; public void setHealth ( int health ) ; // Must now bepublic double getHealth ( ) ; public void setHealth ( double health ) ;
Can a synthetic or bridge method be used to smooth an int - > double API change ?
Java
I am currently taking a Data Structures class and , as you may expect , one of the things we have to do is write some of the common sorts . In writing my insertion sort algorithm , I noticed in ran significantly faster than that of my instructor 's ( for 400000 data points it took my algorithm about 30 seconds and his ...
public static int [ ] insertionSort ( int [ ] A ) { //Check for illegal cases if ( A == null || A.length == 0 ) { throw new IllegalArgumentException ( `` A is not populated '' ) ; } for ( int i = 0 ; i < A.length ; i++ ) { int j = i ; while ( j > 0 & & A [ j - 1 ] > A [ j ] ) { int temp = A [ j ] ; A [ j ] = A [ j - 1 ...
Very Strange Efficiency Quirks while Sorting
Java
I have three modules : module-a , module-b , module-c. Module-a and module-b are in boot layer . Layer for module-c I create myself.Module-a has one interface com.mod-a.Service and in its module-info I have : Module-c implements com.mod-a.Service and in its module-info I have : Module-b creates new layer with module-c ...
module module-a { exports com.mod-a ; } module module-c { requires module-a ; provides com.mod-a.Service with com.mod-c.ServiceImpl ; } module module-b { requires module-a ; requires java.management ; requires slf4j.api ; uses com.mod-a.Service ; } ModuleFinder finder = ModuleFinder.of ( moduleCPath ) ; ModuleLayer par...
How to call a service from module in a new created layer in Java 9 ?
Java
Ok , now here 's the issue . The current code above gets an x , y , z and r ( range ) . It 's job is to reference through the `` cube '' until meets a certain condition I 've set . The problem lies in the fact that it starts on the outside of the cube and progresses from 1 corner to another corner basically.I 'm lookin...
for ( int ix = x - r ; ix < x + r + 1 ; ix++ ) { for ( int iz = z - r ; iz < z + r + 1 ; iz++ ) { for ( int iy = y - r ; iy < y + r + 1 ; iy++ ) { // if ix , iy , iz = something blah blah ( this part is n't needed ) } } }
Creating a check that needs to loop outwards from the middle of 3 variables ( x y z )
Java
Consider this method ( just for illustration ) : That , of course , is not Java , but it could be in your favourite alternative language that supports collection literals , such as Groovy or Kotlin . The expression is succinct , and , just like string literals , the compiler is allowed to put the collection literal in ...
boolean isSmallNumber ( String s ) { return ( n in [ `` one '' , `` two '' , `` three '' , `` four '' ] ) ; } boolean isSmallNumber ( String s ) { return Set.of ( `` one '' , `` two '' , `` three '' , `` four '' ) .contains ( s ) ; } private static final Set < String > SMALL_NUMBERS = Set.of ( ... ) ;
Java 9 collections ' convenience factory methods as an alternative to collection literals
Java
Can someone explain why the second loop is 20x times slower than the first ( 19 ms vs 232 ms ) ? That is how I 'm timing it :
int steps = 256 * 1024 * 1024 ; int [ ] a = new int [ 2 ] ; // Loop 1for ( int i=0 ; i < steps ; i++ ) { a [ 0 ] ++ ; a [ 0 ] ++ ; } // Loop 2for ( int i=0 ; i < steps ; i++ ) { a [ 0 ] ++ ; a [ 1 ] ++ ; } long start_time = System.currentTimeMillis ( ) ; // Looplong end_time = System.currentTimeMillis ( ) ; System.out....
How does array access affect the performance ?
Java
I wanted to test the '== ' operator on Longs and this is what I 've found : the following code : outputs : The only explanation I could come up with was that the JVM stores all long values inside [ -128 , 127 ] in the Perm space , and gives their address to Longs and to everything outside the above range it creates a n...
public static void main ( final String [ ] args ) { final Long n = 0L ; final Long m = 0L ; System.out.println ( n + `` == `` + m + `` : `` + ( n == m ) ) ; final Long a = 127L ; final Long b = 127L ; System.out.println ( a + `` == `` + b + `` : `` + ( a == b ) ) ; final Long A = 128L ; final Long B = 128L ; System.out...
What 's the cause of this strange Java behavior ?
Java
When I was using adt16 in my eclipse everything was ok , but when I use adt 20 then in the package explorer it doesnt show the project names , the projects are being separated by their packages and launcher java class names likeso this is irritating , how can I get rid of it ?
Version : Indigo Service Release 1Build id : 20110916-0149 com.pack.project.javaclass
Project name doesnt show in my eclipse
Java
I have made a very simple Scala program which just prints Hello World : To understand how Scala converts to Java bytecode I decompiled the resulting jar file where there are two files : HelloWorldActivity.class and HelloWorldActivity $ .class.The first one contains this code : while the second one contains : what I ca ...
object HelloWorldActivity { def main ( args : Array [ String ] ) { println ( `` Hello , world '' ) } } import scala.reflect.ScalaSignature ; @ ScalaSignature ( bytes= '' **************** '' ) public final class HelloWorldActivity { public static void main ( String [ ] paramArrayOfString ) { HelloWorldActivity..MODULE $...
What does `` new ( ) '' do inside `` static '' and how does `` static '' alone not throw a compile/run error ?
Java
So , as I understand , one should always program to an interface , as in : So , later in my program I have : Can I follow a better pattern here or somehow do something to avoid the cast ? Casting seems very ugly in this scenario.Thanks .
List < Integer > list = new LinkedList < Integer > ( ) ; public List < Integer > getIntegers ( ) { return list ; } public void processIntegers ( ) { // I need an arraylist here ArrayList < Integer > list = ( ArrayList < Integer > ) getIntegers ( ) ; // can I do this better , without a cast ? }
Programming to an interface - avoiding the later cast
Java
I have a variation of the following code : And as you can see , my queue is not compatible with the ThreadPoolExecutor constructor . Is there any way to work around this than cast my queue to ( BlockingQueue < Runnable > ) ? I obviously ca n't patch Java Standard Library .
package com.test.package ; import java.util.concurrent.BlockingQueue ; import java.util.concurrent.PriorityBlockingQueue ; import java.util.concurrent.ThreadPoolExecutor ; import java.util.concurrent.TimeUnit ; public class TestClass { public static class MyRunnable implements Runnable { @ Override public void run ( ) ...
How can I make my generics code compatible with this method signature ?
Java
I made this recursive method that calculates the longest path in a binary tree . the path its store in an arralist and then returned . however , i had to declare the array list variable global . is it possible to make this method but his the array list variable being local.The reason i had to make it global is because ...
public static < T > ArrayList < T > longestPath ( BinaryNode < T > root ) { //ArrayList path = new ArrayList ( ) ; if ( root == null ) return null ; if ( height ( root.left ) > height ( root.right ) ) { path.add ( root.element ) ; longestPath ( root.left ) ; } else { path.add ( root.element ) ; longestPath ( root.right...
how to make a variable local
Java
This might be pretty basic , but was very curious to know . Here 's the code snippet and the outputand the outputI am interested to know what is GC collecting here since no objects are created . What 's the memory thats being freed up ? ( and that too 52kb ) @ JSauer - It gives Exactly the same results even if run 100 ...
public class PlainSystemGC { public static void main ( String ... strings ) { System.out.println ( `` Free Memory ( Before GC ) : `` + Runtime.getRuntime ( ) .freeMemory ( ) ) ; System.gc ( ) ; System.out.println ( `` Free Memory ( After GC ) : `` + Runtime.getRuntime ( ) .freeMemory ( ) ) ; } } Free Memory ( Before GC...
What is GC collecting here ?
Java
Some Android phones do n't do anything when the the code below is ran . It 's supposed to open the `` About device '' page in Settings.For example , I know for a fact that it has no effect on the Huawei Y9 Prime 2019 running Android 10.What 's the best way to safeguard against this issue when it occurs ? ( In my app , ...
startActivity ( new Intent ( Settings.ACTION_DEVICE_INFO_SETTINGS ) ) ;
Some Android phones not opening “ About device ” page in Settings ?
Java
Elaborating on this : I map a servlet or filter to `` /* '' Now , if I access a url like : Then this will be directed to the servlet ( which is okay ) But if i access a url like : This will be directed also to the servlet , I dont want this behavior , what I want is for index.jsp to be processed as jsp.How can this be ...
/test /index.jsp
Is it possible to map a servlet to /* without overriding JSP processing
Java
I have been searching for clear answers desperately and I think I kinda get it but at the same time I do n't quite get the broad concept of that keyword , static.Here 's the scenario I 've made : Why ca n't you declare a variable as static inside the static method ( or any method ) ? What does `` scope '' mean ? I know...
package oops ; public class Math { boolean notNumber = false ; static boolean notString = false ; public static void main ( String [ ] args ) { int num1 = 1 ; static int num2 = 1 ; //does n't work Math math = new Math ( ) ; math.notNumber = true ; notNumber = true ; //does n't work notString = true ; } public void what...
the concept of STATIC variables , and methods in Java