lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I 'm trying to get the MAC address of bluetooth in my android device . So I 'm using the following method : The address returned is 02:00:00:00:00:00 . I 've seen questions and posts saying that it 's not possible anymore to get your MAC address in android unless your application is a System Application.So what if I re... | BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter ( ) ; String macAddress = mBluetoothAdapter.getAddress ( ) ; | Get the MAC address of bluetooth adapter in Android |
Java | I have a problem in Eclipse . Why is the value of oldList different in LogCat while I do n't change it between the tow Log command ? First I have an initialize method : and in the going method , I printed oldList twice : but the two results is different in LogCat : While i do n't change it between the two logs . I just... | private void initialize ( ) { list [ 0 ] [ 0 ] = 2 ; list [ 0 ] [ 1 ] = 4 ; list [ 1 ] [ 0 ] = 3 ; list [ 1 ] [ 1 ] = 7 ; oldList = list ; going ( ) ; } private void going ( ) { for ( int i = 0 ; i < 2 ; i++ ) { for ( int j = 0 ; j < 2 ; j++ ) { Log.i ( `` Log '' , `` oldList = `` + oldList [ i ] [ j ] ) ; } } Log.i ( ... | incorrect variable change in java |
Java | I have the following program : I also set this system property : -Djava.security.managerMy question is the following - why sometimes I get `` End of the program ! '' written to the standard output , but sometimes I get Exception in thread `` main '' java.util.concurrent.ExecutionException : java.security.AccessControlE... | public static void main ( String [ ] args ) throws Exception { ForkJoinTask < ? > read = ForkJoinPool.commonPool ( ) .submit ( new Runnable ( ) { @ Override public void run ( ) { SecurityManager appsm = System.getSecurityManager ( ) ; if ( appsm ! = null ) { appsm.checkPermission ( new PropertyPermission ( `` os.arch '... | AccessControlException is not always thrown in threads from the common java pool |
Java | I 'm working an app that draws objects on SurfaceView under some parameters , defined by the user . I created the layout for the app , which involves an header , footer , input ( where user enters parameters to draw ) and a custom SurfaceView.Here 's the layout that simplified : The input layout generate dynamic views ... | < android.support.constraint.ConstraintLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > ... | Some layouts do n't draw when the keyboard goes down |
Java | I want to simplify existing code that is related to ImmutableList.of ( ) functionalityI alreaday tried to optimize the creation of the second List by eliminating the `` new ... '' constructor , but of course I couldnt extend a immutable list by calling .add ( ) ; Current code : Expected code like : | static final ImmutableList < ProductCodeEnum > PRODUCTS = ImmutableList.of ( ProductCodeEnum.A , ProductCodeEnum.B , ProductCodeEnum.C ) ; static final ImmutableList < ProductCodeEnum > PRODUCTS_EXTENDED_LIST = new ImmutableList.Builder < ProductCodeEnum > ( ) .addAll ( PRODUCTS ) .add ( ProductCodeEnum.D ) .add ( Prod... | Extend ImmutableList.of ( ) by another List |
Java | I 'm curious if it 's possible to use an annotation on a class or method that , during or before runtime , replaces comments with logging of the comment string . For example , if on android : would translate to something like | @ LogCommentsclass MyActivity extends Activity { @ Override public void onCreate ( Bundle b ) { super.onCreate ( b ) ; // set some local vars int a = 1 ; int b = 2 ; } } class MyActivity extends Activity { @ Override public void onCreate ( Bundle b ) { super.onCreate ( b ) ; Log.d ( `` TAG '' , `` set some local vars '... | Replace java comment with logging during or before runtime |
Java | in spring mvc ( 5.1.3 ) i 'm trying to do : and i get compilation error for the second line.from intellij ( kotlinc-jvm 1.3.11 ) : or from gradle ( kotlin 1.2.71 ) : the java source code of spring method is : intellij displays javadoc : so why the compiler still requires non-nullable type and how to bypass that require... | val url : String ? = nullval matcher : ResultMatcher = MockMvcResultMatchers.forwardedUrl ( url ) Error : ( 230 , 56 ) Kotlin : Null can not be a value of a non-null type String Type mismatch : inferred type is String ? but String was expected /** * Asserts the request was forwarded to the given URL . * < p > This meth... | kotlin wrong nullability inference without any generics |
Java | I have this code . Here the map is Map < Data , Boolean > I want to calculate mask using Java stream . Here I tried to but only get then filter list . Do n't know how calculate the mask here . | int mask = 0 ; for ( Map.Entry < Data , Boolean > entry : map.entrySet ( ) ) { if ( entry.getKey ( ) .getValue ( ) > 0 & & entry.getValue ( ) ) { mask = mask | ( 1 < < ( entry.getKey ( ) .getValue ( ) - 1 ) ) ; } } Integer mask = map.entrySet ( ) .filter ( entry - > entry.getKey ( ) .getValue ( ) > 0 & & entry.getValue... | How to calculate mask using java stream |
Java | Assume that I have Foo.class in Java : And that I have Foo `` class '' in JavaScript : Also , assume that I have Java controller that returns instance of Foo.class as a response to a REST request . In my JavaScript ( AngularJS ) code the request is sent as : And it works . But is there a way to avoid passing every prop... | public class Foo { public int id ; public String data ; } function Foo ( id , data ) { this.id = id ; this.data = data ; } $ http.get ( url + 'bar/get-foo/ ' ) .success ( function ( response ) { var foo = new Foo ( response.id , response.data ) ; logger.info ( `` SUCCESS : /get-foo '' ) ; } ) .error ( function ( error_... | Is there a way to `` expect '' instance of certain Java class in JavaScript code ? |
Java | When I try to compile the following code : I get an incompatible type error : How can I achieve having a LinkedList which contains elements that are Lists with elements that extend Number ? To be clear , I 'm looking to add lists to numList in the following fashion : numList.add ( new LinkedList < Integer > ( ) ) ; | LinkedList < List < ? extends Number > > numList = new LinkedList < List < Integer > > ( ) ; Required : LinkedList < java.util.list < ? extends java.lang.Number > > Found : LinkedList < java.util.list < Integer > > | Nested Bounded Wildcard |
Java | How can I have a type reference that refers to any object that implements a set of interfaces ? For example , I can have a generic type like this : Java : C # That 's how to have a class-wide generic type . However , I 'd like to simply have a data member which references any object that extends a given set of interfac... | public class Foo < T extends A & B > { } public class Foo < T > where T : A , B { } public class Foo { protected < ? extends A , B > object ; public void setObject ( < ? extends A , B > object ) { this.object = object ; } } | C # - How can I have an type that references any object which implements a set of Interfaces ? |
Java | I have three fields that form a unique composite key on a table.I want to pass in 3 different arrays , where the index matches.is there one sql statement that will return all three rows ( assuming they exists ) , just combining via in wo n't work to due to `` false positives '' : database oracle , but via hibernate hql... | custIds= [ 0,1,2 ] custLetters = [ A , B , C ] products = [ `` Cheese '' , '' lemons '' , '' Aubergine '' ] select * from mytable where custId in ( custIds ) and custLetters in ( custLetters ) and product in ( products ) ; | Composite key , in comparison |
Java | What are some reasons why writing the following piece of code is considered bad practice ? To me , picking an arbitrary value to sleep is not good practice , and I would use a BlockingQueue in this situation , but I 'd like to know if there is more than one reason why one should n't write such code . | while ( someList.isEmpty ( ) ) { try { Thread.currentThread ( ) .sleep ( 100 ) ; } catch ( Exception e ) { } } // Do something to the list as soon as some thread adds an element to it . | Why blocking instead of looping ? |
Java | Suppose I have the following code : Assuming that the data is not referenced anywhere else in the program , is the JVM smart enough to allow the data to be garbage collected while the long process is still running ? If not , will addingbefore the long process allow this to happen ? | public void process ( ) { byte [ ] data = new byte [ size ] ; ... // code that uses the above data longProcess ( ) ; // a very long running process that does not use the data . } data = null ; | Java Garbage Collection on Stack-Based Arrays |
Java | An algorithm that goes through all possible sequences of indexes inside an array.Time complexity of a single loop and is linear and two nested loops is quadratic O ( n^2 ) . But what if another loop is nested and goes through all indexes separated between these two indexes ? Does the time complexity rise to cubic O ( n... | for ( int i=0 ; i < N ; i++ ) { for ( int j=i ; j < N ; j++ ) { for ( int start=i ; start < = j ; start++ ) { //statement } } } | What is the time complexity of an iteration through all possible sequences of an array |
Java | I 've implemented an algorithm using single-threaded Java code . When I run my program using JIT compilation enabled it saturates all 8 cores on my machine . When I run the same program using the -Xint JVM option to disable JIT compilation it runs on a single core as expected.This is my Java version info : Why does it ... | java version `` 1.7.0_25 '' OpenJDK Runtime Environment ( IcedTea 2.3.10 ) ( 7u25-2.3.10-1ubuntu0.12.10.2 ) OpenJDK 64-Bit Server VM ( build 23.7-b01 , mixed mode ) | Does the OpenJDK JVM parallelize bytecode ? |
Java | In this program , the third string never gets printed . Why ? ( This Java program was run on Eclipse Indigo on Ubuntu 10.10 . ) | import java.io.PrintWriter ; public class Tester { static void nested ( ) { PrintWriter object2 = new PrintWriter ( System.out , true ) ; object2.println ( `` second '' ) ; object2.close ( ) ; // delete this line to make all strings print } public static void main ( String [ ] args ) { PrintWriter object1 = new PrintWr... | why does a local PrintWriter interfere with another local PrintWriter ? |
Java | In Function.class from Java8 , we have : Compose accepts : Rather than : Is there any plausible situation in which the fact that `` V '' is lower bounded matters ? | default < V > Function < V , R > compose ( Function < ? super V , ? extends T > before ) { Objects.requireNonNull ( before ) ; return ( V v ) - > apply ( before.apply ( v ) ) ; } Function < ? super V , ? extends T > before Function < V , ? extends T > before | What is the purpose of lower bounded wildcard in Function.class ? |
Java | Possible Duplicate : How to simulate constructor race conditions ? How to demonstrate race conditions around values that are n't published properly ? I got the following code from 《java concurrency in practice》 : I am just wondering the condition n ! = n , is this could be true under a certain circumstance? | public class Holder { private int n ; public Holder ( int n ) { this.n = n ; } public void assertSanity ( ) { if ( n ! = n ) throw new AssertionError ( `` This statement is false . `` ) ; } } | Can statement n ! = n returns true in multithread environment |
Java | Please consider the following code.The program will print 0,4.What I understand by this is , the method to be executed will be selected depending on the class of the actual object so in this case is Child . So when Base 's constructor is called print method of Child is called so this will print 0,4.Please tell if I und... | class Base { Base ( ) { print ( ) ; } void print ( ) { System.out.println ( `` Base '' ) ; } } class Child extends Base { int i = 4 ; public static void main ( String [ ] args ) { Base base = new Child ( ) ; base.print ( ) ; } void print ( ) { System.out.println ( i ) ; } } | Runtime polymorphism while creating base class object |
Java | I am trying to combine JavaFX , Spring Boot and VLCJ using JPMS modules . Without Spring Boot , things work fine with this in my module-info.java file : However , if I now bring Spring Boot in the mix , I updated my module-info.java to include the Spring related modules : However , I get this exception at runtime : com... | module myapplication.module { requires javafx.controls ; requires javafx.fxml ; requires javafx.web ; requires vlcj ; requires org.kordamp.iconli.core ; requires org.kordamp.ikonli.javafx ; requires org.kordamp.ikonli.fontawesome5 ; exports com.company.app ; } requires spring.beans ; requires spring.context ; requires ... | java.lang.NoSuchMethodError when using Java 9 modules ( JPMS ) |
Java | Use Bean Validation API for validate object 's for save in DB by Hibernate.With english letters all fine : When i wrote this : It 's does n't work , take error about wrong enter data ( Имя автора только из букв ) But how add russian letters in regexp ? Yes , problem in Spring form . When remove regexp and enter russian... | @ Pattern ( regexp= '' ^ [ a-zA-Z ] + $ '' , message= '' Имя автора только из букв '' ) private String name ; @ Pattern ( regexp= '' ^ [ a-zа-яA-ZА-Я ] + $ '' , message= '' Имя автора только из букв '' ) private String name ; | Bean Validation API |
Java | Ran across something that 's got me puzzled . Why am I not forced to declare `` throws Exception '' in the method signature here ? Now , if I enable the commented out line , it does force me to declare it which is what I 'd expect . I suppose this qualifies more in the Java puzzle category and it 's really bugging me t... | public static void main ( String [ ] args ) { try { System.out.println ( `` foo '' ) ; // throw new Exception ( ) ; } catch ( Exception e ) { throw e ; } } | Why am I not forced to catch Exception here ? |
Java | I 'm having a bit of trouble finding the cause of my problem . Functionality of the program is as follows ... the Server allows multiple users to log in ( connect to the server ) and edit the same string variable named text with the starting commands of either rep : ( for replace the whole string ) or app : ( to append... | import java.io . * ; import java.net . * ; import java.util . * ; public class SynchServer { public static void main ( String [ ] args ) throws IOException { ServerSocket serverSocket = null ; final int PORT = 1234 ; Socket client ; ClientHandler handler ; try { serverSocket = new ServerSocket ( PORT ) ; } catch ( IOEx... | Java 'SyncServer ' allowing two users to simultaneously to edit a string variable |
Java | I recently started writing a generic object mapper for a project and ran into something I do n't quite understand . Given the following : I get the following compilation error : I ca n't seem to figure out a way to properly cast t to make this compile . What am I missing ? Using JDK 1.6.EDIT : This is not an academic q... | public class G < X > { public G ( Class < X > c ) { } public void m ( X x ) { } public static < T > G < T > create ( Class < T > c ) { return new G < T > ( c ) ; } public static void main ( String [ ] args ) { Object o = `` '' ; // irrelevant ! G < ? > t = create ( o.getClass ( ) ) ; t.m ( o ) ; } } m ( capture # 402 o... | Java generics puzzler with generic static factory |
Java | I 'm trying to write a test for this class its called Receiver : Here is the test : Note : receiver is the instance of Receiver class ( real not mock ) , processor is the instance of Processor class ( real not mock ) which processes the person ( mock object of People class ) . GetId is a String not int method that is n... | public void get ( People person ) { if ( null ! = person ) { LOG.info ( `` Person with ID `` + person.getId ( ) + `` received '' ) ; processor.process ( person ) ; } else { LOG.info ( `` Person not received abort ! `` ) ; } } @ Test public void testReceivePerson ( ) { context.checking ( new Expectations ( ) { { receive... | Need help with writing test |
Java | So I was reading up on generics to re-familiarize myself with the concepts , especially where wildcards are concerned as I hardly ever use them or come across them . From the reading I 've done I can not understand why they use wildcards . One of the examples I keep coming across is the following.Why would you not writ... | void printCollection ( Collection < ? > c ) { for ( Object o : c ) { System.out.println ( o ) ; } } < T > void printCollection ( Collection < T > c ) { for ( T o : c ) { System.out.println ( o ) ; } } public static double sumOfList ( List < ? extends Number > list ) { double s = 0.0 ; for ( Number n : list ) s += n.dou... | Java generics : wildcards |
Java | recently I went through the inheritance concept . As we all know , in inheritance , superclass objects are created/initialized prior to subclass objects . So if we create an object of subclass , it will contain all the superclass information . But I got stuck at one point.Do the superclass and the subclass methods are ... | // Superclassclass A { void play1 ( ) { // ... . } } // Subclassclass B extends A { void play2 ( ) { // ... .. } } | Inheritance in Java |
Java | If I have class structure like that And if i create many instances of Foo , how does static field in class Bar acts ? I mean , it is the same instance for all Foo objects or for each instance there is different static field ? | public class Foo { //declaring fields and methods Foo ( int k ) { Bar.a = k ; } public class Bar { public final static int a ; } } | Static fields in inner classes |
Java | I have the code for a general case : The results are : I know there is a priority chain from high to low in Java : My understanding is below : In this code : An upcast happens . A is a parent class reference and B is a child parent class reference . When the code is compiled and run , the child parent class reference d... | public class A { public String show ( A obj ) { return ( `` A and A '' ) ; } } public class B extends A { public String show ( B obj ) { return ( `` B and B '' ) ; } public String show ( A obj ) { return ( `` B and A '' ) ; } } public class C extends B { } public class Test { public static void main ( String [ ] args )... | How does polymorphism in Java work for this general case ( method with parameter ) ? |
Java | After calling method , in below code , Below is the stack frame that I can imagine for nth ( ) method after 4 recursive calls.My question : As per the above diagram , Assuming the instance of being in activation record S5 with value of pos as 1 , I would like to understand , What happens , when java executes return thi... | node.nth ( 5 ) public class List_Node { int item ; List_Node next ; public List_Node ( ) { this.item = 0 ; this.next = null ; } public List_Node ( int item , List_Node next ) { this.item = item ; this.next = next ; } public List_Node ( int item ) { this ( item , null ) ; } public void insertAfter ( int item ) { this.ne... | Query on usage of this variable in Recursion |
Java | Following is an example invocation of the above methodCan this same functionality be implemented using a Java 8 FunctionalInterface . I have tried creating a BiPredicate but am getting compiler errors when I try this . | public static < E extends Enum < E > > boolean validateEnum ( Class < E > clazz , String s ) { return EnumSet.allOf ( clazz ) .stream ( ) .anyMatch ( e - > e.name ( ) .equals ( s ) ) ; } boolean isValid = validateEnum ( Animal.class , `` DOG '' ) ; boolean isValid = validateEnum ( Color.class , `` Red '' ) ; final BiPr... | Java8 FunctionalInterface |
Java | So , I was trying to write a method to answer one of my previous questions : How can I find out if an arbitrary java.lang.Method overrides another one ? To do that , I was reading through the JLS , and there are some parts that seem to be missing in one case.Imagine you have the following classes : In this case , it is... | public class A < T > { public void foo ( T param ) { } ; } public class B extends A < String > { public void foo ( String param ) { } ; } | Is the JLS complete regaring method overriding and generics ? |
Java | I 'm working out this problem from Programming in Java book-site ( for practice , not a HW.. Q15 in http : //introcs.cs.princeton.edu/java/13flow/ ) : Find the sum for the harmonic series 1/1 + 1/4 + 1/9 + 1/16 + ... + 1/N2 . There are 4 variants of for loops , some of them are supposed to give the right answer . My ex... | public class OneThreeExFifteen { public static void main ( String [ ] args ) { int N = 1000000 ; double s1=0 , s2 = 0 , s3 = 0 , s4=0 ; for ( int i = 1 ; i < = N ; i++ ) s1 = s1 + 1 / ( i * i ) ; // Expected s1 = 1 for ( int i = 1 ; i < = N ; i++ ) s2 = s2 + 1.0 / i * i ; // Expected s2 = 1000000 for ( int i = 1 ; i < ... | for loop debug in java - value overflow |
Java | I have a date converter function like : It works fine for Arabic dates like ٢٠١٩-٠٤-١٥ , but when I pass a normal date like 2019-07-31 , it throws an exception because the formatter is of a different type : I do n't have control over the date passed , as it is passed by the user.How can I use the same function to parse... | public static LocalDate getLocalDateFromString ( String dateString ) { DecimalStyle defaultDecimalStyle = DateTimeFormatter.ISO_LOCAL_DATE.getDecimalStyle ( ) ; DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE.withDecimalStyle ( defaultDecimalStyle.withZeroDigit ( '\u0660 ' ) ) ; LocalDate date = ... | Date parsing issue with Arabic and regular date in Java |
Java | In attempting to make some Swing code more readable , I have made an InlineGridBagConstraints class which looks like this : The intention is to change this kind of code : ... with something much easier to understand and read , like this : However , the above code is n't working . When I attempt it , all of the componen... | public class InlineGridBagConstraints extends GridBagConstraints { public InlineGridBagConstraints gridx ( int x ) { gridx = x ; return this ; } public InlineGridBagConstraints gridy ( int y ) { gridy = y ; return this ; } public InlineGridBagConstraints gridheight ( int h ) { gridheight = h ; return this ; } public In... | Why does creating an inline version of GridBagConstraints not work ? |
Java | I realize there are special classes for which this general question does n't apply , but for the simple ones , when we have multiple constructors , and the parameters of one are a clean subset of another , is it better to call the constructor with the longer list from the one with the shorter list , or vice versa ? Why... | public class A { int x ; int y ; int z ; public A ( ) { this ( 0 ) ; } public A ( int x ) { this ( x , 0 ) ; } public A ( int x , int y ) { this ( x , y , 0 ) ; } public A ( int x , int y , int z ) { this.x = x ; this.y = y ; this.z = z ; // some setup stuff needed for all A } } public class A { int x ; int y ; int z ;... | Java constructor chain direction |
Java | We have a problem with configuring lambdaj to work with Joda Time . Since LocalDate is a final class , Lambdaj needs to be initialized like following : ( see bug 70 ) Since we need this configuration to be applied virtually everywhere , we are short of options on how to implement this . Our application is a web applica... | public class LocalDateArgumentCreator implements FinalClassArgumentCreator < LocalDate > { private final long MSECS_IN_DAY = 1000L * 60L * 60L * 24L ; public LocalDate createArgumentPlaceHolder ( int seed ) { return new LocalDate ( ( long ) seed * MSECS_IN_DAY ) ; } } ArgumentsFactory.registerFinalClassArgumentCreator ... | Application-wide configuration of Lambdaj FinalClassArgumentCreators . Where and how to do it ? |
Java | I just found out that an inner class can access another inner class 's private member like this : Method foo of TestInner2 can access the private member mInt of TestInner1.But I have never see this case before . I do n't know the meaning of letting code in TestInner2 can access to the private member of TestInner1.I was... | public class TestOutter { class TestInner1 { private int mInt = 1 ; } class TestInner2 { public int foo ( TestInner1 value ) { return value.mInt ; } } } | Why inner class can access to a private member of another inner class ? |
Java | Stream.collect ( Collector < ? super T , A , R > collector ) Collectors.groupingBy ( Function < ? super T , ? extends K > classifier ) Can someone please explain the generics T , K and R ? I 'm really confused how this kind of method can conform to the signatures above : I can not see how collect can return Map < St... | < R , A > R collect ( Collector < ? super T , A , R > collector ) Performs a mutable reduction operation on the elements of this stream using a Collector . public static < T , K > Collector < T , ? , Map < K , List < T > > > groupingBy ( Function < ? super T , ? extends K > classifier ) Returns a Collector impl... | Explaining Java 8 Collector Interface/Method Signature |
Java | I 'm having trouble understanding the behavior behind the below code . Any help in understanding would be appreciated.The above code will fail with If I were to remove the second argument to each method , both bind calls would execute the first methodThe above will print `` clazz '' twice . | class Binder { < T > void bind ( Class < T > clazz , Type < T > type ) { System.out.println ( `` clazz type '' ) ; } < T > void bind ( T obj , Type < T > type ) { System.out.println ( `` obj type '' ) ; } } class Type < T > { Type ( T obj ) { } } Binder binder = new Binder ( ) ; binder.bind ( String.class , new Type < ... | Java generics ambiguous method |
Java | Am I missing something ? The source is short , ready to run and commented for better understanding . I need to know what I 'm doing wrong.In the main function I run 20 times both methods to compare . You can copy the two sections of the code and run it | package com.company ; import java.io.BufferedReader ; import java.io.FileReader ; import java.io.IOException ; import java.util . * ; public class Main { public static ArrayList < Integer > randomArrayList ( int n ) { ArrayList < Integer > list = new ArrayList < > ( ) ; Random random = new Random ( ) ; for ( int i = 0 ... | Why is my quicksort performance worse than my mergesort ? |
Java | I have some classes like below : Now I have a list of type A . What I want to do is to get a list containing other lists of type D like this : I have tried somthing like this using flatMap : But this collects all the elements of type D into a list : Can someone help please ? | Class A { private String name ; private List < B > b ; // getters and setters } Class B { private String name ; private List < C > c ; // getters and setters } Class C { private String name ; private List < D > d ; // getters and setters } Class D { // properties // getters and setters } List < List < D > > listA.strea... | How to get a List of lists using Streams in this specific case ? |
Java | I was using javap to study the code produced for one of my classes and noticed the following output : What is the meaning of those `` bogus '' type/variable entries in the locals table ? How are they caused ? What is their impact on the resulting code ? The class file was produced using the Eclipse 3.7 compiler and jav... | ... frame_type = 255 /* full_frame */ offset_delta = 11 locals = [ class Test , double , int , double , double , bogus , bogus , int , int , class `` [ D '' ] stack = [ ] ... | `` bogus '' entries in javap local table output |
Java | I am new to Java 8 , just want to ask what is the difference in performance between the two code snippets below.I know both work , but I am wondering why the Java team created Consumer : :andThen method when I can use the normal approach.//Approach 1//Approach 2IMO , approach1 is better , why approach2 again ? If both ... | List < String > list = Arrays.asList ( `` aaa '' , '' cccc '' , '' bbbb '' ) ; List < String > list2 = new ArrayList < > ( ) ; list.stream ( ) .forEach ( x - > { list2.add ( x ) ; System.out.println ( x ) ; } ) ; Consumer < String > c1 = s - > list2.add ( s ) ; Consumer < String > c2 = s - > System.out.println ( s ) ; ... | why java8 streams consumer andThen method ? |
Java | please consider following code : output : java : m ( java.lang.Number ) in inheritanceTest.B can not override m ( java.lang.Number ) in inheritanceTest.A return type int is not compatible with voidI know that static methods doe n't involve in polymorphism hence I infer that overriding is impossible for my code . This c... | class A { public static void m ( Number n ) { System.out.println ( `` Number A '' ) ; } ; } class B extends A { public static int m ( Number n ) { System.out.println ( `` Number B '' ) ; return 1 ; } ; } class Foo { public static void m ( Number n ) { System.out.println ( `` Number A '' ) ; } ; public static int m ( Nu... | Why if static method do n't involve in polymorphism ( late binding ) I see error that static method can not be overridden |
Java | Is it possible to add the numbers 1 to n recursively in Java with one return statement ? How would you change the standard solution : | public static int sum ( int n ) { if ( n == 1 ) return n ; else return n + sum ( n - 1 ) ; } | Java recursion with one return statement |
Java | Hi all I was wondering if there is a way to implement this method without casting to a wider data type ( e.g . long , double , etc ) ? For example , we could implement one for the method CanAdd ( without casts ) as such : Implementation language is Java , though of course this is more of a language-agnostic problem.I w... | CanTimes ( int a , int b ) { returns true if a * b is within the range of -2^31 to 2^31-1 , else false ; } public static boolean CanPlus ( int a , int b ) { if ( b > = 0 ) { return a < = Integer.MAX_VALUE - b } else { return a > = Integer.MIN_VALUE - b } } public static boolean CanTimes ( int a , int b ) { if ( a == 0 ... | Is there an algorithm to decide if a * b fits within the possible values of an integer ? ( without casting to a wider type ) |
Java | I 'm trying to write my own ServerAuthModule , to use a custom login system . If I understood everything right , what happens is that the container calls the validateRequest method for every incoming request , and that my SAM will check for credentials , and tell the container the username and groups of the user ( if t... | public class MySAM implements ServerAuthModule { @ Override public AuthStatus validateRequest ( MessageInfo messageInfo , Subject clientSubject , Subject serviceSubject ) throws AuthException { // check user credentials ... // set username and groups CallerPrincipalCallback cpCallback = new CallerPrincipalCallback ( cl... | Is it possible to determine group membership of a user on demand instead of when logging in in ServerAuthModule ( JASPIC ) |
Java | I have some text that is only being parsed by a DateTimeFormatter when the parse style is Strict - and not when it 's Lenient.This seems like the opposite behaviour to what I 'd expect ? Example : Output : | String pattern = `` ddMMyyHH : mm : ss '' ; String text = `` 02011104:21:32 '' ; System.out.println ( MessageFormat.format ( `` Strict - { 0 } '' , new DateTimeFormatterBuilder ( ) .parseStrict ( ) .appendPattern ( pattern ) .toFormatter ( ) .parse ( text ) ) ) ; System.out.println ( MessageFormat.format ( `` Lenient -... | DateTimeFormatter - Strict vs Lenient unexpected behaviour |
Java | I have a reproducible test case : Using Java 8 , update 51 ( Oracle JDK ) . This ca n't be compiled , using both IntelliJ and javac.IntelliJ output : javac output : Now what is strange , is that removing return ; or the Consumer will fix the error . Is this a java bug , or is there something of the language design that... | public class TestCase { private final java.util.function.Consumer < Object > emptyCallback = result - > { } ; public TestCase ( ) { return ; } public static void main ( String ... args ) { new TestCase ( ) ; } } Error ( 6 , 7 ) : java : variable result might not have been initialized TestCase.java:6 : error : Variable ... | Why does an empty lambda and constructor with an explicit return cause a compiler error ( Java Bug ? ) |
Java | Java 9 introduced the concept of modules , which do not explicitly replace jar files , but the old -- classpath option seems to be gone.The command javac -- help no longer mentions the classpath.I am trying to compile some student work against JUnit : But I get a variety of errors , depending on what I try . For the ex... | > javac *.java -- classpath junit.jar javac : invalid flag : -- classpath > java -- versionjava 9Java ( TM ) SE Runtime Environment ( build 9+181 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 9+181 , mixed mode ) javac -classpath `` C : \Program Files\JetBrains\IntelliJ IDEA 2017.2.5\plugins\junit\lib\junit-jupiter-ap... | How do you compile against a jar file in Java 9 ? |
Java | When you load a bitmap from the resources like so : if the bitmap is reduced in quality by Scaletype , does it still save the whole original bitmap ? ( I would guess yes , because one could change the Scaletype on the fly and you would want to have the full quality . ) if you load the same resources ID into multiple Im... | iv.setImageResource ( R.drawable.image ) ; | Android Resources : How are bitmaps loaded from resources handled memory wise ? |
Java | I have found some strange code , where I said `` This is never called , because it would throw a class cast Exception '' . Well the code gets called and its working.Can anybody explain me : Why is this working ? The method getZipList ( ) is defined to return a List of Strings , but the internal Logic is returning a Lis... | public class GenericMethodList { public static void main ( String [ ] args ) { GenericMethodList o = new GenericMethodList ( ) ; List < String > list = o.getZipList ( true ) ; Iterator < ? > iter = list.iterator ( ) ; while ( iter.hasNext ( ) ) { ZipCode zipplace = ( ZipCode ) iter.next ( ) ; System.out.println ( zippl... | Java generic method returns different type - no exception |
Java | So I 'm currently working on a program that needs to be able to deal with a large amount of data stored in arrays and it needs a method to clear out everything in the array . For the below example , would this be a bad thing to do memory wise ? I know the garbage collector would eventually clean it up for you but is th... | Object [ ] objArray = new Object [ n ] ; /*Do some stuff with objArray*/objArray = new Object [ n ] | Is it bad practice to assign a new array to an existing array to 'clear ' the array in Java ? |
Java | How would you get a reference to an executing class several stack frames above the current one ? For example , if you have : Is there a way to get the value that would be retrieved by using 'this ' in foo ( ) while the thread is executing bar ( ) ? | Class a { foo ( ) { new b ( ) .bar ( ) ; } } Class b { bar ( ) { ... } } | Java : Retrieve this for methods above in the stack |
Java | I have been trying to figure out a way to tag several methods from my base class , so that a client class can call them by tag . The example code is : A client class from a main ( ) method will call each method of Base through a random instruction sequence : Now I wish to get rid of the switch statement altogether from... | public class Base { public void method1 ( ) { ..change state of base class } public void method2 ( ) { ..change state of base class } public void method3 ( ) { ..change state of base class } } public static void main ( String [ ] args ) { String sequence = `` ABCAABBBABACCACC '' Base aBase = new Base ( ) ; for ( int i ... | tagging methods and calling them from a client object by tag |
Java | Determine the output : I know that the answer is 1 , and I 'm guessing that it 's because since the print function is n't overridden in the ChildClass , it has the same definition as it has in the ParentClass . Why is n't the ID the one given in child class since Java uses late binding ? | public class Test1 { public static void main ( String args [ ] ) { ChildClass c = new ChildClass ( ) ; c.print ( ) ; } } class ParentClass { int id = 1 ; void print ( ) { System.out.println ( id ) ; } } class ChildClass extends ParentClass { int id = 2 ; } | Java Inheritance and late binding , why does int id have the parent class value and not the child class one ? |
Java | OK when doing a deep copy obviously references should not be copied . However , if the object being copied contains objects that themselves are references to to the same object should that be maintained or should the data just be copied.ExampleI can see arguments for both but I am wondering what the consensus was . | public class Program ( ) { public void Main ( String [ ] args ) { Person person = new Person ( ) ; person.setName ( `` Simon '' ) ; List < Person > people = new ArrayList < Person > ( ) ; people.add ( person ) ; people.add ( person ) ; people.add ( person ) ; List < Person > otherPeople = magicDeepCopyFunction ( people... | How should Deep Copy Work ? |
Java | I have a simple java method that returns colors based on the HSB value converted from an RGB . It works ( needs some tweaking ) , but I use a series of else if and nested if statements to return the data I want . I had heard that HashMaps and String Factories were better , but I could n't see how these worked with rang... | public static String getColorName ( ) { getHSB ( rgb ) ; if ( hsbH > = 45 & & hsbH < 75 ) { if ( hsbS > 0 & & hsbS < 45 & & hsbB > 70 ) { return `` White/Off White '' ; } else if ( hsbS > 0 & & hsbS < 45 & & hsbB < 10 ) { return `` Dark Yellow '' ; } else { return `` Yellow '' ; } } else if ( hsbH > = 15 & & hsbH < 45 ... | Better solution than else if with ranged data |
Java | I have two similar methods . One of them prints something and one of them save somethings . As you can see there are a lot of duplicate code . How should I refactor it and remove this duplication ? UPDATE : Code was updated to solve problem when method are not exactly similar | public static void printSomething ( List < String > list ) { for ( String item : list ) { if ( item.contains ( `` aaa '' ) ) { System.out.println ( `` aaa '' + item ) ; } if ( item.contains ( `` bbb '' ) ) { System.out.println ( `` bbb '' + item ) ; } else { System.out.println ( item ) ; } } } public static Map < Strin... | How to remove duplication from my code |
Java | Consider this HashMap extention ( generates an instance of the V class when calling `` get '' if it 's null ) The usage of it is something like this It seems to me redundant a little to supply `` Section '' twice , once as a generic type , and also supply it 's class . I assume it 's impossible , but is there to implem... | public class HashMapSafe < K , V > extends HashMap < K , V > implements Map < K , V > { private Class < V > dataType ; public HashMapSafe ( Class < V > clazz ) { dataType = clazz ; } @ SuppressWarnings ( `` unchecked '' ) @ Override public V get ( Object key ) { if ( ! containsKey ( key ) ) { try { put ( ( K ) key , da... | Is there a way to avoid the constructor passing the Class ? |
Java | I have a list of elements , and want to extract the value of the fields ' propery.Problem : all elements should have the same property value.Can I do better or more elegant than the following ? Is this possible directly using the stream methods , eg using reduce ? | Set < String > matches = fields.stream ( ) .map ( f - > f.getField ( ) ) .collect ( Collectors.toSet ( ) ) ; if ( matches.size ( ) ! = 1 ) throw new IllegalArgumentException ( `` could not match one exact element '' ) ; String distrinctVal = matches.iterator ( ) .next ( ) ; //continue to use the value | How to extract only one allowed element from a stream ? |
Java | I 've set 1500 as initialTimeoutMs in DefaultRetryPolicy as below but it does n't consider the timeout : I disconnected the WiFi on my device to test it 's timeout and I saw these times in the Logcat : It took more than 20 seconds while I expected to catch either onResponse or onError after 1.5 seconds ! ! ! | request.setRetryPolicy ( new DefaultRetryPolicy ( 1500 , DefaultRetryPolicy.DEFAULT_MAX_RETRIES , DefaultRetryPolicy.DEFAULT_BACKOFF_MULT ) ) ; 2019-12-16 14:28:15.892 I/MyClass : request sent2019-12-16 14:28:35.930 I/MyClass : request caught onError | Volley request retry policy does n't consider timeout |
Java | Is below interface a valid functional interface in Java 8 ? Why does n't it give me a compile time error ? | @ FunctionalInterfaceinterface Normal { public abstract String move ( ) ; public abstract String toString ( ) ; } | Why is there no compile error for my @ FunctionalInterface with two methods ? |
Java | I am studying for the Java OCP certificate . I am taking mock exams to prepare.Example program : the authors of the OCA/OCP Jave SE 7 Study Guide maintain that the execution : will produce the outputHowever , when I run the code from Eclipse or test it on an outside source , I getAm I missing something here , or is it ... | public class Quetico { public static void main ( String [ ] args ) { Pattern p = Pattern.compile ( args [ 0 ] ) ; Matcher m = p.matcher ( args [ 1 ] ) ; while ( m.find ( ) ) { System.out.println ( m.start ( ) + `` `` ) ; } System.out.println ( `` '' ) ; } } java Quetico `` \B '' `` ^23 * $ 76 bc '' 0 2 4 8 0 2 4 5 7 10 | Metacharacter \B matches ( OCP exam ) |
Java | Here is my class : When I use maven to build , it will give a compilation error : [ ERROR ] /Users/finup/Desktop/a/importtest/src/main/java/pepelu/ImportTest.java : [ 8,6 ] can not find symbolAfter changing the import order to : I got a successful maven build.I searched for documents , but can not find an explain for t... | package pepelu ; import pepelu.ImportTest.InnerClass.InnerEnum ; import javax.annotation.Resource ; public class ImportTest { @ Resource public static class InnerClass { public enum InnerEnum { A } } public static void main ( String [ ] args ) { System.out.println ( InnerEnum.A ) ; } } mvn clean compile import javax.an... | Java how import order matters when import class/enum inner an inner class |
Java | Say I am making a command-line interface . I want to print out a string , and then change it . For example , when you run the program , it prints outA few seconds later , though , the message gets changed to : Is this possible ? Cross-OS would be preferable . | Hello , World ! Hello , Computer User ! | Is it possible to recall a println in Java ? |
Java | Here is the SQL version for the input and output : As 5 is non repeated.How do i implement it using JAVA 8 streams ? I tried below but obviously it is giving wrong result | with tab1 as ( select 1 as id from dual union all select 1 as id from dual union all select 2 as id from dual union all select 2 as id from dual union all select 5 as id from dual ) select id from tab1 group by id having count ( id ) =1 ; Output is Id=5 and count is 1 List < Integer > myList = new ArrayList < Integer >... | Java 8 Streams : get non repeated counts |
Java | This way of initializing static final variable A works okay . This way gives compile error `` Can not assign a value to final variable ' A'.Why ? | public class Test { private static final int A ; static { A = 5 ; } } public class Test { private static final int A ; static { Test.A = 5 ; } } | Initializing static final variables in java |
Java | After an update of our application we now use the Camera2 API , unfortunately the preview is streched on our test device : Samsung SM-J330F/DS , Android-Version 8.0.0 , API 26Because we do n't experience this problem with Googles Camera2Basic project on the same device , we tried to adjust our project to use the same t... | mMainLayout = new FrameLayout ( this ) ; mMainLayout.setBackgroundColor ( Color.BLACK ) ; mMainLayout.setLayoutParams ( new LayoutParams ( LayoutParams.MATCH_PARENT , LayoutParams.MATCH_PARENT ) ) ; mPreview = new AutoFitTextureView ( this ) ; mPreview.setLayoutParams ( new FrameLayout.LayoutParams ( LayoutParams.MATCH... | Preview streched in Camera2 API when creating layout programmaticaly |
Java | I have a block of code that I am having an issue reducing the cyclomatic complexity of . Because of the multiple conditions that have to match , I am not sure the best way to break it down further . Complicating matters is that in 2 of the cases a new object is created , but not in the third ( it calls out to another m... | if ( ! cond3 & & ! cond1 & & cond2 & & cond4 ) { // actions to perform calculateValues ( ) ; return result ; } else if ( ! cond1 & & cond2 & & cond3 ) { // actions to perform Object result = new Result ( ) ; return result ; } else if ( ! cond4 & & cond3 & & cond1 & & cond5 ) { // actions to perform Object result = new ... | Cyclomatic Complexity reduction |
Java | I have the following code.. Now when I run this program , the OPs are : My question : how is it that the time taken for execution is `` 0 '' ? ? .. If the compiler does some optimization , then why does n't it do it always ? . I think the `` 0 '' is because that statement wasnt executed by the compiler . | public static void main ( String [ ] args ) { int i = 1234 ; int j = 1234 ; int k = 4321 ; long l1 = System.nanoTime ( ) ; if ( i == j ) { System.out.println ( `` equal '' ) ; } System.out.println ( System.nanoTime ( ) - l1 ) ; l1 = System.nanoTime ( ) ; if ( i ! = k ) { System.out.println ( `` equal '' ) ; } System.ou... | Code optimization by compiler in Java- Time taken for execution of `` if '' condition is Zero |
Java | During a 45 minute technical interview with Google , I was asked a Leaper Graph problem.I wrote working code , but later was declined the job offer because I lacked Data structure knowledge . I 'm wondering what I could have done better . The problem was as following : '' Given an N sized board , and told that a piece ... | static boolean reachable ( int i , int j , int n ) { boolean grid [ ] [ ] = new boolean [ n ] [ n ] ; reachableHelper ( 0 , 0 , grid , i , j , n - 1 ) ; for ( int x = 0 ; x < n ; x++ ) { for ( int y = 0 ; y < n ; y++ ) { if ( ! grid [ x ] [ y ] ) { return false ; } } } return true ; } static void reachableHelper ( int ... | Optimize Leaper Graph algorithm ? |
Java | I 've been using several methods of calling methods . More recently , I 've been using a static instance of a class , I do believe that 's the proper term for it ( please correct me if I 'm wrong ) . Which is better ( or even suggest ideas ) , and why ? The first way I was the simple old static methods.The second way (... | static void exampleMethod1 ( ) { } static void exampleMethod2 ( ) { } public class ExampleClass { public static ExampleClass instance ; public ExampleClass ( ) { instance = this ; } public static ExampleClass getInstance ( ) { return instance ; } void exampleMethod1 ( ) { //code } void exampleMethod2 ( ) { //code } // ... | Is it better to have a single instance of a class , or simply have a bunch of static methods ? |
Java | I 've got a rather large java ee application with a huge classpath doing a lot of xml processing . Currently I am trying to speed up some of my functions and locating slow code paths via sampling profilers.One thing I noticed is that especially parts of our code in which we have calls like TransformerFactory.newInstanc... | private static < T > T findServiceProvider ( final Class < T > type ) throws TransformerFactoryConfigurationError { try { return AccessController.doPrivileged ( new PrivilegedAction < T > ( ) { public T run ( ) { final ServiceLoader < T > serviceLoader = ServiceLoader.load ( type ) ; final Iterator < T > iterator = ser... | FactoryFinder performance/bad caching |
Java | I came across this question today , and am not sure whether they 'll be closed , since it 's wrapped , or if it is still necessary to close all streamsindependently . | private InputStream input ; private InputStreamReader inputReader ; private BufferedReader reader ; try { input = new InputStream ( ) ; inputStreamReader = new InputStreamReader ( inputStream ) ; reader = new BufferedReader ( inputStreamReader ) ; // do I/O operations } catch ( IOException e ) { Log.d ( `` IOException ... | Do I have to explicity close all streams , if they 're wrapped in a buffer via java ? |
Java | DateTimeFormatter is not giving correct format for Dec 30 and 31 2018 as per following snippet . Is this the expected behavior or is there a bug with DateTimeFormatter ? | final String DATE_FORMAT = `` YYYYMM '' ; DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern ( DATE_FORMAT ) ; LocalDateTime startDate = LocalDateTime.of ( 2018,12,29,5,0,0 ) ; System.out.println ( startDate.format ( dateFormat ) ) ; //prints 201812LocalDateTime startDate = LocalDateTime.of ( 2018,12,30,5,0,0 )... | DateTimeFormatter giving wrong format for edge cases |
Java | I 'm developing a service that monitors computers . Computers can be added to or removed from monitoring by a web GUI . I keep reported data basically in various maps like Map < Computer , Temperature > . Now that the collected data grows and the data structures become more sophisticated ( including computers referenci... | public void onRemove ( Computer computer ) { temperatures.remove ( computer ) ; // ... } Map < Computer , Temperature > temperatures = new WeakHashMap < > ( ) ; | Simulating DELETE cascades with WeakHashMaps |
Java | We are using Elasticsearch 0.90.7 in our Scala Play Framework application , where the end of our `` doSearch '' method looks like : where ListenableActionFuture extends java.util.concurrent.Future , and ListenableActionFuture # actionGet is basically the same as Future # getThis all works fine when we execute searches ... | def doSearch ( ... ) = { ... val actionRequessBuilder : ActionRequestBuilder // constructed earlier in the method val executedFuture : ListenableActionFuture < Response > = actionRequestBuilder.execute return executedFuture.actionGet } val search1 = scala.concurrent.Future ( doSearch ( ... ) ) val search2 = scala.concu... | Scala and Java futures apparently having unexpected interactions |
Java | Why does this code compile with explicit static field notation on the right hand side , but not without ? | public class A { static int a = ++A.a ; // compiles //static int a = ++a ; // error - can not reference a field before it is defined public static void main ( String [ ] args ) { System.out.println ( a ) ; } } | Why does static field self assignment compile only with explicit static syntax ? |
Java | This question is related to but it is different in understanding how the code actually works . More precisely , I do not understand how numberOfTrailingZeros ( int i ) in java 8 here compute the final result . The code is as followsNow I understand the purpose of the shift operations from 16 to 2 , but wo n't n have al... | public static int numberOfTrailingZeros ( int i ) { // HD , Figure 5-14 int y ; if ( i == 0 ) return 32 ; int n = 31 ; y = i < < 16 ; if ( y ! = 0 ) { n = n -16 ; i = y ; } y = i < < 8 ; if ( y ! = 0 ) { n = n - 8 ; i = y ; } y = i < < 4 ; if ( y ! = 0 ) { n = n - 4 ; i = y ; } y = i < < 2 ; if ( y ! = 0 ) { n = n - 2 ... | How does Integer.numberOfTrailingZero ( int i ) work ? |
Java | Note : I 'm not asking the age-old question about why outer variables accessed in an anonymous class need to be declared final.When creating an anonymous class in Java , you can add additional methods if you desire : However , Java also allows you to declare the additional methods as final : My question is : Are n't th... | Runnable r = new Runnable ( ) { public void run ( ) { internal ( ) ; } public void internal ( ) { .. code .. } } ; public final void internal ( ) { ... } | Does adding the 'final ' keyword to methods in anonymous classes have any effect ? |
Java | I am trying to understand Java 's String class but I am having a hard time understanding the situation described below.Consider the following example snippet : If I use bool = y == x.intern ( ) ; the variable bool will equal true.My question is : When I make a declaration like this : x 's value would be false but when ... | String x = new String ( `` Hey '' ) ; String y = `` Hey '' ; String b = `` h '' ; String a = b.intern + `` ey '' ; boolean x = a == `` hey '' ; | Using intern in java Strings |
Java | Could you please explain why below work in a way is does.It seems to me the java type system is weak to infer the type of R | public class Test { interface Parser < A , R > { R parse ( A a ) ; } static class ResponseParser implements Parser < String , Integer > { public Integer parse ( String s ) { return Integer.parseInt ( s ) + 1 ; } } interface Function < A , R > { R with ( A a ) ; } public static < A , R , P extends Parser < A , R > > Fun... | Type inference in java |
Java | By analyzing a problem I 'm trying to understand this strange stack trace : Based on the stack trace , AbstractQueuedSynchronizer calls Apache HTTP client . How could this happen ? We are running Oracle Java 1.8 on Amazon LinuxAnd I have a lot of threads with exactly the same stacktrace . Anytime.Later Edit : renamed f... | Thread 3049 : ( state = BLOCKED ) - java.lang.Object.wait ( long ) @ bci=0 ( Compiled frame ; information may be imprecise ) - java.io.PipedInputStream.read ( ) @ bci=142 , line=326 ( Compiled frame ) - java.io.PipedInputStream.read ( byte [ ] , int , int ) @ bci=43 , line=377 ( Compiled frame ) - org.apache.http.entit... | Inconceivable stack trace |
Java | I have a string like that ( $ character is always surrounded with other characters ) : I want my string method to put a \ in front of $ and remove newlines : I tried this but it does n't put \ character : | a $ bc $ de $ f a\ $ bc\ $ de\ $ f s=s.replaceAll ( `` \n '' , '' '' ) .replaceAll ( `` $ '' , `` \\ $ '' ) ; | Java string replacing ( remove newlines , change $ to \ $ ) |
Java | Based on the description of SerialVersionUID here : https : //docs.oracle.com/javase/8/docs/platform/serialization/spec/class.html # a4100 , it seems necessary to always include SerialVersionUID in any classes you create so that a JVM used for serialization and a different JVM used for deserialzation wo n't automatical... | Map < Integer , String > myMap = new HashMap < > ( ) ; public class NewClass implements Serializable { private static final long serialVersionUID = 1L ; private final Map < Integer , String > myMap ; public NewClass ( ) { this.myMap = new HashMap < > ( ) ; } } | SerialVersionUID in the Java standard library across different JVMs |
Java | I 'm working on a transcript project for school , and it 's compiling as if there 's an anonymous inner class , but I have n't written any . Why is javac compiling an inner class without there being any inner classes ( including enums or exceptions ) written ? The file in question is SemesterInfo $ 1.class , compiled f... | 02/20/2016 02:03 PM 915 AddResult.class02/15/2016 09:16 PM 848 AddResult.java02/20/2016 02:03 PM 1,032 Console.class02/05/2016 08:27 AM 1,315 Console.java02/20/2016 02:03 PM 1,624 CourseInfo.class02/19/2016 10:56 AM 9,203 CourseInfo.java02/20/2016 02:03 PM 2,244 CourseInfoTester.class02/17/2016 05:15 PM 2,226 CourseInf... | Mystery of the Hidden Java Inner Class That Does n't Exist |
Java | I 'm trying to solve an interview problem I was given a few years ago in preparation for upcoming interviews . The problem is outlined in a pdf here . I wrote a simple solution using DFS that works fine for the example outlined in the document , but I have n't been able to get the program to meet the criteria ofYour co... | package analyzer.block.geo.main ; import analyzer.block.geo.model.Geo ; import analyzer.block.geo.result.GeoResult ; import java.awt . * ; import java.io.BufferedReader ; import java.io.FileNotFoundException ; import java.io.IOException ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.time.LocalD... | How can I improve this search algorithms runtime ? |
Java | I have a method params is a list which is lager than 50000 items ; Limited to the business logic , the list must less than 30000 , so that I have a method to split this array to 2d array before the logicThis is my current solution : I would like to create an annotation on top of the method instead of many duplicate cod... | public static final < T > Collection < List < T > > partitionBasedOnSize ( List < T > inputList , int size ) { AtomicInteger counter = new AtomicInteger ( 0 ) ; return inputList.stream ( ) .collect ( Collectors.groupingBy ( s - > counter.getAndIncrement ( ) / size ) ) .values ( ) ; } public List < Account > getChildren... | How to create a customisation annotation for splitting request param and collect return result ? |
Java | In a Java loop , is it more efficient to use a boolean flag instead of an if statement ? Take a look at these two bits of code.Using a flag : Using an if statement : The method with the if statement is of course faster if isSomething ( ) return true on the first iteration . But , is it faster on average or does the bra... | public boolean isSomethingForAnyone ( ) { boolean flag = false ; for ( Item item : listOfItems ) { flag = flag || item.isSomething ( ) ; } return flag ; } public boolean isSomethingForAnyone ( ) { for ( Item item : listOfItems ) { if ( item.isSomething ( ) ) return true ; } return false ; } | Is it more efficient to use a flag or an if clause ? |
Java | I have just thrown everything I know about Java optimisation out the window . I have the following task : Given a 2D array representing a playing field and a position on the field , fill another array with the number of steps a player can make to get to every other position in the field . The player can move up , down ... | private void fillCounterArray ( int [ ] counters , int position ) { Queue < Integer > queue = new ArrayDeque < Integer > ( 900 ) ; // Obtain the possible destinations from position , check the valid ones // and add it the stack . int [ ] destination = board.getPossibleDestinations ( position ) ; for ( int i = 0 ; i < d... | Unexpected Java performance |
Java | I am reading through the following section in the Java tutorial : http : //docs.oracle.com/javase/tutorial/java/generics/capture.htmlIt starts off by saying that the following code produces an error due to the fact that a capture can not be converted to an Object so the set method can not confirm that Object is of type... | import java.util.List ; public class WildcardError { void foo ( List < ? > i ) { i.set ( 0 , i.get ( 0 ) ) ; } } public class WildcardFixed { void foo ( List < ? > i ) { fooHelper ( i ) ; } // Helper method created so that the wildcard can be captured // through type inference . private < T > void fooHelper ( List < T ... | Java Generics Wildcard vs Typed Generics usage |
Java | The business model is a bit complex , so please forgive me if the explanation is n't 100 % clear : The Uploader interface ( String upload ( String path , byte [ ] fileContents ) ) defines different ways to upload a file ( contained in the byte array ) , for example AmazonUploader which takes the content and the path st... | @ Overridepublic String upload ( String path , byte [ ] fileContents ) { final File file = new File ( path ) ; try { FileUtils.writeByteArrayToFile ( file , fileContents ) ; } catch ( IOException e ) { throw new RuntimeException ( `` Error writing file to path `` + path , e ) ; } return `` '' ; } # ! /bin/bashCONFIGDIR... | How to make sure file is created with the correct user or permissions ? |
Java | Question summary - How do I convert this to a Scala class ? Issue - Multiple constructors calling different super constructorsJava class - I have been trying to convert these constructors for this class to scala for about a day and I can not make any headway on how to deal with the following issue - ( Multiple construc... | public class ClassConstExample extends BaseClassExample { private String xyzProp ; private string inType = `` def '' ; private String outType = `` def '' ; private String flagSpecial = `` none '' ; public ClassConstExample ( final String file , final String header , final String inType , final String outType , final St... | Converting Java to Scala , how to deal with calling super class constructor ? |
Java | QuestionWhat is the most efficient way to create additional threads from a thread ? ContextI am redesigning an application to be more efficient . One of the largest improvements will be running concurrent operations ; however I am new to concurrent programming . The scenario I am looking to improve is as follows : We h... | MP |- > RT |- > RT |- > RT |- > RTMP |- > RT |- > RT ... | What is the most efficient way to create additional threads from a thread ? |
Java | I am working in Selenium , and this question is more specific to Java rather than Selenium.The example I am providing is Selenium WebDriver ExplicitWait , What he is exactly Doing ? How he is writing Logic without Assigning a Reference to an object to the class ExpectedCondition ? ? ? Thanks . | new ExpectedCondition < WebElement > ( ) { @ Override public WebElement apply ( WebDriver d ) { return d.findElement ( By.id ( `` myDynamicElement '' ) ) ; } } ) ; | What is this actually in Java ? |
Java | I have a method which is calculating nutrients for a list of object which we are receiving from API request call.The method looks like : My FoodNutritional.class looks like : My solution in method works but I started thinking If it is possible to rid off this sum stream method boilerplate for this approach . All I want... | public Nutrients nutrientsCalculator ( DailyMeals dailyMeals ) { String foodNamesForRequest = prepareFoodNamesForRequest ( dailyMeals ) ; HttpEntity < NutrientsBodyForRequest > requestBody = prepareRequestForAPICall ( foodNamesForRequest ) ; ResponseEntity < List < FoodNutritional > > response = //create request here i... | How to sum up the individual fields of the object list and return the results as a single object |
Java | I have List object and I need to take the first element on the list if it is not null or empty . I write below code using java and now I want to convert it to Java 8.I convert it like this . I need to know this is correct ? | List < DD > container A < DD , DI > a ; if ( container ! =null || ! container.isEmpty ( ) ) { for ( DD dd : container ) { a = dd.getPrescription ( ) ; break ; } } DD detail = container.stream ( ) .findFirst ( ) .get ( ) ; | How to convert following method to java 8 ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.