lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | This is the second time I found myself writing this kind of code , and decided that there must be a more readable way to accomplish this : My code tries to figure something out , that 's not exactly well defined , or there are many ways to accomplish it . I want my code to try out several ways to figure it out , until ... | Method candidateMethod = getMethodByAnnotation ( clazz ) ; if ( candidateMethod == null ) { candidateMethod = getMethodByBeingOnlyMethod ( clazz ) ; } if ( candidateMethod == null ) { candidateMethod = getMethodByBeingOnlySuitableMethod ( clazz ) ; } if ( candidateMethod == null ) { throw new NoSuitableMethodFoundExcep... | Letting the code try different things until it succeeds , neatly |
Java | I was playing around with generics and found that , to my surprise , the following code compiles : I would expect T to be inferred to B . A does not extend B . So why does n't the compiler complain about it ? T seems to be inferred to Object , since I can pass a Generic < Object > as well.Moreover , when actually runni... | class A { } class B extends A { } class Generic < T > { private T instance ; public Generic ( T instance ) { this.instance = instance ; } public T get ( ) { return instance ; } } public class Main { public static void main ( String [ ] args ) { fArray ( new B [ 1 ] , new Generic < A > ( new A ( ) ) ) ; // < -- No error... | Why is n't java typesafe when inferring array types ? |
Java | For my flow chart I generate three different agents via different sources . Now I want to handle them differently in diverse blocks in the flow chart . For instance , I want to have a different delay time for the agents . Since I am new to AnyLogic and not that good with Java , I have problems to understand how to hand... | if ( agent.TypeComponent == `` blade '' || agent.TypeComponent == `` narcelle '' ) return uniform ( 3.5 , 6 ) ; else return uniform ( 1 , 3 ) ; | How can I handle different materials in one flowchart in Anylogic ? |
Java | I ran into some strange behaviour of Java generics today . The following code compiles fine and works as you would expect : but if you change the type of the variable generic to GenericClass ( note no type parameters ) compilation fails with the message `` incompatible types : java.lang.Object can not be converted to j... | import java.util . * ; public class TestGeneric { public static void main ( String [ ] args ) { GenericClass < Integer > generic = new GenericClass < Integer > ( 7 ) ; String stringFromList = generic.getStringList ( ) .get ( 0 ) ; } static class GenericClass < A > { private A objA ; private List < String > stringList ;... | Strange generics behaviour . Being erased early ? |
Java | Using vaadin ( 7.7.3 ) I 'm filtering a grid by name , this filtering takes a couple seconds to remove the objects from the Grid gui . And so , if I click on that timelapse a row of the Grid which is removed from the Container , it raises an exception : I guess this is normal because it removes the objects from the Con... | Caused by : java.lang.IllegalArgumentException : Given item id ( 5422bef6-e472-4d3e-af54-316c52d373da ) does not exist in the containerat com.vaadin.ui.Grid $ AbstractSelectionModel.checkItemIdExists ( Grid.java:1371 ) at com.vaadin.ui.Grid $ SingleSelectionModel.select ( Grid.java:1460 ) at com.vaadin.ui.Grid $ Single... | How to catch an exception when filtering a vaadin grid |
Java | My original question used FileNotFoundException and IllegalStateException and therefore they are included in the answer . I have changed them to their superclasses IOException and RuntimeException respectively for simplicity.This compiles ( not using ternary , 1 checked , 1 unchecked ) : This also compiles ( using tern... | private void test ( ) throws IOException { // throws is required if ( new Random ( ) .nextInt ( 2 ) ==0 ) throw new IOException ( ) ; throw new RuntimeException ( ) ; } private void test3 ( ) { // throws not required throw new Random ( ) .nextInt ( 2 ) ==0 ? new UncheckedIOException ( null ) : new RuntimeException ( ) ... | Using Ternary Operator to Throw Checked or Unchecked Exceptions |
Java | I used to think was a reliable way to determine whether the shell that launched my Java application was interactive or not . This allowed me to use ANSI escape sequences in interactive mode and plain System.out/System.err whenever the program 's output was redirected to a file or piped to the stdin of some other proces... | System.console ( ) ! = null | Determining whether a Java program has been launched from an interactive shell |
Java | In some old Java code , I found a class that contains a lot of methods that all use the same error handling code ( try-catch with a lot of error handling , logging and so on ) . It looks like the first method was simply copied and then the code in the try block was slightly adapted . Here is what it basically looks lik... | public class myClass { public void doSomething ( ) { try { //do something } catch ( Exception e ) { //extensive error handling } } public void doSomethingElse ( ) { try { //do something else } catch ( Exception e ) { //extensive error handling , copy-pasted from the above method } } | How to simplify a class with lot 's of copy-pasted error handling code ? |
Java | As per the documentation on Oracle 's website : Side-effects in behavioral parameters to stream operations are , in general , discouraged , as they can often lead to unwitting violations of the statelessness requirement , as well as other thread-safety hazards . Does this include saving elements of the stream to a data... | public SavedCar saveCar ( Car car ) { SavedCar savedCar = this.getDb ( ) .save ( car ) ; return savedCar ; } public List < SavedCars > saveCars ( List < Car > cars ) { return cars.stream ( ) .map ( this : :saveCar ) .collect ( Collectors.toList ( ) ) ; } public SavedCar saveCar ( Car car ) { SavedCar savedCar = this.ge... | Saving to database in stream pipeline |
Java | The polynomial 's degree should be # of points - 1 e.g . if there are 2 points given it should be a line.I know I can solve this using a matrix e.g . if there are 4 points : the polynomial would be y = ax^3 + bx^2 + cx + d and the matrix would beand I can solve for a , b , c , d . Is there a library that can do this op... | | y0 | | x0^3 x0^2 x0 1 | | a || y1 | = | x1^3 x1^2 x1 1 | x | b || y2 | | x2^3 x2^2 x2 1 | | c || y3 | | x3^3 x3^2 x3 1 | | d | | Java library for estimating a polynomial based on a set of points |
Java | I 'm having some trouble trying to read a String and a Double from a txt file . Here is my txt file : And here is the code I am using to read them : Whenever I run this code , Exception in thread `` main '' java.util.InputMismatchException appears telling me the problem is in nextDouble ( ) .Does anybody know how to so... | Mike 300.50John 260Lisa 425.33 reader = new Scanner ( ) ; while ( reader.hasNext ( ) ) { name= reader.next ( ) ; salary = reader.nextDouble ( ) ; System.out.println ( name + `` `` + salary + `` \r\n '' ) ; } | Need to read String and Double from file |
Java | A customer is complaining that he 's experiencing a memory leak in our Java application.Despite all my efforts to reproduce his environment , configuration and usage , I was n't able to reproduce , and thus identify , the leak.I 'd want to go down another path ... Instead of trying to replicate it , maybe I could ask h... | num # instances # bytes class name -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 : 14156 577318512 [ B 2 : 9196 47439696 [ I 3 : 83396 9809992 [ C | Remotely identify a memory leak in an application used by a customer |
Java | I have this codeand it works . But when I flip the order , I get an illegal forward reference error . I 'm a little bit shocked , I did n't expect something like this from Java . : ) What happens here ? Why is the order of declarations important ? Why does the assignment work but not the method call ? | private static Set < String > myField ; static { myField = new HashSet < String > ( ) ; myField.add ( `` test '' ) ; } static { myField = new HashSet < String > ( ) ; myField.add ( `` test '' ) ; // illegal forward reference } private static Set < String > myField ; | Why is the order of declarations important for static initializers ? |
Java | I want to use JavaPoet to generate an annotation with a type literal as value . For example : I 've tried all the options I can think of , but none work : using $ L generates interface MyServiceusing $ T generates my.package.MyService , which is close but misses the .class part.using $ N gives an error : expected name ... | @ AutoService ( MyService.class ) public class GeneratedClass implements MyService { } TypeSpec.classBuilder ( `` GeneratedClass '' ) .addModifiers ( Modifier.PUBLIC ) .addSuperinterface ( MyService.class ) .addAnnotation ( AnnotationSpec.builder ( AutoService.class ) .addMember ( `` value '' , `` $ L '' , MyService.cl... | How do I get JavaPoet to generate a class literal ? |
Java | I am trying to get current time in other time zone . I used this code for this : But , when I am running this code , this code provides the current time in CET as the time in my local machine is in CET.I am confused . Then why there is scope to provide a TimeZone in constructor ? | GregorianCalendar calender = new GregorianCalendar ( TimeZone.getTimeZone ( `` Asia/Bangkok '' ) ) ; System.out.println ( calender.getTime ( ) ) ; | GregorianCalendar Class in Java |
Java | Out of the two methods in StringBuilder 's append , which of the following code is better ? or | stringBuilder.append ( '\n ' ) ; stringBuilder.append ( `` \n '' ) ; | Which one is better to pass to StringBuilder.append ? |
Java | If I have a class that implements two interfaces and I send that class to an overloaded method that accepts either interface ; which variant of the method will be called ? In other words , if I have something like this : And I send my class C to the method/s in D : Which method should be called ? Does the Java standard... | interface A { } interface B { } class C implements A , B { } class D { public static void doThings ( A thing ) { System.out.println ( `` handling A '' ) ; } public static void doThings ( B thing ) { System.out.println ( `` handling B '' ) ; } public static void main ( String [ ] args ) { doThings ( new C ( ) ) ; } } do... | Multiple interfaces in a java class - which gets used for method calls ? |
Java | Why does it seem that Gson ignores the nested generic type declaration when serializing ? I am trying to get Gson to use the compile-time type I specify , instead of the runtime type of objects in the list . I am also using an abstract superclass for A.java , but the example below has the same problem.Output : Expected... | public class A { public String foo ; } public class B extends A { public String bar ; } public static void main ( String [ ] args ) { Gson gson = new Gson ( ) ; B b = new B ( ) ; b.foo = `` foo '' ; b.bar = `` bar '' ; List < A > list = new ArrayList < A > ( ) ; list.add ( b ) ; System.out.println ( gson.toJson ( b , n... | Why does Gson serializes runtime type in list , not specified compile-time type ? |
Java | I have used SLF4J logging to print all the logs . I am using the latest version of org.slf4j . implementation 'org.slf4j : slf4j-api:2.0.0-alpha1 ' implementation 'org.slf4j : log4j-over-slf4j:2.0.0-alpha1'But I 'm getting the following error and also no logs are being printed.The logs are working fine with the older v... | SLF4J : No SLF4J providers were found.SLF4J : Defaulting to no-operation ( NOP ) logger implementationSLF4J : See http : //www.slf4j.org/codes.html # noProviders for further details.SLF4J : Class path contains SLF4J bindings targeting slf4j-api versions prior to 1.8.SLF4J : Ignoring binding found at [ jar : file : /hom... | How to enable logging in org.slf4j for the version : ' 2.0.0-alpha1 ' in Spring boot |
Java | I have an android application which is getting gesture coordinates ( 3 axis - x , y , z ) . I need to compare them with coordinates which I have in my DB and determine whether they are the same or not.I also need to add some tolerance , since accelerometer ( device which captures gestures ) is very sensitive . It would... | private int checkWhetherGestureMatches ( byte [ ] values , String [ ] refValues ) throws IOException { int valuesSize = 32 ; int ignorePositions = 4 ; byte [ ] valuesX = new byte [ valuesSize ] ; byte [ ] valuesY = new byte [ valuesSize ] ; byte [ ] valuesZ = new byte [ valuesSize ] ; for ( int i = 0 ; i < valuesSize ;... | Compare graph values or structure |
Java | The code below succeeds in Java 8 but throws a ClassCastException in Java 11 . Why did the behavior change ? I could not find any related changes in OpenJDK 's Java 9 , Java 10 or Java 11 feature sets . | public class GenericsExample { public static void main ( String [ ] args ) { Set < Car > set = new HashSet < > ( ) ; set.add ( getAnimal ( ) ) ; } static < T extends Animal > T getAnimal ( ) { return ( T ) new Animal ( ) { } ; } interface Animal { } class Car { } } | Why does this code with generics throw a ClassCastException in Java 11 ? |
Java | The question : while this function has been called from a thread , IS there a way the list passed to this function can be modified by another thread ? | Integer getElement ( List < Integer > list ) { int i = Random.getInt ( list.size ( ) ) ; return list.get ( i ) ; } | Can a list passed to a function be modofied by another thread in Java ? |
Java | I am working with Java 8 streams , and would like to come up with a way to debug them . So i thought I could write a filter that printed out the elements at a stage of the stream , something like this : Close , but that 's not quite it , as it does n't have the proper delimiters to make it legible : What I want is : Is... | int [ ] nums = { 3 , -4 , 8 , 4 , -2 , 17 , 9 , -10 , 14 , 6 , -12 } ; int sum = Arrays.stream ( nums ) .filter ( w - > { System.out.print ( `` `` + w ) ; return true ; } ) // trace .map ( n - > Math.abs ( n ) ) .filter ( w - > { System.out.print ( `` `` + w ) ; return true ; } ) // trace .filter ( n - > n % 2 == 0 ) .... | Tracing Streams |
Java | I 'm working on an app for a robot where the user can define punch combinations which the robot will later fetch from the device . To allow the user to store these trainings I have defined a class `` Trainings '' which holds the id , the name and the punch combination of the training . This training is later saved in a... | public void deleteTraining ( Training training ) { SQLiteDatabase db = this.getWritableDatabase ( ) ; db.delete ( TABLE_TRAININGS , KEY_ID + `` = ? `` , new String [ ] { String.valueOf ( training.getID ( ) ) } ) ; db.close ( ) ; } public View getView ( int position , View convertView , ViewGroup parent ) { if ( convert... | Nullpointer Exception after deleting entry from SQL database |
Java | I just learned from Peter Lawreys post that this is valid expression , and evaluates to true.My question is , why is it allowed to have double literals which ca n't be represented in a double , while integer literals that ca n't be represented are disallowed . What is the rationale for this decision.A side note , I can... | 333333333333333.33d == 333333333333333.3d 99999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999... | Why is arbitrary precision in double literals allowed in Java ? |
Java | The code : is used by my class : As you see it has two type parameters P and X . Despite of that the X can always be deduced from P but the language requires me to supply both : Is there any trick to get rid of the X type parameter ? I want just useAlso , I do n't want lose type information and use it as : | interface Property < T > { T get ( ) ; } class BoolProperty implements Property < Boolean > { @ Override public Boolean get ( ) { return false ; } } class StringProperty implements Property < String > { @ Override public String get ( ) { return `` hello '' ; } } class OtherStringProperty implements Property < String > ... | Eliminate type parameter of java generics |
Java | Input string is `` 1.01 '' and output is `` . '' . I ca n't understand why matcher.find ( ) returns true , there are no symbols like `` + '' , `` - '' , `` * '' , `` ^ '' , `` % '' in input string . Why did it happen ? | String s = `` 1.01 '' ; Matcher matcher = Pattern.compile ( `` [ +-/\\*\\^\\ % ] '' ) .matcher ( s ) ; if ( matcher.find ( ) ) { System.out.println ( matcher.group ( ) ) ; } | what is wrong with matcher.find ( ) ? |
Java | Consider the following code : I came across this the other day when accidentally calling a static method in a non-static way.I know that you should n't call static methods in a non-static way , but I am still wondering , why is n't it possible to infer the type in this case ? | class Test { void accept ( Consumer < Integer > c ) { } static void consumer ( Integer i ) { } void foo ( ) { accept ( this : :consumer ) ; // The method accept ( Consumer < Integer > ) in the type Test is not applicable for the arguments ( this : :consumer ) accept ( Test : :consumer ) ; // Valid } } | Java 8 type inference with non-static access of static members |
Java | Since this question is back to four votes to close , I 'm trying again to ask a more narrow question that hopefully the community will view more favorably.Which specific design decisions in Java are documented to be done the way that they are not because that was the preferred design decision , but rather because it wa... | public void addEmptyMember ( List < ? > someList ) { if ( someList instanceof List < String > ) { ( ( List < String > ) someList ) .add ( `` '' ) ; } } | What Java designs are explicitly done to support backwards compatability ? |
Java | I have a CreateOrder instance which has some String , Integer and Double states in it . When I create an object for CreateOrder in my JUnit test and send it over , I am able to validate String attributes but not Integer using Optional API as follows - Like for aoid , I also want to user ofNullable ( ) for integer but n... | String aoid = Optional.ofNullable ( createOrder.getAltorderid ( ) ) .orElse ( `` '' ) ; int quantity = Integer.parseInt ( each.getQty ( ) ) ; double amount = Double.parseDouble ( each.getPrice ( ) .getAmount ( ) ) ; | Validating inputs using Optional |
Java | I found a scenario where java program behaves differently after renaming a variable . I understand this is n't actually code that anyone would use but if someone knows whats going on it would be nice to have an explanation . I tried this with java 1.6 on Eclipse Kepler.This outputs : hello Exception in thread `` main '... | package _test ; public class TestClass { public static void main ( String ... args ) { Object testClazz $ 1 = new Object ( ) { public String toString ( ) { return `` hello '' ; } } ; TestClass $ 1 test = new TestClass $ 1 ( ) ; System.out.println ( testClazz $ 1.toString ( ) ) ; test.doStuff ( ) ; } } class TestClass $... | Java changing variable name changes program behaviour |
Java | I 've read pretty often , that using try-catch is quite slow compared to normal code.Now I wonder if the number of caught exceptions affects the performance of the code or not.So isslower than ? Of course I 'm only referring to the code in the try-clause and if no exception is caught . | try { ... } catch ( StrangeException e ) { ... } try { ... } catch ( StrangeException e ) { ... } catch ( MysteriousException e ) { ... } catch ( FrighteningException e ) { ... } | Does the number of caught exceptions affect the performance of the try-code ? |
Java | Coursework brief requires me to assign an optional cmd argument to a static final variable.I have tried doing it in main ( ) but compiler complains `` can not assign a value to final variable '' . I 've tried doing it in a static method called by main ( ) but same error . I 've heard about static blocks being used in o... | public class FibonacciNim { private static Scanner myScanner = new Scanner ( System.in ) ; private static final int NO_OF_HEAPS ; private static final int TOKENS_PER_HEAP ; public static void main ( String [ ] args ) { // set heaps and tokens using args if ( args.length == 0 ) { NO_OF_HEAPS = 3 ; TOKENS_PER_HEAP = 9 ; ... | How to initialize static final variables based on cmd args ? |
Java | I am trying to call into a Rust library from Java and I really want to use SWIG to generate the interface layer from a C header file that I write ( I also want to allow regular C clients to call into my library , hence I think it makes sense to maintain one interface header ) .I am doing this all on Windows using Mingw... | cargo new testlibcd testlib void tell_me_the_answer ( void ) ; % module testlib % { # include `` testlib.h '' % } % include `` testlib.h '' mkdir testlibswig -outdir testlib -java -package testlib testlib.i public final class Program { static { System.loadLibrary ( `` testlib '' ) ; } public static void main ( final St... | Is it possible to use Java , SWIG and Rust together ? |
Java | Consider the abstract Data class with an abstract Builder : The class is extended , which also includes its own extended Builder : The Extension object gets all methods from both classes . However the order the setter methods is called is important . This is OK : Whereas this produces a compilation error : I know the r... | abstract class Data { abstract static class Builder < T extends Data > { private String one ; protected Builder ( ) { this.one = null ; } public final Builder < T > withOne ( final String value ) { this.one = value ; return this ; } protected abstract T build ( ) ; } private final String one ; protected Data ( final Bu... | How do I define a builder pattern hierarchy where the setters can be called in any order |
Java | I 've been experimenting with the HttpClient stuff in the Java 9/10 incubator , and have the following trivial code ( virtually stolen from the project home page ! ) : I find it works fine if it 's pointed at a URL that is not the localhost , but fails if I ask for the localhost ( whether by the name `` localhost '' , ... | URI uri = URI.create ( `` http : //192.168.1.102:8080/ '' ) ; HttpRequest getRequest = HttpRequest.newBuilder ( ) .uri ( uri ) .GET ( ) .build ( ) ; HttpResponse < String > response = client.send ( getRequest , HttpResponse.BodyHandler.asString ( ) ) ; System.out.println ( `` response to get : `` + response.body ( ) ) ... | java 10 httpclient incubator GET request fails on node.js server |
Java | I 'm building ( well , trying to build ) a simple usenet news reader . The code below works . Is grabs the username , host , password from the SharedPreferences and connects to the server and sucessfully authenticates , however it locks up the UI until all the tasks are done.How would i change this code so that it does... | package com.webfoo.newz ; import java.io.IOException ; import java.net.SocketException ; import android.app.Activity ; import android.content.Intent ; import android.content.SharedPreferences ; import android.os.Bundle ; import android.view.View ; import android.widget.TextView ; import org.apache.commons.net.nntp.NNTP... | Connect to a Socket locks up UI |
Java | So here it is this exampleand class Stuff is defined as followThe output isHow does Java tell the null is a String ? If I change Stuff to I get compilation error for Stuff ( null ) : Again , why does Java `` decide '' null is a String ? | public static void main ( String [ ] args ) { new Stuff ( null ) ; new Stuff ( `` a '' ) ; new Stuff ( 1 ) ; } public class Stuff { Stuff ( Object o ) { System.out.println ( `` object '' ) ; } Stuff ( String s ) { System.out.println ( `` string '' ) ; } } stringstringobject public class Stuff { Stuff ( String s ) { Sys... | What is the type on null as a method argument ? |
Java | I would like to do the following : That is , given an immutable list of T , you can add any U to the list to yield an immutable list of U , with the constraint that U must be a supertype of T. For exampleI can add a monkey to a list of monkeys , yielding a new list of monkeys ; I can add a human to a list of monkeys , ... | public class ImmutableList < T > { public < U super T > ImmutableList < U > add ( U element ) { ... } } public class ImmutableList < T > { public ImmutableList < T > add ( T element ) { ... } public static < U > ImmutableList < U > add ( ImmutableList < ? extends U > list , U element ) { ... } } // if ' U super T ' wer... | Substitute for illegal lower bounds on a generic Java method ? |
Java | I want to create two interfaces with inverse relationships . I 'm not sure if expression C extends Category < D , Item < D , C > > is correct , but at least there are no compiler errors.I extends Item gives the warning Item is a raw type . References to Item < D , C > should be parametrized . I triedbut this results in... | public interface Item < D extends Description , C extends Category < D , Item < D , C > > > { public C getCategory ( ) ; public void setCategory ( C category ) ; } public interface Category < D extends Description , I extends Item > { public List < I > getItems ( ) ; public void setItems ( List < I > items ) ; } I exte... | Generic Interface with inverse relationship |
Java | I have a requirement to trigger the Cloud Dataflow pipeline from Cloud Functions . But the Cloud function must be written in Java . So the Trigger for Cloud Function is Google Cloud Storage 's Finalise/Create Event , i.e. , when a file is uploaded in a GCS bucket , the Cloud Function must trigger the Cloud dataflow.Whe... | package com.example ; import com.example.Example.GCSEvent ; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport ; import com.google.api.client.http.HttpRequestInitializer ; import com.google.api.client.http.HttpTransport ; import com.google.api.client.json.JsonFactory ; import com.google.api.client.j... | How to trigger Cloud Dataflow pipeline job from Cloud Function in Java ? |
Java | I 've been trying to figure out what the best practice is for form submission with spring and what the minimum boilerplate is to achieve that . I think of the following as best practise traitsValidation enabled and form values preserved on validation failureDisable form re-submission F5 ( i.e . use redirects ) Prevent ... | @ Controller @ RequestMapping ( `` / '' ) public class MyModelController { @ ModelAttribute ( `` myModel '' ) public MyModel myModel ( ) { return new MyModel ( ) ; } @ GetMapping public String showPage ( ) { return `` thepage '' ; } @ PostMapping public String doAction ( @ Valid @ ModelAttribute ( `` myModel '' ) MyMod... | Spring form submission with minum boilerplate |
Java | I am trying to create a huffman tree , and am in the middle of attempting to merge two trees . I can not figure out how to remove a Tree in my program without getting the `` concurrent Modification Exception '' because I am iterating over a list and attempting to remove from the list at the same time . | BinaryTree < Character , Integer > t1 = null ; BinaryTree < Character , Integer > t2 = null ; BinaryTree < Character , Integer > tFinal = null ; int treeSize = TREES.size ( ) ; for ( int i = 0 ; i < treeSize ; i++ ) { for ( BinaryTree < Character , Integer > t : TREES ) { System.out.println ( `` treeSize `` + treeSize ... | How to delete from a list , while modifying the list |
Java | I am trying to take a part of a String from point ( a , b ) and replace letters from given values in the string into ' X's.Example : If the string is ABC123 and switch ( 3,5 ) is called , it would change it to ABCXXX.So far I have : I am very lost ... .thanks for any help ! | public void switch ( int p1 , int p2 ) { String substring = myCode.substring ( p1 , p2-1 ) ; } | Java Changing Part of String with Specific Character |
Java | Can somebody who understand the Java Memory Model better than me confirm my understanding that the following code is correctly synchronized ? I understand that this code is correct but I have n't worked through the whole happens-before math . I did find two informal quotations that suggest this is lawful , though I 'm ... | class Foo { private final Bar bar ; Foo ( ) { this.bar = new Bar ( this ) ; } } class Bar { private final Foo foo ; Bar ( Foo foo ) { this.foo = foo ; } } | Java Memory Model : Is it safe to create a cyclical reference graph of final instance fields , all assigned within the same thread ? |
Java | I have a string ; How can I split/extract logical values from this string inside parenthesis as ; Any idea ? all is welcome | String value = `` ( 5+5 ) + ( ( 5+8 + ( 85*4 ) ) +524 ) '' ; ( 85*4 ) as one ( 5+8 + one ) as two ( two+524 ) as three ( ( 5+5 ) + three ) as four ... | Extract from string in Java |
Java | The Java project I 'm working on uses a combination of code analysis tools : PMD , Checkstyle and FindBugs . These pick up on plenty of bugs , style issues etc . but one often slips through the net : Note the other way round is checked , i.e . public abstract BadlyNamedClass gives PMD warning `` Abstract classes should... | public class AbstractBadlyNamedClass { // Not abstract ! // ... } | Is there a Checkstyle/PMD rule `` Non-abstract classes should not be named AbstractXXX '' ? |
Java | I have currently two queues and items traveling between them . Initially , an item gets put into firstQueue , then one of three dedicated thread moves it to secondQueue and finally another dedicated thread removes it . These moves obviously include some processing . I need to be able to get the status of any item ( IN_... | while ( true ) { Item i = firstQueue.take ( ) ; statusMap.put ( i , AFTER_FIRST ) ; process ( i ) ; secondQueue.add ( i ) ; statusMap.put ( i , IN_SECOND ) ; } | Tracking the progress between Queues in a Map |
Java | I have a constructor which gets a HashSet and a HashMap . I need to run a validation check on one hashMAp and combine it with the hashSet , as 'super ' must receive only one hashSet.I ca n't find a way to do it as I get following error : can not reference this before supertype constructorExample : I want to do somethin... | public class A extends B { public A ( HashSet < Obj > h1 , HashMap < UID , Objects > m1 ) { super ( new C ( h1 ) ) ; //h1 should contain changes related to m1.. } public class A extends B { public A ( HashSet < Obj > h1 , HashMap < UID , Objects > m1 ) { runMyFunc ( h1 , m1 ) ; super ( new C ( h1 ) ) ; } runMyFunc ( Ha... | How to run a function before calling super in java ? |
Java | I have TypeToken class used to represent some generic type like this : TypeToken < List < String > > listOfStrings = new TypeToken < List < String > > { } And this works fine , TypeToken is just class TypeToken < T > { } with simple method to get that type . Now I wanted to create simple methods for common type like Li... | public static < T > TypeToken < ? extends T > extendsType ( Class < T > type ) { return null ; } public static < T > TypeToken < List < T > > list ( TypeToken < T > type ) { return null ; } class TypeToken < X > { static < T > TypeToken < ? extends T > extendsType ( Class < T > type ) { return null ; } static < T > Typ... | Unexpected generic behavior with TypeToken nesting generic types |
Java | If I run my project in Eclipse all is OK . But when I do : and afterwards start my project then it is not working . I found this difference : Eclipse : mvn package : Why ? What could I do , that mvn package loads the same jetty version 9.2.13 ? UPDATE : I found some additional differences : Compiling in Eclipse ( WebAp... | mvn clean mvn package INFO org.eclipse.jetty.server.Server : doStart:327 ~ jetty-9.2.13.v20150730 INFO org.eclipse.jetty.server.Server : doStart:327 ~ jetty-9.2.z-SNAPSHOT org.eclipse.jetty.server.Server : doStart:327 ~ jetty-9.2.13.v20150730org.eclipse.jetty.server.handler.ContextHandler $ Context : log:2052 ~ No Spri... | mvn package load other Library as Eclipse |
Java | When an exception occurs during the handling of an exception , only the last exception gets reported , because I can add just one exception to an Error object . How to report all exception in the final error message ? Example : In the example everything fails . The database insert causes ex1 . The rollback causes ex2 .... | class main { public static void main ( String [ ] args ) { try { // Database.insert ( ) ; throw new Exception ( `` insert failed '' ) ; } catch ( Exception ex1 ) { try { // Database.rollback ( ) ; throw new Exception ( `` rollback failed '' ) ; } catch ( Exception ex2 ) { throw new Error ( `` Can not roll back transact... | How to avoid exception shadowing ? |
Java | I am preparing for the OCA SE 7 exam , and some of these questions are really ( ! ) tricky.In one of the books Im using I found an error I think , so I would like to confirm the following please ... After the println method executes , how many String objects are there in the pool ? It is my understanding that : - line ... | public static void main ( String ... args ) { String autumn = new String ( `` autumn '' ) ; // line one System.out.println ( `` autumn '' == `` summer '' ) ; // line two } | String count in the pool with println |
Java | Assume this code : Here , a temporary object new Foo ( ) creates a statically held Thread thread which utilizes an instance-tied String thing in an anonymous implementation of Runnable . Does the String thing get garbage collected after expiration of new Foo ( ) , or will it persist for its use within run ( ) ? Why ? | public class Foo { public static Thread thread ; public String thing = `` Thing ! ! `` ; public static void main ( String [ ] args ) { new Foo ( ) .makeThread ( ) ; // < - Foo object may get garbage collected here . thread.start ( ) ; } private void makeThread ( ) { thread = new Thread ( new Runnable ( ) { @ Override p... | Will an unreferenced object used in an anonymous class instance not expire ? |
Java | Scenario : I want to have an enum containing all the playing cards in a standard deck . For this example ignore the jokers.Writingfeels wrong.I 'd like to be able to do something like thisI 've considered defining card as a class containing suit and face fields , where suit and face are themselves enums . However in ot... | enum Cards { SPADE_1 ( 0 , 1 ) , SPADE_2 ( 0 , 2 ) , etc . enum Card { for ( int suit=0 ; suit < 4 ; suit++ ) { for ( int face=1 ; face < 13 ; face++ ) { new Card ( suit , face ) ; } } } I 'm not sure if it 's considered good form to answer my own question , but @ Paul just gave me a brainwave.Declare Card to have a pr... | Enumerate enum-instances with loop |
Java | I 'm new to Netty . There is a problem about file transfer confusing me for days . I want to send image file from client to server.The code below is executable . But only I shutdown server forcibly can I open received image file normally . Otherwise , it shows `` It looks like you do n't have permission to view this fi... | public class FileClientHandler extends ChannelInboundHandlerAdapter { private int readLength = 8 ; @ Overridepublic void channelActive ( ChannelHandlerContext ctx ) throws Exception { sendFile ( ctx.channel ( ) ) ; } private void sendFile ( Channel channel ) throws IOException { File file = new File ( `` C : \\Users\\x... | How can I know if there is no data to read in Netty ByteBuf ? |
Java | Java requires the instantiation of a bounded type parameter to its upper bound class to have a cast , for example : T is already restricted to Integer or one of its sub classes ( I know , there are n't any ) upon declaration , and it seems to me that any bounded type parameter may only be instantiated to its upper boun... | < T extends Integer > void passVal ( T t ) { Integer number = 5 ; t = ( T ) number ; // Without cast a compile error is issued } | Why does java require a cast for the instantiation of a bounded type parameter to its upper bound class ? |
Java | Bridge methods are used in java to handle covariance in derived methods , and to change visibility on derived methods.However , both of these cases are for instance methods ( as you ca n't derive static methods ) .I was looking at how Kotlin generates argument defaults , and I was struck that it uses static bridge meth... | public class BridgeTest1Base < T > { public T frob ( ) { return null ; } } public class BridgeTest1Derived extends BridgeTest1Base < Integer > { public Integer frob ( ) { return null ; } } public class BridgeTest1Derived extends BridgeTest1Base < Integer > { @ Override public Integer frob ( ) { return null ; } @ Overri... | Does javac ever generate static bridge methods ? |
Java | I have something like the below : A collection of say 100 , where the stackid could be duplicate with different questionIds . Its a one to many relationship between stackId and questionIdIs there a streamy , java 8 way to convert to the below strcuture : Which would be a collection of 25 , with each instance having a n... | public class MyClass { private Long stackIdprivate Long questionId } public class MyOtherClass { private Long stackIdprivate Collection < Long > questionIds } [ { 1,100 } , { 1,101 } , { 1,102 } , { 1,103 } , { 2,200 } , { 2,201 } , { 2,202 } , { 1,203 } ] [ { 1 , [ 100,101,102,103 ] } , { 2 , [ 200,201,202,203 ] } ] | grouping objects java 8 |
Java | Actually , this is the first time I see a code like this : two lines I do n't understand : | class A { public static void main ( String args [ ] ) { outer : for ( int i=0 ; i < 10 ; i++ ) { for ( int j=0 ; j < 10 ; j++ ) { if ( j > i ) { System.out.println ( ) ; continue outer ; } System.out.print ( `` `` + ( i *j ) ) ; } } System.out.println ( ) ; } } outer : for ( int i=0 ; i < 10 ; i++ ) // this seems simil... | I need a help to understand this code |
Java | Hello I was trying to use Java regular expression to get the required context path from the following path information.I want to write regular expression to get `` /Systems '' and `` /lenovo '' separately.I tried the following regular expression using groups but not working as expected.Could any body tell me what might... | String path = `` /Systems/lenovo/ '' ; String systemString = path.replaceAll ( `` ( . * ) ( /\\w+ ) ( [ / ] [ \\w+ ] ) '' , `` $ 2 '' ) - to get `` /Systems '' - not workingString lenovoString = path.replaceAll ( `` ( . * ) ( /\\w+ ) ( [ / ] [ \\w+ ] ) '' , `` $ 3 '' ) - to get `` /lenovo '' - working . | Regular Expression for Separating Paths |
Java | I am wondering if there is a way to combine multiple attributes from an object into a list of String . In My Case , I have an object with the name `` debitCardVO '' and I want it to convert from object to ListHere is my code Snippet : | for ( DebitCardVO debitCardVO : debitCardVOList ) { List < String > debitCardList = debitCardVOList.stream ( ) .map ( DebitCardVO : :getCardBranchCode , DebitCardVO : :getAccountNo ) .collect ( Collectors.toList ( ) ) ; } | How to convert multiple attributes of object into List < String > using java 8 |
Java | Found fact about unbounded wildcards that is annoying me . For example : It fails , although works with Map < ? , ? > or Map < ? , Map < Integer , String > > return type.Could someone tell me the exact reason ? Thanks in advance.UpdateSeems that i understood and the simplest explanation for this question ( omitting all... | public class Test { private static final Map < Integer , Map < Integer , String > > someMap = new HashMap < > ( ) ; public static void main ( String [ ] args ) { getSomeMap ( ) ; } static Map < ? , Map < ? , ? > > getSomeMap ( ) { return someMap ; //compilation fails } } | Nested wildcards |
Java | The Dagger 2 documentation suggests providing different configurations for testing and production using an interface for ProductionComponent and TestComponent , as follows : Let 's say we have an Android activity ( MyApp ) which uses ProductionComponent : Generally , what 's the best way to use DaggerTestComponent.buil... | @ Component ( modules = { OAuthModule.class , // real auth FooServiceModule.class , // real backend OtherApplicationModule.class , /* … */ } ) interface ProductionComponent { Server server ( ) ; } @ Component ( modules = { FakeAuthModule.class , // fake auth FakeFooServiceModule.class , // fake backend OtherApplication... | Testing with Dagger 2 using separate component configurations in Android |
Java | I have a series of points , which represent mobile devices within a room . Previously I have systematically emitted a ping from each and recorded the time at which it arrives at the others to calculate the distances.Here 's a simple diagram of an example network.The bottom A node should have been a D insteadAfter recor... | A = { B : 2 , C : 1 , D : 3 } B = { A : 2 , C : 2 , D : 2 } C = { A : 1 , B : 2 , D : 2 } D = { A : 3 , B : 2 , C : 2 } | Positioning Devices ( Intersecting Circles ) |
Java | While refactoring some code I stumbled over this oddity . It seems to be impossible to control the strictfp property for an initializer without affecting the entire class . Example : From the JLS , Section 8.1.1.3 I gather that the initializer would be strictfp if the class would be declared using the strictfp modifier... | public class MyClass { public final static float [ ] TABLE ; strictfp static { // this obviously does n't compile TABLE = new float [ ... ] ; // initialize table } public static float [ ] myMethod ( float [ ] args ) { // do something with table and args // note this methods should *not* be strictfp } } | How to make a ( static ) initializer block strictfp ? |
Java | When user change Display settings scaling ( Windows 10 , right click on desktop , select Display settings and scale to 150 % ) , suddenly all values reported by or orbecome invalid . Is there a way how to get the actual values ? | GraphicsDevice device = MouseInfo.getPointerInfo ( ) .getDevice ( ) ; Rectangle bounds = device.getDefaultConfiguration ( ) .getBounds ( ) ; Toolkit.getDefaultToolkit ( ) .getScreenSize ( ) ; GraphicsEnvironment.getLocalGraphicsEnvironment ( ) .getMaximumWindowBounds ( ) ; | obtain Windows 10 Display settings values in Java |
Java | I am trying to create an app that will redirect to a certain webpage when run . I would like this app to be full screen with no title bar or browse bar . I am able to call a BrowseSession to bring up the proper website in the browser but it does n't give me the desired feel . Here is the code I am using for the BrowseS... | BrowserSession browser = Browser.getDefaultSession ( ) ; browser.displayPage ( `` http : //www.stackoverflow.com '' ) ; String baseURL = `` http : //www.stackoverflow.com '' ; BrowserFieldConfig config = new BrowserFieldConfig ( ) ; config.setProperty ( BrowserFieldConfig.JAVASCRIPT_ENABLED , Boolean.TRUE ) ; BrowserFi... | How to suppress the browser top bar while using a BlackBerry BrowserSession |
Java | I have a question about g1gc.These are the heap usage graph.The above is -Xms4g -Xmx4g.The bottom is -Xms8g -Xmx8g.I do n't know why the 8g option causes g1gc to happen more often . Other options are all default.And server spec is 40 logical process . ps . What are the proper tuning options ? addtional questionCan the ... | 2019-05-07T21:03:42.093+0900 : 10.280 : [ GC pause ( G1 Evacuation Pause ) ( young ) , 0.1785373 secs ] [ Parallel Time : 43.4 ms , GC Workers : 28 ] [ GC Worker Start ( ms ) : Min : 10280.0 , Avg : 10280.1 , Max : 10280.6 , Diff : 0.6 ] [ Ext Root Scanning ( ms ) : Min : 0.0 , Avg : 0.4 , Max : 0.8 , Diff : 0.8 , Sum ... | Why do I get GC more often when I raise memory ? |
Java | Recently I was playing around with some simple Java code using main methods to quickly test the code I wrote . I ended up in a situation where I had two classes similar to those : I was quite surprised that the code stopped compiling and Eclipse complained that Exception IOException is not compatible with throws clause... | public class A { public static void main ( String [ ] args ) { // code here } } public class B extends A { public static void main ( String [ ] args ) throws IOException { // code here } } | Signature difference when hiding static method in a subclass |
Java | I saw a similar code in google guava ( as factory methods ) for making instances of Hashmap without mentioning the generic types.I do n't understand how the generic is getting inferred by the above program.I mean how can the function getHashMap understand the type of map since i 'm not passing any type information to t... | public static void main ( String [ ] args ) { Map < String , Map < Long , List < String > > > map = getHashMap ( ) ; } static < K , V > Map < K , V > getHashMap ( ) { return new HashMap < K , V > ( ) ; } | How is the generic type getting inferred here ? |
Java | I 'm trying to get a head start on practicing interview questions and I came across this one : Turn String aaaabbbbddd into a4b4d3You would basically want to convert the existing string into a string with each unique character occurrence and the number of times the character occurs . This is my solution but I think it ... | String s = `` aaaabbbbddd '' ; String modified = `` '' ; int len = s.length ( ) ; char [ ] c = s.toCharArray ( ) ; int count = 0 ; for ( int i = 0 ; i < len ; i++ ) { count = 1 ; for ( int j = i + 1 ; j < len ; j++ ) { if ( c [ i ] == ' ' ) { break ; } if ( c [ i ] == c [ j ] ) { count++ ; c [ j ] = ' ' ; } } if ( c [ ... | Turn String aaaabbbbddd into a4b4d3 |
Java | I have a simple xml file and I want to remove everything before the first < item > tag . The following java code is not working : What is the correct way to do this ? And how do I address the non-greedy issue ? Sorry I 'm a C # programmer . | < sometag > < something > ... .. < /something > < item > item1 < /item > ... . < /sometag > String cleanxml = rawxml.replace ( `` ^ [ \\s\\S ] + < item > '' , `` '' ) ; | Simple java regular expression replace question |
Java | I 'm trying to create a work queue class ( FooQueue ) that has : a set of function members doing work ( do* ) . Each one of them take one parameter , having the same type ( FooItem ) .an 'add ' function that takes 2 parameters : one of the above functions , and a FooItem . Most importantly , the add function should onl... | public class App { public static void main ( String [ ] args ) { FooQueue q = new FooQueue ( ) ; q.add ( FooQueue : :dos , new FooItem ( ) ) ; // this compiles q.add ( q : :do1 , new FooItem ( ) ) ; // this does not : // does not consider q : :do1 'delegate ' // as taking 2 parameters , // with q being the first one Fo... | passing and enforcing a member function in java |
Java | When I 'm looking at Spring FrameWork 3.0 I see the following code example : This option does n't work for me . Only when I change the code the following way : It works fine . Can anybody tell me why ? | @ RequestMapping ( `` /index.dlp '' ) public ModelAndView index ( ) { logger.info ( `` Return View '' ) ; return new ModelAndView ( `` index '' ) ; } @ RequestMapping ( `` /index.dlp '' ) public ModelAndView index ( ) { logger.info ( `` Return View '' ) ; return new ModelAndView ( `` index.jsp '' ) ; } | Spring MVC framework very basic Dispatcher question |
Java | I 've just been profiling some code where I increment some frequency counters with the following code : The creation of the query takes almost 50 % of the execution time , and I 'd like to reuse the work somehow . Is it safe to save the query and ops objects in a ThreadLocal and just call query.field ( `` text '' ) .eq... | Datastore ds = ... final Query < Unit > query = ds.createQuery ( Unit.class ) ; query.field ( `` text '' ) .equal ( text ) ; query.field ( `` langCode '' ) .equal ( lang.getCode ( ) ) ; UpdateOperations ops = ds.createUpdateOperations ( Unit.class ) ; ops.inc ( `` frequency '' , value ) ; ds.update ( query , ops , fals... | Is there a good pattern for reusing Morphia queries ? |
Java | I am designing the API for a service that deals with Job entities . I need to retrieve jobs given a status . So , I ended up naming my methods like so : A while later I realised that I also need to be able to retrieve jobs which do n't belong to a given status . Say , I want to retrieve all but the closed jobs.I have b... | List < Job > getJobsByStatus ( JobStatus status ) ; List < Job > getJobsAllButStatus ( JobStatus status ) ; List < Job > getJobsNotStatus ( JobStatus status ) ; | How should I name this method ? |
Java | I just started working in Java networking protocols . I am trying to connect to the internet using my proxy server . When I see the post at 'https : //www.tutorialspoint.com/javaexamples/net_poxy.htm ' , they set the http.proxyHost property to 'proxy.mycompany1.local ' . I know I can set this to my proxy server IP , bu... | import java.net.HttpURLConnection ; import java.net.InetSocketAddress ; import java.net.Proxy ; import java.net.ProxySelector ; import java.net.URI ; import java.net.URL ; public class TestProxy { public static void main ( String s [ ] ) throws Exception { try { System.setProperty ( `` http.proxyHost '' , `` abcd '' ) ... | what is 'proxy.mycompany1.local ' |
Java | If I have this interface : Why ca n't I implement it like this ? It seems like void should be covariant with everything . Am I missing something ? Edit : I should have been clearer that I 'm looking for the design justification , not the technical reason that it wo n't compile . Are there negative consequences to makin... | public interface Foo { void bar ( ) ; } public class FooImpl implements Foo { @ Override public Object bar ( ) { return new Object ( ) ; } } | Why is void not covariant in Java ? |
Java | I 've been working on some ways to optimize LinkedList 's . Does anyone know if the Java default doubly-linked LinkedList class is optimized to do get ( ) operations in reverse ? For example : Would the call to list.get ( half + 1 ) optimize the search and go in reverse since it is a doubly-linked list ? It would make ... | // Some LinkedList list that exists with n elements ; int half = list.size ( ) / 2 ; list.get ( half + 1 ) ; | Is Java 's LinkedList optimized to do get ( index ) in reverse when necessary ? |
Java | Possible Duplicate : Java import confusion When i read play frameworks documentation , I found this.In the first line itself they have imported all the classes under play package . Then what is the use of second line . Check this link . Go to 'Providing an application error page ' section.Correct me if i 'm wrong in im... | import play . * ; import play.mvc . * ; | Why some Java codes imports same package again ? |
Java | This question has received a total of several paragraphs of answer . Here is the only sentence that actually tells me what I was looking for : Your examples would make little difference since intermediate computations need to be stored temporarily on the stack so they can be used later on.In fact , it answers my questi... | void makeWindow ( ) { Display .getContext ( ) .windowBuilder ( ) .setSize ( 800 , 600 ) .setBalloonAnimal ( BalloonAnimal.ELDER_GOD.withColor ( PUCE ) ) .build ( ) ; } void makeWindow ( ) { DisplayContext dc = Display.getContext ( ) ; WindowBuilder wb = db.windowBuilder ( ) ; BalloonAnimal god = BalloonAnimal.ELDER_GOD... | Does adding local variables to methods make them slower ? |
Java | I was asked to implement an `` access policy '' to limit the amount of concurrent executions of a certaing process within an application ( NOT a web application ) which has direct connection to the database.The application is running in several machines , and if more than a user tries to call the process , only one exe... | SELECT Active FROM Process UPDATE Process SET Active = ' Y ' UPDATE Process SET Active = ' N ' | Limit concurrent execution of an application process using database |
Java | Occasionally , I meet an interesting , strange thing : same block of encrypted text can be decrypted using several different key ! Can anyone please indicate me what 's going wrong ? Thanks a lot.Please do n't try to let me switch to triple DES/AES etc , I just want to know where the problem is - the way calling the Ja... | D : \ > java -versionjava version `` 1.7.0_21 '' Java ( TM ) SE Runtime Environment ( build 1.7.0_21-b11 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 23.21-b01 , mixed mode ) D : \ > java DESTest -e 12345678 abcde977encrypted as [ 17fd146fa6fdbb5db667efe657dfcb60 ] D : \ > java DESTest -d 17fd146fa6fdbb5db667efe657df... | Strange DES behavior - decryption is successful using different keys |
Java | I 'm working on a legacy Java application , that deals with `` fruits '' and `` vegetables '' , let 's say , for the sake of the question.They are treated as different things internally , cause they do n't have all methods/properties in common , but a lot of things are DONE very similar to both of them.So , we have a t... | public void doSomething ( Plant p ) { // do the stuff that is common , and then ... if ( p.hasFruit ( ) ) { doThingWithFruit ( p.getFruit ( ) ) ; } else { doThingWithVegetable ( p.getVegetable ( ) ) ; } } public void createSomethingUsingFruit ( Something s , Fruit f ) ; public void createSomethingUsingVegetable ( Somet... | What is the proper design to deal with this ? |
Java | I try to find the greatest common divisor for two integers . But I do n't understand what is wrong with my code : | public class Main { public static void main ( String [ ] args ) { Scanner s = new Scanner ( System.in ) ; int a = s.nextInt ( ) ; int b = s.nextInt ( ) ; while ( a ! = 0 | b ! = 0 ) { if ( a > = b ) { a = a % b ; } else { b = b % a ; } } if ( a == 0 ) { System.out.println ( b ) ; } else { System.out.println ( a ) ; } }... | Greatest common divisor |
Java | i am basically coming from java background and struggling to understand the modulo operation in Ruby . The above operation in Java yields , 2 -2 2 -2But in Ruby , the same expression yields 21-1-2 .How logically ruby is good at this ? How the module operation is implemented in Ruby ? If the same operation is defined as... | ( 5 % 3 ) ( -5 % 3 ) ( 5 % -3 ) ( -5 % -3 ) | Why ruby modulo is different from java/other lang ? |
Java | This works ok : This does not compile : Error message : Why ? | Map aMap ; aMap = new HashMap < String , TreeSet < String > > ( ) ; Map < String , Set < String > > aMap ; aMap = new HashMap < String , TreeSet < String > > ( ) ; Compilation failed ( 26/05/2014 11:45:43 ) Error : line 2 - incompatible types - found java.util.HashMap < java.lang.String , java.util.TreeSet < java.lang.... | HashMap / TreeSet combination inconsistency |
Java | I try to learn about good practices in programming and I 'm stuck with this question . I know that in Java , recursive functions can be ' a pain in the ass ' ( sometimes ) , and I try to implement as much as I can the tail version of that function . Is it worth bothering with this or should I do in the old fashioned wa... | tailrec fun tail_fibonacci ( n : BigInteger , fib1 : BigInteger = BigInteger.ZERO , fib2 : BigInteger = BigInteger.ONE ) : BigInteger { return when ( n ) { BigInteger.ZERO - > fib1 else - > tail_fibonacci ( n.minus ( BigInteger.ONE ) , fib1.plus ( fib2 ) , fib1 ) } } fun iterative_fibonacci ( n : BigInteger ) : BigInte... | When using Java/Kotlin for programming is recommended to use Tail recursion or the Iterative version ? Is there any difference in performance ? |
Java | I created a class MyList that has a fieldI would like to be able to iterate the list like this : ( when my list is an instance of MyList ) .How ? What should I add to my class ? | private LinkedList < User > list ; for ( User user : myList ) { //do something with user } | How do I iterate a class of my creation in Java ? |
Java | Is there any difference performance-wise between the two code snippets below ? andFor me , I think the second one is better , but it is longer . The first one is shorter , but I am not really sure if it is faster . I am not sure , but to me it seems like every time that loop is iterated , auth.getProjects is called . I... | for ( String project : auth.getProjects ( ) ) { // Do something with 'project ' } String [ ] projects = auth.getProjects ( ) ; for ( String project : projects ) { // Do something with 'project ' } | Is there any difference between these two loops ? |
Java | A common pattern with a map is to check if a key exists and then act on the value only if it does , consider : However this is generally considered poor , as it requires two map lookups , where this alternative only requires one : Yet this second implementation has it 's own problems . In addition to being less concise... | if ( ! map.containsKey ( key ) ) { map.put ( key , new DefaultValue ( ) ) ; } return map.get ( key ) ; Value result = map.get ( key ) ; if ( result == null ) { result = new DefaultValue ( ) ; map.put ( key , result ) ; } return result ; public boolean containsKey ( Object key ) { return getEntry ( key ) ! = null ; } pu... | Why do n't common Map implementations cache the result of Map.containsKey ( ) for Map.get ( ) |
Java | can anybody explain this why its happeningit prints zero . | int i=0 ; i=i++ ; i=i++ ; i=i++ ; System.out.println ( i ) ; | unable to make out this assignment in java |
Java | I have a classI also have another classThe Log class works perfectly fine , I use it all the time . Now when I do this : I get the compiler error The method d ( String , Object ... ) in the type Log is not applicable for the arguments ( Configuration ) . I can solve this : My problem : How is this different ? In the fi... | class Configuration { // various stuff @ Override public String toString ( ) { // assemble outString return outString ; } } class Log { public static void d ( String format , Object ... d ) { // print the format using d } } Configuration config = getConfiguration ( ) ; Log.d ( config ) ; Log.d ( `` '' + config ) ; // s... | toString : When is it used ? |
Java | I 'm trying to dynamically load a Groovy script as a class but the class object is created even when the script 's code does not compile.For example , a simplified version of my Groovy code to load the Groovy script is as follows : Clearly , the code blah blah blah is n't a legitimate Groovy script . And yet , a class ... | GroovyCodeSource src = new GroovyCodeSource ( `` blah blah blah '' , `` Foo.groovy '' , GroovyShell.DEFAULT_CODE_BASE ) new GroovyClassLoader ( ) .parseClass ( src , true ) | GroovyClassLoader call to parseClass is successful , even when code does not compile |
Java | I have producer and consumer connected with BlockingQueue.Consumer wait records from queue and process it : I need pause this process for a while from other thread . How to implement it ? Now I think implement it such , but it 's looks like bad solution : | Record r = mQueue.take ( ) ; process ( r ) ; private Object mLock = new Object ( ) ; private boolean mLocked = false ; public void lock ( ) { mLocked = true ; } public void unlock ( ) { mLocked = false ; mLock.notify ( ) ; } public void run ( ) { ... . Record r = mQueue.take ( ) ; if ( mLocked ) { mLock.wait ( ) ; } pr... | Suspend consumer in producer/consumer pattern |
Java | example code : Question : will the literal string `` hi '' somehow stay in memory , even after the StringBuffer has been garbage collected ? Or is it just used to create a char array for the StringBuffer and then never put anywhere in memory ? | StringBuffer sb = new StringBuffer ( `` hi '' ) ; sb = null ; | StringBuilder / StringBuffer with literal string in memory |
Java | Some background : I created a contrived example to demonstrate use of VisualVM to my team . In particular , one method had an unnecessary synchronized keyword , and we saw threads in the thread pool blocking , where they did n't need to be . But removing that keyword had the surprising effect described below , and the ... | public class Main { private static ExecutorService exec = Executors.newFixedThreadPool ( 5 ) ; private final static int MATRIX_SIZE = 500 ; private static UncorrelatedRandomVectorGenerator generator = new UncorrelatedRandomVectorGenerator ( MATRIX_SIZE , new StableRandomGenerator ( new JDKRandomGenerator ( ) , 0.1d , 1... | Why does this code run faster with a lock ? |
Java | I am trying to change the default font in my app . But its not working . These are steps I have taken:1 ) Created class TypefaceUtil.java2 ) In a class extending Application:3 ) In styles.xmlStill its not working . Am I missing something ? | import android.content.Context ; import android.graphics.Typeface ; import android.util.Log ; import java.lang.reflect.Field ; public class TypefaceUtil { public static void overrideFont ( Context context , String defaultFontNameToOverride , String customFontFileNameInAssets ) { try { final Typeface customFontTypeface ... | Unable to change default font in Android app |
Java | I 'm missing some kind of collection functionality for a specific problem.I 'd like to start with a few informations about the problem 's background - maybe there 's a more elegant way to solve it , which does n't end in the specific problem I 'm stuck with : I 'm modelling a volume mesh made of tetrahedral cells ( the... | Cell getAdjacentCell ( Cell cell , int faceIndex ) { Face face = cell.getFace ( faceIndex ) ; Face partnerFace = face.getPartner ( ) ; if ( partnerFace == null ) return null ; // no adjacent cell present Cell adjacentCell = partnerFace.getCell ( ) ; return adjacentCell ; } Set < Face.Signature > faceSignatureCcw = new ... | Java : efficient Collection concept for a paired objects |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.