lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | Context : I 'm trying to create an animation in java.The animation is simply take an image and make it appear from the darkest pixels to the lightest.The Problem : The internal algorithm defining the pixels transformations is not my issue.I 'm new to Java and Computing in general . I 've done a bit of research , and kn... | import java.awt.Graphics2D ; import java.awt.image . * ; /** * @ author Psyny */public class ImageAppearFX { //Essencial Data BufferedImage imgProcessed ; int [ ] RAWoriginal ; int [ ] RAWprocessed ; WritableRaster rbgRasterProcessedW ; //Information about the image int x , y ; int [ ] mapBrightness ; public ImageAppea... | Fastest Performance Filtering an Image |
Java | I am still on a learning curve in Java . To understand a bit more of initializer blocks I created a small test class : When I create an instance , I get this log : This tells me , both initializer blocks run BEFORE the constructor , in the order they appear in the source code ( same as static initializers ) .What I wan... | public class Script { { Gadgets.log ( `` anonymous 1 '' ) ; } public Script ( ) { Gadgets.log ( `` constructor '' ) ; } { Gadgets.log ( `` anonymous 2 '' ) ; } } Script : anonymous 1Script : anonymous 2Script : constructor { // whatever code is needed for initialization goes here } | Non-Static initializer blocks - do I have a bit more control ? |
Java | We are trying to save many child in a short amount of time and hibernate keep giving OptimisticLockException.Here a simple exemple of that case : Where university_id can be null.The java object look like : It seem when we assign university and then save Student , if we do more than 4 in a short amount of time we will g... | Universityidnameaudit_versionStudent idname university_idaudit_version @ Entity @ Table ( name = `` university '' ) @ DynamicUpdate @ Data @ Accessors ( chain = true ) @ EqualsAndHashCode ( callSuper = true ) public class University { @ Id @ SequenceGenerator ( name = `` university_id_sequence_generator '' , sequenceNa... | Why does hibernate need to save the parent when saving the child and cause a OptimisticLockException even if there no change to the parent ? |
Java | I 'm running an UIMA application on apache spark . There are million of pages coming into batches to be processed by UIMA RUTA for calculation . But some time i 'm facing out of memory exception.It throws exception sometime as it successfully process 2000 pages but some time fail on 500 pages.Application LogUIMA RUTA S... | Caused by : java.lang.OutOfMemoryError : Java heap space at org.apache.uima.internal.util.IntArrayUtils.expand_size ( IntArrayUtils.java:57 ) at org.apache.uima.internal.util.IntArrayUtils.ensure_size ( IntArrayUtils.java:39 ) at org.apache.uima.cas.impl.Heap.grow ( Heap.java:187 ) at org.apache.uima.cas.impl.Heap.add ... | Uima Ruta Out of Memory issue in spark context |
Java | Could someone validate my understanding of the memory fence established after a constructor executes . For example , suppose I have a class called Stock.Further , assume that the constructor is executed by Thread1 and then updateQty ( ) and updatePrice ( ) are called several time by Thread2 ( always by Thread2 ) . My c... | public final class Stock { private final String ticker ; private double qty ; private double price ; public Stock ( String ticker , double qty , double price ) { this.ticker = ticker ; this.qty = qty ; this.price = price ; //I am assuming a memory fence gets inserted here . } public final void updateQty ( double qty ) ... | After an object is constructed , is a memory fence established with other threads ? |
Java | I pasted some code about Java concurrency : Why does return value ; need to be synchronized ? ? ? Is the return statement not atomic ? ? | public class ValueLatch < T > { @ GuardedBy ( `` this '' ) private T value = null ; private final CountDownLatch done = new CountDownLatch ( 1 ) ; public boolean isSet ( ) { return ( done.getCount ( ) == 0 ) ; } public synchronized void setValue ( T newValue ) { if ( ! isSet ( ) ) { value = newValue ; done.countDown ( ... | Is the return statement atomic ? |
Java | First time posting thought I would try this community out . I have researched for hours and i just cant seem to find an example close enough to get ideas from . I dont care what language answers are in but would prefer java , c/c++ , or pseudocode . I am looking to find consecutive paths of length n in a grid.I found a... | A B C A . C A B . A . . A . . A . . . . .. . . . B . C . . C B . . B . . B . . . .. . . . . . . . . . . . C . . . . C C . .. . . . . . . . . . . . . . . . . . B . .. . . . . . . . . . . . . . . . . . . A . ( spaces are for clarity only ) public class SimpleRecursive { private int ofLength ; private int paths = 0 ; priv... | How to memoize recursive path of length n search |
Java | In one module , I use spring-boot-starter-activemq:2.07.RELEASE which depends on activemq-broker:5.15.8 which depends on guava:18.0.In another module , I would like to use guava , so I have to use : If I use an higher version in my pom.xml this version will be also used by activemq-broker due to the nearest definition ... | < dependency > < groupId > com.google.guava < /groupId > < artifactId > guava < /artifactId > < version > 18.0 < /version > < /dependency > | How to automatically reuse dependency versions in a multi-module Maven project ? |
Java | The following code snippet returns 46059 on Java 6 and 48757 on Java 7 . Any ideas what might have changed ? | int i = 0 ; for ( char c = Character.MIN_VALUE ; c < Character.MAX_VALUE ; c++ ) { if ( Character.isLetterOrDigit ( c ) ) { i++ ; } } System.out.println ( i ) ; | Character.isLetterOrDigit ( char ) returns different value in java 6 and 7 |
Java | I 'm trying to figure out the options that I have for the architecture of my API project.I would like to create an API using JAX-RS version 1.0 . This API consumes Remote EJBs ( EJB 3.0 ) from a bigger , old and complex application . I 'm using Java 6.So far , I can do this and works . But I 'm not satisfied with the s... | /api/ /com.organization.api.v1.rs - > Rest Services with the JAX-RS annotations /com.organization.api.v1.services - > Service classes used by Rest Services . Basically , they only have the logic to transform the DTOs objects from Remote EJBs in JSON . This is separated by API version , because the JSON can be different... | Options to organize my project with : JAX-RS API , ServiceLocator and Remote EJBs |
Java | ( Merry Christmas btw ^^ ) Here is my problem ( in JAVA ) but it 's definitely an algorithmic problem and I do n't know how to solve it : / So here it is , with an example ( just for information , all my calculs are in Binary , so 1+1 = 0 ) let 's name variables : My goal with theses things , is to generate all the pos... | N : the number of elements in kernel . M : the length of an element in the kernel . int [ ] [ ] Kernel : ... . i : 0 1 1 1 0 1 0 1 0 1 1 1 0 1 1 1 0 1 0 1 0 1 1 1 0 ( length = M ) i+1 : 1 0 1 0 1 1 0 1 0 1 0 0 0 0 0 1 0 1 0 1 1 0 1 0 1 ( length = M ) ... . N : ... . Result [ 0 ] = 0 0 0 0 0 0 0 0 0 0 0 0 0 Result [ 1 ]... | 2^N Combinaisons with Integers ( Kernel ) , how to generate them ? |
Java | As per a literature I read , we have juicy fruits implementign the following interface : Using bounded type variables , following method would taks a bunch of fruits and squeeze them all : Now we need lower siblings as below to work too : So I would expect the method to look as follows : Instead I find the method signa... | public interface Juicy < T > { Juice < T > squeeze ( ) ; } < T extends Juicy < T > > List < Juice < T > > squeeze ( List < T > fruits ) ; class Orange extends Fruit implements Juicy < Orange > ; class RedOrange extends Orange ; < T extends Juicy < T > > List < Juice < ? super T > > squeeze ( List < ? extends T > fruits... | bounded generic method with 'super ' type |
Java | I 'm trying to run a javafx sample on a raspaberry pi 3 in a embedded environment ( buildroot ) , i want to run it without X. when i run the command : i get the following error : I ran the hello_triangle and hello_dispmanx examples to test gpu accelaration and there where no problems.Do n't know why i 'm getting the Co... | /root/jre-13.0.1/bin/java -Dfile.encoding=UTF-8 -- add-modules javafx.controls , javafx.fxml -Dprism.verbose=true -Djavafx.verbose=true -Dglass.platform=Monocle -Dprism.order=es2 -Djava.library.path=/root/jre-13.0.1/lib/ -Dembedded=monocle -jar /home/root/NetBeansProjects//JavaFXFXML/dist/JavaFXFXML.jar cmd : cd '/home... | JavaFX 0x300b : Could not get EGL surface |
Java | This is a question more about best practices/design patterns than regexps.In short I have 3 values : from , to and the value I want to change . From has to match one of several patterns : Whereas To has to be a decimal number . Depending on what value is given in From I have to check whether a value I want to change sa... | XX.X > XX.X > =XX.X < XX.X < =XX.XXX.X-XX.X | Best way to validate a String against many patterns |
Java | Quick disclaimer , I am very new to gRPC and RPC in general , so please have patienceI have two gRPC servers running on the same java application , Service A and Service B.Service A creates multiple clients of Service B which then synchronously makes calls to the various instances of Service BThe serverService A has a ... | rpc notifyPeers ( NotifyPeersRequest ) returns ( NotifyPeersResponse ) ; @ Overridepublic void notifyPeers ( NotifyPeersRequest request , StreamObserver < NotifyPeersResponse > responseObserver ) { logger.debug ( `` gRPC 'notifyPeers ' request received '' ) ; String host = request.getHost ( ) ; for ( PeerClient c : cli... | gRPC client not working when called from within gRPC service |
Java | I am using the Naga library to read data from a socket , which produces byte [ ] arrays which are received via a delegate function.My question is , how can I convert this byte array into specific data types , knowing the alignment ? For example , if the byte array contains the following data , in order : How can I extr... | | byte | byte | short | byte | int | int | | Dissect a byte array into distinct data types ? |
Java | This is kind of difficult to explain , but I 've looked everywhere , and I could n't find any good answer.I 've also seen Stack Overflow questions How can I refer to the class type a interface is implementing in Java ? and How do I return an instance of an object of the same type as the class passed in using Java 6 ? ,... | public interface SelfMaker < SELF > { public SELF getSelf ( ) ; } public class Dog implements SelfMaker < Dog > { String color ; public String toString ( ) { return `` some `` + color + `` dog '' ; } public Dog procreate ( Dog anotherDog ) { Dog son = getSelf ( ) ; son.color = color ; return son ; } @ Override public D... | How can I refer to the type of the current class ? |
Java | This is a nasty problem , and it might be that the design is just bad.Writing a set of simple charts components ( pie , bar & line charts ) and am choking on some generics stuff . In advance , I 'm sure there are many Java APIs for doing exactly what I 'm trying to do here ( charting/reports/etc . ) , however I 'm inte... | public abstract class Chart < T extends ChartComponent > { private List < T > components ; // ... rest of the Chart class } public abstract class ChartComponent { private Color color ; // .. rest of ChartComponent class } public class PieWedge extends ChartComponent { double wedgeValue ; // ... rest of PieWedge class }... | Inherited some bad Java generics |
Java | Which one is more efficient to instantiate a list ? OR | List < Type > list = new ArrayList < Type > ( 2 ) ; list.add ( new Type ( `` one '' ) ) ; list.add ( new Type ( `` two '' ) ) ; List < Type > list = Arrays.asList ( new Type ( `` one '' ) , new Type ( `` two '' ) ) ; | Which one is more efficient of using array list ? |
Java | I am building a Java Swing gui and I am wondering what the best way of managing all my images would be . So far I have just been creating images from different classes whenever they are needed , by pointing out the path of each one , for example : There are 2 things I do n't like . First thing would be having all those... | ImageIcon temp= new ImageIcon ( `` resources/pictures/temp.png '' ) ; | managing my Images in Java |
Java | Hey , im trying to wirte about 600000 Tokens into my MySQL Database Table . The Engine I 'm using is InnoDB . The update process is taking forever : ( . So my best guess is that I 'm totally missing something in my code and that what I 'm doing is just plain stupid.Perhaps someone has a spontaneous idea about what seem... | public void writeTokens ( Collection < Token > tokens ) { try { PreparedStatement updateToken = dbConnection.prepareStatement ( `` UPDATE tokens SET ` idTag ` = ? , ` Value ` = ? , ` Count ` = ? , ` Frequency ` = ? WHERE ` idToken ` = ? ; '' ) ; for ( Token token : tokens ) { updateToken.setInt ( 1 , 0 ) ; updateToken.... | MySQL Updates are taking forever |
Java | Hello I want this code to non recursive how I can do it ? It generates all the combinations from specific numbers . | public class test { public static void main ( String [ ] args ) { int [ ] array = new int [ ] { 0 , 1 , 2,3 } ; int size = 2 ; int [ ] tmp = new int [ size ] ; //Arrays.fill ( tmp , -1 ) ; generateCombinations ( array , 0 , 0 , tmp ) ; } private static void generateCombinations ( int [ ] array , int start , int depth ,... | recursive code to non recursive with loops |
Java | To distinguish between an instance field and a local variable of the same name we can qualify access to the field with the prefix this . : I 'm trying to do the same thing in a static context by qualifying access with the class name : The compiler wants nothing to do with this code . I have several variables like this ... | class Test { public final Foo x ; public Test ( Foo x ) { this.x = x ; } } import java.util . * ; class Test { public static final Map < String , Object > map ; static { Map < String , Object > map = new HashMap < > ( ) ; // ... // assume I fill the map with useful data here // ... // now I want to freeze it and assign... | Assign to static final field of same name |
Java | An article on the Oracle Java Community sites gives as an example ( for a JPA Converter , but that 's not relevant , I guess ) the following method : What is the use of casting the String y to a String val ? Is there a valid reason to do this ? Original article : What 's New in JPA | public Boolean convertToEntityAttribute ( String y ) { String val = ( String ) y ; if ( val.equals ( `` Y '' ) ) { return true ; } else { return false ; } } | Why cast a String to a String ? |
Java | I have a tree , represented as a list , It actually is a very large tree so what I would like to do is start the search if I ca n't find what I am looking for in say 100 ms save state , return , do some house keeping and then call search again and continue where I left off . Basically simulation I am working with is gi... | A / \ B C /\ \ D E F ( A ( B ( D ) ( E ) ) ( C ( F ) ) ) | Tree Search Saving Execution State |
Java | I am using this library which I have installed locally as a module . I 'm able to access it via my main project , but I 'm not able to do the opposite . For example , access a variable in my main project from this library ... I tried adding this line in the library 's build.gradle : But I get this weird error : How can... | implementation project ( ' : app ' ) Circular dependency between the following tasks : :placepicker : generateDebugRFile\ -- - : placepicker : generateDebugRFile ( * ) ( * ) - details omitted ( listed previously ) | Access main project from module in Android Studio ? |
Java | Probably a very noob questionI am new to java and am reading a third party api written in java ... I came across this declarationI am unable to understandWhy is this declaration like this ? What advantages does one get in declaring something like above and what are the alternatives to such declaration.Any advice/refere... | Foo foo = new FooBar ( ) .new Foo ( ) ; FooBar ( ) .new | unable to understand new keyword in java |
Java | RandomAccess is a marker interface in Java used by List implementations to indicate they have fast random access to their elements . Since it is designed specifically for List implementations , why is not in the List hierarchy ? For example , consider the following method that requires a RandomAccess list as input and ... | public < E , L extends List < E > & RandomAccess > E getRandomElement ( L list ) { ... } public < E , L extends RandomAccess < E > > E getRandomElement ( L list ) { ... } | Why is n't RandomAccess in the List hierarchy ? |
Java | I have following Java code , However , output is false . Can anybody help me , why this is not giving True ? | int a [ ] = new int [ ] { 20 , 30 } ; List lis = Arrays.asList ( a ) ; System.out.print ( lis.contains ( 20 ) ) ; | Java Array to List Issue |
Java | This program gives 6 as output , but when I uncomment the line 9 , output is 5 . Why ? I think b.a should n't change , should remain 5 in main . | 1 class C1 { 2 int a=5 ; 3 public static void main ( String args [ ] ) { 4 C1 b=new C1 ( ) ; 5 m1 ( b ) ; 6 System.out.println ( b.a ) ; 7 } 8 static void m1 ( C1 c ) { 9 //c=new C1 ( ) ; 10 c.a=6 ; 11 } 12 } | Pass by value/reference , what ? |
Java | Does not compile : Compiles OK : | void test ( Integer x ) { switch ( x ) { case ' a ' : } } void test ( Byte x ) { switch ( x ) { case ' a ' : } } | Why in a Java switch over an Integer wrapper , does a 'char ' case not compile , but compilation is OK when the switch is over Byte ? |
Java | We use SWT browser in our java app to render HTML content . The problems arise when the environment has a very high resolution ( 4K ) . When the content has a such html : And the used java source is : On regular environments with 1920x1080 and resolution is 96 , the rendered content and the viewed content in the Intern... | < html > < head > < style > .test { font-size : 35px ; font-family : Arial ; } < /style > < /head > < body > < div class='test ' > TEST < /div > < /body > < /html > import org.eclipse.swt.SWT ; import org.eclipse.swt.browser . * ; import org.eclipse.swt.layout . * ; import org.eclipse.swt.widgets . * ; public class SWT... | Java SWT Browser . Different output on screens with Ultra HD ( 4K ) or higher resolutions |
Java | I 've a problem to set button Visibility through another ActivityCode explanation : First , menu.xmlf2 button used for intent leveltwo.class but it still set to GONE , f2lock is ImageView for levellockedSecond , menu.javafollowing code to call levelone.java with a Resultso in levelone.java i put the code like thisthe c... | < Button android : id= '' @ +id/f1 '' android : layout_width= '' 50dp '' android : layout_height= '' 50dp '' android : layout_marginRight= '' 10dp '' android : background= '' @ drawable/button1 '' android : visibility= '' visible '' / > < ImageView android : id= '' @ +id/f2lock '' android : layout_width= '' 50dp '' and... | set button Visible in another acticty with Preferences setting |
Java | I am having the following preudo-codewhere the entire code has , let 's say 500 lines with lots of logic inside for statements . The problem is refactoring this into a readable and maintainable code and as a best practice for similar situations . Here are the possible solutions I found so far.1 : Split into methodsCons... | using ( some web service/disposable object ) { list1 = service.get1 ( ) ; list2 = service.get2 ( ) ; for ( item2 in list2 ) { list3 = service.get3 ( depending on item2 ) ; for ( item3 in list3 ) { list4 = service.get4 ( depending on item3 and list1 ) ; for ( item4 in list4 ) { ... } } } } for ( item2 in list2 ) { compu... | Refactoring inner loops with lots of dependencies between levels |
Java | My question is related to the following code : Now , as I 've commented in the code , what I 'm trying to achieve is a faster execution of my program by executing the 'while ' loop only when iPrime = true . 50 % of numbers are divisible by 2 and so this once this has been established the calculations can stop.I 'm doin... | public static void main ( String [ ] args ) { // Find Prime Numbers from 0 to 100 int i ; for ( i=2 ; i < = 100 ; i++ ) { int j = 2 ; boolean iPrime = true ; //The following line gives incorrect results , but should execute faster // while ( ( iPrime = true ) & & ( j < ( i / 2 + 1 ) ) ) { //The following line gives cor... | Using logic inside a switch statement |
Java | In the implementation details of HashMap , I can read : If I have constant hashCode and fine equals and my class does n't implement Comparable how exactly it will break the ties and how the tree will be constructed ? I mean - bucket will transform to a tree and will use System.identityHashCode to break a tie.Then I wil... | When using comparators on insertion , to keep a * total ordering ( or as close as is required here ) across * rebalancings , we compare classes and identityHashCodes as * tie-breakers . | IdentityHashCode in HashMap 's bucket |
Java | App running with JSF , Primefaces , eclipselink , not a small app , about 100 pages/bean all working perfectlyI got some troubles understanding how my @ ViewScoped page works , I got a select UI component , filled with a simple List < People > and a back-end selectedPeople in my beanSequence of use and problem is ( inf... | // all getters , setters , JPA annotations , all goodpublic class People { private String name ; private List < Car > cars ; } @ ManagedBean @ ViewScopedpublic class PeopleBean { @ EJB private Service sPeople ; private People selectedPeople ; private List < People > listPpl ; @ PostConstruct public void init ( ) { list... | How to deal with 'cached ' instance in @ ViewScoped page ? |
Java | I used to believe that any variable that is shared between two threads , can be cached thread-locally and should be declared as volatile . But that belief has been challenged recently by a teammate . We are trying to figure out whether volatile is required in the following case or not.Now my contention is that , it is ... | class Class1 { void Method1 ( ) { Worker worker = new Worker ( ) ; worker.start ( ) ; ... System.out.println ( worker.value ) ; // want to poll value at this instant ... } class Worker extends Thread { int value = 0 ; // Should this be declared as a volatile ? public void run ( ) { ... value = 1 ; // this is the only p... | Volatility of objects other than class variables |
Java | I found a quiz about Java 8 Stream API of peek method as belowThe output isI am confused how this stream works ? My expected result should be The peek ( ) method is an intermediate operation and it processes each element in Stream . Can anyone explain me this . | Arrays.asList ( `` Fred '' , `` Jim '' , `` Sheila '' ) .stream ( ) .peek ( System.out : :println ) .allMatch ( s - > s.startsWith ( `` F '' ) ) ; FredJim FredJimSheila | How peek ( ) and allMatch ( ) works together in Java 8 Stream API |
Java | The following algorithm is used to find a basin in matrix . The whole question is as follows : 2-D matrix is given where each cell represents height of cell . Water can flow from cell with higher height to lower one . A basin is when there is no cell with lower height in the neighbours ( left , right , up , down , diag... | public final class Basin { private Basin ( ) { } private static enum Direction { NW ( -1 , -1 ) , N ( 0 , -1 ) , NE ( -1 , 1 ) , E ( 0 , 1 ) , SE ( 1 , 1 ) , S ( 1 , 0 ) , SW ( 1 , -1 ) , W ( -1 , 0 ) ; private int rowDelta ; private int colDelta ; Direction ( int rowDelta , int colDelta ) { this.rowDelta = rowDelta ; ... | Time Complexity of finding a basin |
Java | I want to get response after post data but it fails . I want to create a login system , I have successfully submited data to php file , everything is working fine now I want to get response from same function but I 'm unable to know where the issue is . Here is the Java function : And here is php code : Please help me ... | public class PostDataGetRes extends AsyncTask < String , String , String > { protected void onPreExecute ( ) { super.onPreExecute ( ) ; } @ Override protected String doInBackground ( String ... strings ) { try { postRData ( ) ; } catch ( NullPointerException e ) { e.printStackTrace ( ) ; } catch ( Exception e ) { e.pri... | Why does n't the function get data from php in android ? |
Java | This is my first attempt : But when I try to compile this I get the following error : What I do n't understand is the world class has no relationship to the type variable but javac thinks it does . What am I doing wrong ? | import java.util.function . * ; import java.util.ArrayList ; public class IO < A > { private Function < World , Tuple < World , A > > transform ; private class World { private ArrayList < String > stdin ; private ArrayList < String > stdout ; public World ( ) { this.stdin = new ArrayList < String > ( ) ; this.stdout = ... | How do you implement Haskell 's IO type in Java ? |
Java | Why is this not allowed in Java ? Why do we have to declare variable v in the for loop initialization ? I know it 's not a statement if I do it like that but why does n't Java allow the above ? | int v = 0 ; for ( v ; v < 2 ; v++ ) { ... } | Why must a variable be declared in a for loop initialization ? |
Java | I have the following Hibernate code which I believe should be working , but it throws an error : org.springframework.web.util.NestedServletException : Request processing failed ; nested exception is org.hibernate.exception.SQLGrammarException : ERROR : syntax error at or near `` . '' Position : 503The relevant code is ... | @ Overridepublic List < RepositoryLink > getRepositoryLinks ( final DugaUser user ) { Query query = sessionFactory.getCurrentSession ( ) .createQuery ( `` from RepositoryLink link where : user in ( link.dugaUsers ) '' ) ; query.setParameter ( `` user '' , user ) ; return query.list ( ) ; } @ Entity @ Table ( name = `` ... | Check if Entity is in list of mapped entities |
Java | While I am trying to convert yaml string to Map I am getting key change.YAML File : -Java code : -output : -in above output false is replace with `` NO '' , but I need `` NO '' as it is.Expected output : - | -- -HK : isp : Airtel : AirtelChennal www.enemalta.com : default : defaultEma user1 : chennal1 studiodefault : hkDefaultchennal country : DK : denmarkChennal NO : chennal2 Yaml yaml= new Yaml ( ) ; Map < String , Object > map= ( Map < String , Object > ) yaml.load ( yamlString ) ; { HK= { isp= { Airtel=AirtelChennal } ... | unable to convert yaml string to map with key `` NO '' in java |
Java | I have got this doubt many times , but did n't figure it out the correct soltion . This time I want clear it off . I have situation likewhat are the trade offs between first way and second way ? which one is better in storing the result in a variable or calling the function two times ? | 1 . String sNumber= '' ksadfl.jksadlf '' ; if ( sNumber.lastIndexOf ( ' . ' ) > 0 ) //do something ... ... if ( sNumber.lastIndexOf ( ' . ' ) > 1 ) //do something ... 2.int index = sNumber.lastIndexOf ( ' . ' ) ; if ( index > 0 ) //do something ... ... if ( index > 1 ) //do something ... | Which one is better in calling a function : two times or storing the result in a variable ? |
Java | I want to compare two List and give point to listOneor listTwo depending on which value is greaterHere is my tested codeIt works , but its not outputting the expected answer expected output : 2 1 output am getting : 2 1 0 0 | List < Integer > listOne= new ArrayList < > ( ) ; listOne.add ( 10 ) ; listOne.add ( 2 ) ; listOne.add ( 3 ) ; //Second Array List < Integer > listTwo= new ArrayList < > ( ) ; listTwo.add ( 3 ) ; listTwo.add ( 7 ) ; listTwo.add ( 1 ) ; [ 10 , 2 , 3 ] compare to [ 3 , 7 , 1 ] if listOne.get ( 0 ) > listTwo.get ( 0 ) //a... | Comparing List < Integer > by index |
Java | I am using IntelliJ for the Java Projects . As I am new to Java , I tried Ant as a build tool in my project.When I am using Junit 4.11 in my Ant build file , I am getting the following errors : And when I used Junit 4.8.2 , then all the tests ran successfully.Can anyone tell me please , what is this issue ? Thanks in a... | [ javac ] /Users/rajatg/fizz-buzz/src/test/FizzBuzzTest.java:4 : error : package org.hamcrest.core does not exist [ javac ] import static org.hamcrest.core.Is.is ; [ javac ] ^ [ javac ] /Users/rajatg/fizz-buzz/src/test/FizzBuzzTest.java:4 : error : static import only from classes and interfaces [ javac ] import static ... | Why JUnit 4.11 is not working in Ant build file , but JUnit 4.8.2 is working fine ? |
Java | It will return `` 10 '' .Now I just replace Return type Integer to StringBuilder and Output was changed.OutPut is `` abcaaa '' So , Anybody can explain me in detail. ? what are the differences . ? | public class J { public Integer method ( Integer x ) { Integer val = x ; try { return val ; } finally { val = x + x ; } } public static void main ( String [ ] args ) { J littleFuzzy = new J ( ) ; System.out.println ( littleFuzzy.method ( new Integer ( 10 ) ) ) ; } } public class I { public StringBuilder method ( String... | Behavior of return statement in catch and finally |
Java | Part of the code : The last line returns null . The API documentation says : `` the eval method returns null if something went wrong '' . How do I find out what went wrong ? | Rengine re = getRengine ( ) ; re.eval ( `` library ( quantmod ) '' ) ; re.eval ( `` library ( PerformanceAnalytics ) '' ) ; re.eval ( `` library ( tseries ) '' ) ; re.eval ( `` library ( FinTS ) '' ) ; re.eval ( `` library ( rugarch ) '' ) ; re.eval ( `` library ( robustbase ) '' ) ; re.assign ( `` arLagNum '' , new do... | How to find what went wrong during eval in R ? |
Java | I have a weird ( to me anyway ) issue with Hibernate which I ca n't make any sense of.The code below is my attempt at modeling a ManyToOne relation with an attribute between the entities Case and Suggestion using an additional entity CaseToSuggestion with Case being my aggregate root : If I create new objects for the a... | @ Entity @ Table ( name = `` sga_cases '' ) public class Case { @ Id @ GeneratedValue ( strategy = GenerationType.AUTO ) private int id ; // Business key @ Column ( name = `` caseid '' , unique = true , nullable = false ) private String caseId ; ... @ OneToMany ( mappedBy = `` associatedCase '' , orphanRemoval = true ,... | Hibernate generates ghost entries for new child entities |
Java | I 'm trying to update a phonegap Android app from cordova 3.5.0 to cordova 5.1.1 because of security concerns.When I launch the app I get the following errors but I just ca n't understand where they come from.. Could you help me by suggesting where to investigate ? | W/System.err ( 1672 ) : org.json.JSONException : Value PluginManager at 0 of type java.lang.String can not be converted to intW/System.err ( 1672 ) : at org.json.JSON.typeMismatch ( JSON.java:100 ) W/System.err ( 1672 ) : at org.json.JSONArray.getInt ( JSONArray.java:357 ) W/System.err ( 1672 ) : at org.apache.cordova.... | Errors upgrading cordova app |
Java | I 'm working on a utility for supporting context-dependent injection , i.e . what gets injected can now also depend on where it is injected . Logger injection is a common application of this technique.So far , I 've successfully implemented this for HK2 and Guice , and with some limitations for Dagger.To solve this for... | class BaseClass { @ Inject Logger logger ; } class SubClass extends BaseClass { } | Accessing `` containing class '' from DependencyDescriptor |
Java | I need to find out the first outermost ( not nested ) brackets indexes.For exampleI can find it by lots of conditions , current code : Is there more clean way to do it ? | [ ] output : 0 , 11 [ 2 ] output : 1 , 33 [ a2 [ c ] ] 2 [ abc ] 3 [ cd ] output : 1 , 7 public static void main ( String [ ] args ) { String input = `` 3 [ a2 [ c ] ] 2 [ abc ] 3 [ cd ] ef '' ; int first = 0 ; int second = 0 ; int count = 0 ; boolean found = false ; for ( int index = 0 ; index < input.length ( ) ; ind... | Find the first outer brackets |
Java | I have a doubt that why compilier is not showing any error since doit ( 4,5 ) is causing ambiguityWhen I ru the code , I get output as a ad not b why ? | public class Demo { public static String doit ( int x , int y ) { return '' a '' ; } public static String doit ( int ... val ) { return `` b '' ; } public static void main ( String args [ ] ) { System.out.println ( doit ( 4,5 ) ) ; } } | variable argument in java |
Java | I searched a looooot and Im not able to find the solution for my problem.Im using osgi , karaf and java 8.I have some modules , for example : WEBSERVICE-SOMETHINGinside this module lets say API , PERSISTENCE , ADAPTERpersistence and api starts fine , but adapter gives that error : the chains are in the adapter and the ... | Uses constraint violation . Unable to resolve resource adapter [ adapter [ 288 ] ( R 288.2 ) ] because it is exposed to package 'javax.xml.bind.annotation ' from resources org.apache.felix.framework [ org.apache.felix.framework [ 0 ] ( R 0 ) ] and jakarta.xml.bind-api [ jakarta.xml.bind-api [ 79 ] ( R 79.0 ) ] via two ... | Uses constraint violation . Unable to resolve resource -javax.xml.bind.annotation and jakarta.xml.bind-api |
Java | The following code compiles ( and runs tests as expected ) in Eclipse : However , compiling with either javac ( JDK 7 ) directly or via Maven fails with the following error : To be honest , the complexity of enums + interfaces + type-parameters ( generics ) all at play at once threw me off as I was writing the code , b... | import java.util.EnumSet ; public class EnumTest { static enum Cloneables implements Cloneable { One , Two , Three ; } public < T extends Cloneable > T getOne ( Class enumType ) { EnumSet < ? extends T > set = EnumSet.allOf ( enumType ) ; return set.iterator ( ) .next ( ) ; } } type argument ? extends T is not within b... | Discrepancy between Eclipse compiler and javac - Enums , interfaces , and generics |
Java | Take a look that the following code snippet : Suppose A 's constructor throws a runtime exception . At the marked line , am I always guaranteed to get a NullPointerException , or foo ( ) will get invoked on a half constructed instance ? | A a = nulltry { a = new A ( ) ; } finally { a.foo ( ) ; // What happens at this point ? } | ` return value ' from Constructor Exception in Java ? |
Java | tl ; dr is there JavaDoc for ifs ? IntroI am writing an enterprise application for multiple customers . 99 % of the code base is shared , but every now and then there is a variant like this : I would now like to document all these variants for the users . It should be clear from the documentation what happens if I turn... | if ( user.hasModule ( REPORTS ) ) { ... conditional code ... } /** Enables the cool report . */if ( user.hasModule ( REPORTS ) ) { ... conditional code ... } @ Doc ( text= '' Enables the cool report . `` ) if ( user.hasModule ( REPORTS ) ) { ... conditional code ... } if ( user.hasModule ( REPORTS , `` Enables the cool... | How to document code with variants ? ( JavaDoc for ifs ) |
Java | I am developing a space combat game in Java as part of an ongoing effort to learn the language . In a battle , I have k ships firing their guns at a fleet of n of their nefarious enemies . Depending on how many of their enemies get hit by how many of the shots , ( each ship fires one shot which hits one enemy ) , some ... | Number of hits | Number of occurences | Total shots -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 | 30 | 30 2 | 12 | 24 3 | 4 | 12 4 | 7 | 28 5 | 1 | 5 | How to generate a distribution of k shots on n enemies |
Java | I have the follwing Java 9 module : With an exported type : And a non-exported type : The exported type uses the non-exported type as a method parameter type in a public method . I 'd have assumed that the compiler would reject such an inconsistent class configuration , as clients in other modules could not really invo... | module com.example.a { exports com.example.a ; } public class Api { public static void foo ( ImplDetail args ) { } } package com.example.b.internal ; public class ImplDetail { } | Why does compilation of public APIs leaking internal types not fail ? |
Java | I am trying to read a .txt file and use each sentence as a name for a team , and at the same time use that name to seek out another .txt file to get its content . All the .txt files are at the root of my assets folder . The first .txt file works fine , I use assetmanager.open and readLine ( ) to obtain the string , but... | private void loadTeams ( ) { try { BufferedReader r = new BufferedReader ( new InputStreamReader ( assetManager.open ( `` matches.txt '' ) ) ) ; String name , bio , trainer ; for ( int i = 0 ; i < 4 ; i++ ) { name = r.readLine ( ) ; bio = r.readLine ( ) ; trainer = r.readLine ( ) ; System.out.println ( name+ '' , `` +b... | Strings contain the same characters but are still different |
Java | I have a server somewhat like this : As you can see , there are threads handling requests and a thread initing the server . Requests can come in before initing has finished , therefore there is the check with an IllegalStateException.Now , to make this thread safe ( so request handler threads do n't see a stale , null-... | class Server { private WorkingThing worker ; public void init ( ) { runInNewThread ( { // this will take about a minute worker = new WorkingThing ( ) ; } ) ; } public Response handleRequest ( Request req ) { if ( worker == null ) throw new IllegalStateException ( `` Not inited yet '' ) ; return worker.work ( req ) ; } ... | Thread-safe but fast access to an `` eventually final '' variable ? |
Java | I am having issues using java generics - specifically , using wildcard capture . Here is a simplified version of the code I have that exhibits the problem I am seeing . It is driving me crazy : Package declaration and imports are not included - otherwise this is complete . This does not compile . The problem is with th... | public class Task { private Action < ActionResult , ? extends ActionSubject > action ; private ActionSubject subject = new ActionSubjectImpl ( ) ; private List < ActionResult > list = new ArrayList < > ( ) ; public static void main ( String [ ] args ) { Task task = new Task ( ) ; task.setAction ( new ActionImpl ( ) ) ;... | How do I resolve this wildcard capture issue when using java generics ? |
Java | I have the following method declaration : When I use it in the following way : it works fine but shows the type safety warnings.But when I provide the generic type to the SentCallback , like : it show the following compilation error : The method executeAsync ( Method , Callback ) in the type AbsSender is not applicable... | public < T extends Serializable , Method extends BotApiMethod < T > , Callback extends SentCallback < T > > void executeAsync ( Method method , Callback callback ) executeAsync ( editMessage , new SentCallback ( ) { executeAsync ( editMessage , new SentCallback < Message > ( ) | Java 8 generics compatibility |
Java | I 'm trying to use IntelliJ SDK as standalone java parser and it works fine in most cases , but failing to resolve return type of generic methods.When I debugging resolveMethod for verify ( mock ) .simpleMethod ( ) in next sample inside of IntelliJ : I see return type of verify ( mock ) as IMethods and simpleMethod als... | public class ResolutionTest { private interface IMethods { String simpleMethod ( ) ; } private IMethods mock ; public static < T > T verify ( T m ) { return m ; } public void test ( ) { verify ( mock ) .simpleMethod ( ) ; } } import com.intellij.codeInsight.ContainerProvider ; import com.intellij.codeInsight.runner.Jav... | Symbols resolution in standalone IntelliJ parser |
Java | I 'm writing an IntelliJ-Plugin to analyse java-program code . Thus i use Soot to write static analyses . Every time a user triggers the analyse-action of my plugin , I take the current VirtualFile of the current context like this : When I check the content of this file all changes are applied . After this I 'm loading... | FileEditorManager manager = FileEditorManager.getInstance ( e.getProject ( ) ) ; VirtualFile files [ ] = manager.getSelectedFiles ( ) ; toAnalyse = files [ 0 ] ; [ ... ] String dir = toAnalyse.getParent ( ) .getPath ( ) ; Options.v ( ) .setPhaseOption ( `` jb '' , `` use-original-names '' ) ; Options.v ( ) .set_soot_cl... | Soot : Reload class after source-file changed |
Java | The above regex for validating zip code seems to allow exclamation ( ! ) even though I have n't allowed it here . Not sure what the mistake is ? Do I need to change the regex pattern | public static final String REGEX_ADDRESS_ZIP = `` ^ [ 0-9\\ - . ] + $ '' ; | How do I prevent exclamations via a regex |
Java | I have three entities as follows : Now , given an Instance of EntityA , i want to get a list of EntityC . I have two options available to me currently . I do n't know which one is more optimized . The options are:2.Add a new property to EntityBWhich of these two queries is easier and optimized ? | public class EntityA { private Long id ; //Getters and setters } public class EntityB { private Long id ; private EntityA entitya ; //Getters and setters } public class EntityC { private Long id ; private BigDecimal amount ; private EntityB entityb ; //Getters and setters } 1.select c from EntityC c where c.entityb in ... | How to Optimise a JPA Query |
Java | I am creating a Word Comparison class and it will count the occurrences of words as well . ( This is Java ) This was my original method : My IDE suggested that the loop and list assignment could be replaced with a `` collect call '' : `` stream api calls '' In which it generated this code : I am kinda confused on how t... | /** * @ param map The map of words to search * @ param num The number of words you want printed * @ return list of words */public static List < String > findMaxOccurrence ( Map < String , Integer > map , int num ) { List < WordComparable > l = new ArrayList < > ( ) ; for ( Map.Entry < String , Integer > entry : map.ent... | Explanation of this Lambda Expression |
Java | Okay , so I 'm making a dynamic 2D array in Java that implements the java.util.Collection interface . I made my array implement it because I wanted it to have the same functionality as a normal Collection . However , I can not implement the size ( ) method because in the interface it returns an integer and a 2D matrix ... | public abstract class AbstractMatrix < E > implements Collection < E > { @ Override public long size ( ) { return columns * rows ; } } | Can a dynamic 2D array implement the Java.Collection.size ( ) method ? |
Java | ( preliminary note : maybe this is better suited for codereview ? ) EDIT Answer to self ; I believe this answer covers all my needs/problems , but of course , comments are welcome . Original question left below for reference.Hello , Of interest here is the .getSources ( ) method . This method is meant to return a list ... | protected abstract MessageSource tryAndLookup ( final Locale locale ) throws IOException ; /** * Set of locales known to have failed lookup . * * < p > When a locale is in this set , it will not attempt to be reloaded. < /p > */private final Set < Locale > lookupFailures = new CopyOnWriteArraySet < Locale > ( ) ; /** *... | Ways to improve upon that code using only JDK ( 6 ) provided classes ? ( concurrency , thread safety ) |
Java | There is this Javascript function that I 'm trying to rewrite in Java : My Java adaptation : When I pass -1954896768 , Javascript version returns 70528 , while Java returns -896768 . I 'm not sure why . The difference seems to start inside the if condition : in Javascript function after the if encodingRound2 = 23400705... | function normalizeHash ( encondindRound2 ) { if ( encondindRound2 < 0 ) { encondindRound2 = ( encondindRound2 & 0x7fffffff ) + 0x80000000 ; } return encondindRound2 % 1E6 ; } public long normalizeHash ( long encondindRound2 ) { if ( encondindRound2 < 0 ) { encondindRound2 = ( ( ( int ) encondindRound2 ) & 0x7fffffff ) ... | Javascript function rewritten in Java gives different results |
Java | I was reading the java 8 language specification type inference . It says thatwould be first reducedand then to and at the end to I 'm having a hard time understanding how the reduction of the constraint was derived . It would be a great help if anyone can point out the logic using the java 8 language spec . Here 's the... | List < String > ls = new ArrayList < > ( ) ArrayList < α > - > List < String > α < = String α = String ArrayList < α > - > List < String > to α < = String new ArrayList < > - > List < String > to ArrayList < α > - > List < String > ArrayList < α > - > List < String > | Java 8 Type Inference - How reduction is done for generic constructors ? |
Java | I 'm attempting to use JDOM2 in order to extract the information I care about out of a XML document . How do I get a tag within a tag ? I have been only partially successful . While I have been able to use xpath to extract < record > tags , the xpath query to extract the title , description and other data with in the r... | < record > < header > < identifier > oai : lcoa1.loc.gov : loc.pnp/cph.3a02293 < /identifier > < datestamp > 2009-05-27T07:22:37Z < /datestamp > < setSpec > cwp < /setSpec > < setSpec > lcphotos < /setSpec > < /header > < metadata > < oai_dc : dc xsi : schemaLocation= '' http : //www.openarchives.org/OAI/2.0/oai_dc/ ht... | JDOM2 xpath finding nodes within a different namespace |
Java | I 'm doing a Java Record/Replay tool and I need to launch Java applications from my main Java app . I need access to the EventDispatchThread in order to intercept the events and record them , so I 'm launching the application through reflection with ( code snippet simplified ) : I previously dynamically load all the ja... | Class < ? > app = Class.forName ( mainClass ) ; Method m = app.getMethod ( `` main '' , new Class [ ] { String [ ] .class } ) ; m.invoke ( null , new Object [ ] { new String [ ] { } } ) ; | Launch a java application from another java application |
Java | I 'm new to swing , any help appreciated.In this piece of code I 'm turning a card over face up , if it turns out that they do n't match I want them to turn back face down again.At the moment what is happening:1. when clicked the first card turns over 2. when a second card is clicked either of two things happen ( a ) i... | Console output : Card : 0 setCard : 6 setSleeping nowCard : 6 unsetCard : 0 unset @ Overridepublic void actionPerformed ( ActionEvent e ) { String buttonPressed = e.getActionCommand ( ) ; int pos = Integer.valueOf ( buttonPressed ) ; action = Control.model.ReceiveCardsTurned ( pos ) ; keypadArray [ pos ] .setIcon ( myI... | Updating swing components correctly ? |
Java | I ran into an issue while manipulating some bytecode , where a certain final String constant was not inlined by the java compiler ( Java 8 ) , see the example below : Resulting bytecode with javac ( 1.8.0_101 ) You can see that the second time the fields ENABLED and DISABLED are being accessed , the compiler did not in... | public class MyTest { private static final String ENABLED = `` Y '' ; private static final String DISABLED = `` N '' ; private static boolean isEnabled ( String key ) { return key.equals ( `` A '' ) ; } private static String getString ( String key , String value ) { return key + value ; } public static void main ( Stri... | Does the JLS require inlining of final String constants ? |
Java | For copying file in S3 , I am using vfs-s3-2.2.1.jar I found S3FileObject class under com.intridea.io.vfs.provider.s3 package.In which I am using public void copyFrom ( final FileObject file , final FileSelector selector ) method for copy file.In this method I found following code : In official reference it uses these ... | try { if ( srcFile.getType ( ) .hasChildren ( ) ) { destFile.createFolder ( ) ; // do server side copy if both source and dest are in S3 and using same credentials } else if ( srcFile instanceof S3FileObject ) { S3FileObject s3SrcFile = ( S3FileObject ) srcFile ; String srcBucketName = s3SrcFile.getBucket ( ) .getName ... | java : Use Server-Side Encryption in Amazon S3 using vfs s3 plugin |
Java | How many memory locations will it take to have a string concatenation ? In following two statements : and and Which will consume more memory ? In which of the case StringBuilder is useful to the most ? | String myStringVariable = `` Hello '' ; String s = `` ABC '' + `` Hello '' + `` DEF '' ; String s = `` ABC '' ; s = s + `` Hello '' ; s = s + `` DEF '' ; String s = `` ABC '' + myStringVariable + `` DEF '' ; | How many memory locations will it take to have a string concatenation ? |
Java | In the `` 95 % of performance is about clean representative models '' talk by Martin Thompson , between 17 and 21 minute , such code is presented : In 20:16 he says : You can get much better performance , so leaving things like capacity in there is the right thing to do.I tried to come up with a code example in which c... | public class Queue { private final Object [ ] buffer ; private final int capacity ; // Rest of the code } | Is using own int capacity faster than using .length field of an array ? |
Java | Briefly : collect ( groupingBy ( ) ) returns a map Map < K , List < T > > . How can I replace , for each K , the value List < T > by a new value ( of class U ) which is computed based on List < T > , and return Map < K , U > in the same stream ( ) ? An example : Suppose I have a Task , which consists of a taskId and a ... | public class Task { int taskId ; List < Job > jobList ; } // in class Jobint getAgentId ( ) { // return the `` agent '' who is responsible for @ param job } // in class Partition ; ` Integer ` for `` agent '' idMap < Integer , Task > partition ( Task task ) { } Map < Integer , Task > partition ( Task task ) { int id = ... | How to process the resulting List < T > values of ` groupingBy ` in the same ` stream ( ) ` ? |
Java | I 'd like to sync a large list of items between the client and the server . Since the list is pretty big I ca n't sync it in a single request so , how can I ensure the list to be synched with a reasonable amount of calls to the synchronization service ? For example : And I want to sync a list with 100.000 items so I ma... | getItems ( int offset , int quantity ) : Item [ ] getItems ( 0,100 ) : Return items ( in the original list ) [ 0,100 ) getItems ( 100,100 ) : Return items ( in the original list ) [ 100,200 ) # # # # # before the next call the items 0-100 are removed # # # # getItems ( 200,100 ) : Return items ( in the original list ) ... | How to sync large lists between client and server |
Java | I came across the example below of a Java class which was claimed to be thread-safe . Could anyone please explain how it could be thread-safe ? I can clearly see that the last method in the class is not being guarded against concurrent access of any reader thread . Or , am I missing something here ? | public class Account { private Lock lock = new ReentrantLock ( ) ; private int value = 0 ; public void increment ( ) { lock.lock ( ) ; value++ ; lock.unlock ( ) ; } public void decrement ( ) { lock.lock ( ) ; value -- ; lock.unlock ( ) ; } public int getValue ( ) { return value ; } } | Does partial thread-safety make a Java class thread-safe ? |
Java | I watched a code from JavaDays , author said that this approach with probability is very effective for storing Strings like analogue to String intern methodPlease , explain me , what is effect of probability in this line : This is original presentation from Java Days https : //shipilev.net/talks/jpoint-April2015-string... | public class CHMDeduplicator < T > { private final int prob ; private final Map < T , T > map ; public CHMDeduplicator ( double prob ) { this.prob = ( int ) ( Integer.MIN_VALUE + prob * ( 1L < < 32 ) ) ; this.map = new ConcurrentHashMap < > ( ) ; } public T dedup ( T t ) { if ( ThreadLocalRandom.current ( ) .nextInt ( ... | Deduplication for String intern method in ConcurrentHashMap |
Java | Would someone please tell me why i am getting a dead code warning in the else branch of if ( projectId ! = null ) ? If i got this right , the interpreter thinks projectId can never be null - is that right ? In my opinion this is not possible ... Even if i put aor ain front ofthe result is always the same ! Please help ... | Integer projectId = null ; if ( ! sprintTaskConnections.isEmpty ( ) ) projectId = sprintTaskConnections.get ( 0 ) .getProjectId ( ) ; // init name , state , startDate , endDate hereJiraSprint sprint = new JiraSprint ( sprintInfo.getInt ( `` id '' ) , name , state , projectId , startDate , endDate ) ; if ( projectId ! =... | Why do I get a `` dead code '' warning in this Java code ? |
Java | I 'm surprised by how painful it is to use java.util.ArrayList < T > .toArray ( ) .Suppose I declare my array list as : Then to convert it to an array , I have to do one of the following : or : or : None of the above are very readable . Should n't I be able to say the following instead ? But that gives a compile error ... | java.util.ArrayList < double [ ] > arrayList = new java.util.ArrayList < double [ ] > ( ) ; ... add some items ... double [ ] [ ] array = ( double [ ] [ ] ) arrayList.toArray ( new double [ 0 ] [ ] ) ; double [ ] [ ] array = ( double [ ] [ ] ) arrayList.toArray ( new double [ arrayList.size ( ) ] [ ] ) ; double [ ] [ ]... | Could java.util.ArrayList < T > .toArray ( ) be made friendlier ? |
Java | Is the following program guaranteed to produce a list with the same contents and ordering in future java releases ? The javadoc of the java.util.Random class guarantees that it will always return the same random numbers if intialized with the same seed in all future java releases.But are there any guarantees regarding ... | import java.util.ArrayList ; import java.util.Arrays ; import java.util.Collections ; import java.util.List ; import java.util.Random ; public class Test { public static void main ( String [ ] args ) { List < String > list = new ArrayList < > ( Arrays.asList ( `` A '' , `` B '' , `` C '' , `` D '' ) ) ; Collections.shu... | Is there any guarantee that the algorithm behind java.util.Collections.shuffle ( ) remains unchanged in future Java releases ? |
Java | I 'm writing tests for my program . Sometimes my tests work , and sometimes they fail . I 'm trying to track down all of the sources of nondeterminism.Here 's a simple , self-contained example of my problem : This program creates an ArrayList . It tries to access element -1 repeatedly . Initially , this creates a detai... | import java.util.ArrayList ; public class ArrayExceptions { public static void main ( String [ ] args ) { final int ITERATIONS = 10000 ; ArrayList < Integer > list = new ArrayList < > ( ) ; try { list.get ( -1 ) ; } catch ( ArrayIndexOutOfBoundsException e ) { e.printStackTrace ( ) ; } for ( int i = 0 ; i < ITERATIONS ... | Repeatedly thrown ArrayIndexOutOfBoundsException stop producing stack traces |
Java | Here 's what I know , if there 's any errors , let me know . Example watch faces , like the analog watch face , in the SDK use a deprecated Time object for managing time.According to the documentation Time was deprecated in level 22 ( Android 5.1 ) . Now obviously it still has a lot of life , but in the interests of fu... | long timeStart = 0 ; long timeEndcalendarStart = 0 ; long timeDifference = 0 ; long calendarEnd = 0 ; long calendarDifference = 0 ; for ( int index = 0 ; index < 30000 ; index++ ) { timeStart = System.currentTimeMillis ( ) ; Time testTime = new Time ( ) ; testTime.setToNow ( ) ; long mills = testTime.toMillis ( false )... | Android Wear : Is there any reason to use a Time object rather than a Calendar object ? |
Java | I am building a stacked bar chart , however when I specify a min value for the axis the rendering of bars gets warped , and the axis scale/steps is erroneous . A line series I have added does however work as expected.Here is the initial chart : When I supply minimum/maximum values to the axis : you can see the bars wor... | NumericAxis < MarketDataDetailsDecorator > axis = new NumericAxis < > ( ) ; axis.setPosition ( Chart.Position.BOTTOM ) ; axis.setMinimum ( 995 ) ; // only this lineaxis.setMaximum ( 1016 ) ; // and this line get added | sencha gxt stacked bar with non-zero axis min behaving incorrectly |
Java | I have the following maps : The values inside these maps look something like : Second map : I want the map after the merge to be : So I want to do the merge , and combine the values of duplicate keys . I believe it should be something like this : | Map < String , Map < String , Long > > mapOne ; Map < String , Map < String , Long > > mapTwo ; { BMW = { SIZE=1 , SPEED=60 } , AUDI = { SIZE=5 , SPEED=21 } , SEAT= { SPEED=15 } } { Suzuki = { WHEELS_SIZE=2 , DOORS=3 } , AUDI = { WHEELS_SIZE=5 , DOORS=5 } , SEAT= { DOORS=4 } } { BMW = { SIZE=1 , SPEED=60 } , AUDI = { S... | How to merge two nested maps with same keys and keep the values |
Java | I 'd like to achieve drawing a diagram just like the image attached but I 'm having trouble drawing the red vertical rectangle on the right along with putting other objects on top . The biggest concern is the to do with numerous different screen sizes of Android devices . I fully understand what I 'm trying to achieve ... | < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < RelativeLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' > < my.package.name.ComplexDiagram android : layout_width... | Draw multi object diagram in fragment |
Java | I 'm constructing an app and for that I have a function to fill it with test data.Short outline : No matter how often I create the test data , the picture looks always like this : So the trend of the random numbers is always negative . Why is that ? | HashMap < String , Long > iIDs = new HashMap < String , Long > ( ) ; HashMap < String , Integer > vals = new HashMap < String , Integer > ( ) ; long iID1 = addIndicator ( `` I1 '' , `` i1 '' , Color.RED ) ; long iID2 = addIndicator ( `` I2 '' , `` i2 '' , Color.BLUE ) ; long iID3 = addIndicator ( `` I3 '' , `` i3 '' , ... | Java random is always delivering a negative trend on the long run ? |
Java | We have an ArrayList of items in several classes which are giving me trouble every time I 'd like to insert a new item into the list . It was a mistake on my part to have designed the classes in the way I did but changing the design now would be more headache than it 's worth ( bureaucratic waterfall model . ) I should... | Foo extends Bar { public Foo ( ) { m_Tags.add ( `` Jane '' ) ; m_Tags.add ( `` Bob '' ) ; m_Tags.add ( `` Jim '' ) ; } public String GetJane ( ) { return m_ParsedValue.get ( m_Tags.get ( 1 ) ) ; } public String GetBob ( ) { return m_ParsedValue.get ( m_Tags.get ( 2 ) ) ; } public String GetJim ( ) { return m_ParsedValu... | Reformatting code with Regular Expressions |
Java | I 'm trying to get the sunday of the same week as a given date.During this I ran into this problem : results in `` Sun Jan 07 11:18:42 CET 2018 '' butgives me the correct Date `` Sun Dec 17 11:18:42 CET 2017 '' Can someone explain why the first exmple is behaving this way ? Is this really intended ? Thanks | Calendar calendar = Calendar.getInstance ( Locale.GERMANY ) ; calendar.set ( 2017 , 11 , 11 ) ; calendar.set ( Calendar.DAY_OF_WEEK , Calendar.SUNDAY ) ; System.out.println ( calendar.getTime ( ) .toString ( ) ) ; Calendar calendar2 = Calendar.getInstance ( Locale.GERMANY ) ; calendar2.set ( 2017 , 11 , 11 ) ; calendar... | Calling getTime changes Calendar value |
Java | This code : has a compile error of The method add ( capture # 1-of ? extends Reader ) in the type List is not applicable for the arguments ( BufferedReader ) Why ? BufferedReader extends reader , so why is n't that a `` match '' ? | List < ? extends Reader > weirdList ; weirdList.add ( new BufferedReader ( null ) ) ; | < ? extends > Java syntax |
Java | Why does below line print false ? i think it should print true . | TimeZone.getTimeZone ( `` UTC+5:30 '' ) .hasSameRules ( TimeZone.getTimeZone ( `` GMT+5:30 '' ) | Why GMT and UTC timezones do n't have same rules |
Java | In Python , if I want to do a fold over the operation xor , I can write : rather than the more cumbersomeIs there anything like this in the new Java 8 functional features ? e.g . to write something like this rather than | reduce ( operator.xor , my_things , 0 ) reduce ( lambda x , y : x^y , my_things , 0 ) myThings.reduce ( 0 , Integer : :xor ) myThings.reduce ( 0 , ( x , y ) - > x ^ y ) | Convenience functions for operators in Java 8 ? |
Java | Do I understand right that end of constructor is not a happens - before relation in Java ? Is it possible , that code below with threads A and B not been synchronized somehow could throw a NullPointerException ? | // Shared reference declarationpublic MyClass val ; // Class declarationpublic class MyClass { public Object object ; public MyClass ( ) { object = new Object ( ) ; } } // Using in thread AMyClass loc = new MyClass ( ) ; val = loc ; // Using in thread Bif ( val ! = null ) { val.object.hashCode ( ) ; // IMO could throw ... | End of constructor as happens - before relation in Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.