lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
There is the question on whether java methods should return Collections or Streams , in which Brian Goetz answers that even for finite sequences , Streams should usually be preferred.But it seems to me that currently many operations on Streams that come from other places can not be safely performed , and defensive code...
public interface CoordinateServer { public Stream < Integer > coordinates ( ) ; // example implementations : // IntStream.range ( 0 , 100 ) .boxed ( ) // finite , ordered , sequential // final AtomicInteger atomic = new AtomicInteger ( ) ; // Stream.generate ( ( ) - > atomic2.incrementAndGet ( ) ) // infinite , unorder...
How to safely consume Java Streams safely without isFinite ( ) and isOrdered ( ) methods ?
Java
I am often in a situation where I have a method where something can go wrong but an exception would not be right to use because it is not exceptional.For example : I am designing a monopoly game . The class Bank has a method buyHouse and a field which counts the number of houses left ( there is 32 houses in monopoly ) ...
1. public void buyHouse ( Player player , PropertyValue propertyValue ) { if ( houseCount < 0 ) throw new someException ; ... . //Not really an exceptional situation } 2. public boolean buyHouse ( Player player , PropertyValue propertyValue ) { if ( houseCount < 0 ) return false ; ... . //This I think is the most norma...
Something can go wrong but it is not an exception
Java
I have a problem about Java Swing and JPanel . I could say that I am an unexperienced Java programmer , but not entirely new to programming.My problem is that I have an class called RandomParticle , which I want to move on the screen ( in a JFrame of course ) . The particle is a default object just to get up the graphi...
public class RandomParticle extends Ellipse2D.Double { private Ellipse2D.Double circle ; public RandomParticle ( double xPos , double yPos , double rad ) { setCircle ( new Ellipse2D.Double ( xPos , yPos , rad , rad ) ) ; } public Ellipse2D.Double getCircle ( ) { return circle ; } public void setCircle ( Ellipse2D.Doubl...
Does all graphical objects have to inherit from JPanel ?
Java
My app contains a few textViews which are supposed to be scrolling horizontally . This works when my layout is first loaded but after clicking on a button to load another layout and then re-click on that button to load back the first layout those textViews start scrolling after a `` big '' delay ( like 20 secs+ ) . I '...
public class CardViewActivity extends AppCompatActivity { private ImageView cardArtImageView ; private TextView leaderSkillDescText ; private TextView superAttackTitleText ; private TextView superAttackDescText ; private TextView passiveSkillTitleText ; private TextView passiveSkillDescText ; private TextView hpText ; ...
Horizontally Scrolling Text Performance Issues
Java
Are there any disadvantages in using Java 6 wildcards in my classpath ? e.g.I can see that where there are two jars that both contain a class with the same path then using a wildcard may lead to results that are hard to track down.But other than that , is there anything else to be aware of ?
C : > set CLASSPATH=.\lib\*
Why would I not use a wildcard in my classpath ?
Java
I created an image gallery app . My requirment : I want to select multiple images , click on button cut and come back to activity which displays all folders ( ImageGallery.java ) . Now , I want to select a folder and paste all the selected images in that folder , on selecting the folder.What is happening ? I am able to...
int int_position ; private GridView gridView ; GridViewAdapter adapter ; ArrayList < Model_images > al_menu = new ArrayList < > ( ) ; private ArrayList < Integer > mSelected = new ArrayList < > ( ) ; boolean boolean_folder ; gridView.setOnItemLongClickListener ( new AdapterView.OnItemLongClickListener ( ) { @ Override ...
not able to move images to another folder in gallery , using asynctask
Java
null is a reference and it is of null type only , i.e . null is not object type.But , when I run the following code snippet I was surprised when I pass null to method method ( null ) ; it calls method ( String s ) not method ( Object o ) .If null is itself a type defined by Java and not object type , then why does it c...
public class Test { public static void main ( String [ ] args ) { method ( null ) ; } public static void method ( Object o ) { System.out.println ( `` Object impl '' ) ; } public static void method ( String s ) { System.out.println ( `` String impl '' ) ; } } public static void method ( Integer s ) { System.out.println...
Null is of reference type , is it a String reference or Object reference ?
Java
I 'm trying to replicate this in Java . To save you the click , it says that a character array [ ' F ' , ' R ' , ' A ' , ' N ' , ' K ' , NULL , ' k ' , ' e ' , ' f ' , ' w ' ] , when converted to a null-terminated string , will stop after ' K ' , since it encounters a null pointer there . However , my Java attempts do ...
public class TerminatingStrings { public static void main ( String [ ] args ) { char [ ] broken = new char [ 3 ] ; broken [ 0 ] = ' a ' ; broken [ 1 ] = '\u0000 ' ; broken [ 2 ] = ' c ' ; String s = new String ( broken ) ; System.out.println ( s ) ; } }
Terminate a char [ ] - > String conversion midway via a null pointer
Java
I can only find stuff about the inverse ; using Clojure to implement Java interfaces . However , I want to write a programme in Clojure and allow one to extend it with Java . For example : Also , how would I specify parameter types so I don ’ t have to use Object everywhere ? The only option I currently see is using do...
# P.clj ( defprotocol P ( f [ a ] ) ( g [ a b ] ) ) # I.javapublic class I implements P { public Object f ( Object a ) { … } public Object g ( Object a , Object b ) { … } }
Is it possible for a class written in Java to implement a protocol written in Clojure ?
Java
Given this inputI need the 3rd column particularly from the file and find which is the last D1 for the group G1 and similarly last D2 for particular G2 . After finding the last value , I need something to be appended in the corresponding line like `` LL '' : I have tried it , but the line is getting appended parallel t...
0000027788|001400000000000000000001224627|G1|||G10000027789|001400000000000000000001224627|D1|||G10000027790|001400000000000000000001224627|D1|||G10000027790|001400000000000000000001224627|D1|||G10000027791|001400000000000000000001224627|G2|||G20000027792|001400000000000000000001224627|D2|||G20000027793|001400000000000...
Append a character for last value in a list in JAVA
Java
I would like to migrate my java program from JDK8 to JDK11.I resolved build errors caused by APIs removed in JDK11.But , I got JNI related problem.To explain about the problem , let 's assume that we have the following java file.As you can see , it has only one int variable , and no method is defined.When I generate JN...
package mypkg ; public class JNITest { static final int X_MINOR_MASK = 1 ; } javac -sourcepath ./mypkg -d $ OUTPUT_DIR ./mypkg/JNITest.java javah -jni -d $ OUTPUT_DIR/jni -cp ./ $ OUTPUT_DIR mypkg.JNITest /* DO NOT EDIT THIS FILE - it is machine generated */ # include < jni.h > /* Header for class mypkg_JNITest */ # if...
Can not create JNI header file with JDK11 javac for variable only class file
Java
Is this bad practice ?
ArrayList < ArrayList < ArrayList < Double > > > list = new ArrayList < ArrayList < ArrayList < Double > > > ( ) ;
Stacking generics
Java
This is a continuation of this question.I am trying to cover chart plot with an AnchorPane , i called it buffer . Here is a code example.Everything works fine until I resize the stage . When I resize the AnchorPane ( buffer ) is not covering a chart plot properly . i.e . it is not fitting the size . How to fix it or do...
package launcher ; import javafx.application.Application ; import javafx.geometry.Bounds ; import javafx.geometry.Side ; import javafx.scene.Node ; import javafx.scene.Scene ; import javafx.scene.chart.LineChart ; import javafx.scene.chart.NumberAxis ; import javafx.scene.layout.AnchorPane ; import javafx.stage.Stage ;...
How to cover chart plot with AnchorPane in JavaFX 8 ?
Java
I am currently working on a Spring Data Neo4j 5.0.3 REST API application that interfaces with a Neo4j 3.3.1 causal cluster consisting of 3 core nodes ( 1 leader and 2 followers ) . For better or for worse , we are also submitting a lot of custom cypher queries to the database using session.query a la SQL prepared state...
private Transaction.Type getTransactionType ( TransactionDefinition definition , Neo4jTransactionObject txObject ) { Transaction.Type type ; if ( definition.isReadOnly ( ) & & txObject.isNewSessionHolder ( ) ) { type = Transaction.Type.READ_ONLY ; } else if ( txObject.transactionData ! = null ) { type = txObject.transa...
How to mark a custom Spring Data Neo4j 5.0.3 cypher query as read-only
Java
I 'm aware that Thread.stop ( ) is deprecated , and for good reason : it is not , in general , safe . But that does n't mean that it is never safe ... as far as I can see , it is safe in the context in which I want to use it ; and , as far as I can see , I have no other option.The context is a third-party plug-in for a...
public void playMoveInternal ( GameState game ) throws IllegalMoveException , InstantiationException , IllegalAccessException , IllegalMoveSpecificationException { ThreadGroup group = new ThreadGroup ( `` playthread group '' ) ; Thread playthread = null ; group.setMaxPriority ( Thread.MIN_PRIORITY ) ; GameMetaData meta...
Using Thread.stop ( ) on carefully locked down , but untrusted , code
Java
and both output same result 0.8999999999999999 , but outputs 0.9.Perhaps by default Java performs calculations in double , then why does downcasting corrects result ? And if 1.1 is converted to 1.100000000000001 in double then why does System.out.println ( ( double ) ( 1.10 ) ) outputs 1.1 only.EDIT : To get why this h...
System.out.println ( 2.00-1.10 ) System.out.println ( ( double ) ( 2.00-1.10 ) ) System.out.println ( ( float ) ( 2.00-1.10 ) )
Why does casting to float produce correct result in java ?
Java
The following line of code is accepted by the compiler ( sun-jdk-8u51 ) without any warnings or errors : Whereas the next two code lines lead to a compilation error ( incompatible types : possible lossy conversion from int to short ) : Why is the compiler not able to perform the same narrowing conversion of the primiti...
short b = true ? 1 : 1 ; boolean bool = true ; short s = bool ? 1 : 1 ;
Why does the narrowing conversion from int to short not work if local variable is used in the ternary operator
Java
I wanted to print 100 as output in the below program.I am getting 0 as answer .
class s extends Thread { int j=0 ; public void run ( ) { try { Thread.sleep ( 5000 ) ; } catch ( Exception e ) { } j=100 ; } public static void main ( String args [ ] ) { s t1=new s ( ) ; t1.start ( ) ; System.out.println ( t1.j ) ; } }
What to do in order to print 100 ?
Java
Consider the following JAVA model for hibernate : and the following model for API serialization ( using spring boot rest controller ) : What i want is to : Have some filtering applied at the Person ( statically defined ) Have some filtering applied at the PersonVO ( get from @ RequestParam ) In C # .NET i could make li...
@ Entity @ Tablepublic class Person { @ Id @ GeneratedValue ( strategy = GenerationType.AUTO ) public Long id ; @ Column public String firstName ; @ Column public String lastName ; @ Column public Boolean active ; } public class PersonVO { public Long id ; public String fullName ; } IQueryable < Person > personsQuery =...
Java using filtering at different models before and after the projection
Java
If I placed 00 or 0 before digits values in array output become different.Output is :011091621
int arr [ ] [ ] =new int [ 3 ] [ 2 ] ; arr [ 0 ] [ 0 ] =00 ; arr [ 0 ] [ 1 ] =01 ; arr [ 1 ] [ 0 ] =10 ; arr [ 1 ] [ 1 ] =0011 ; arr [ 2 ] [ 0 ] =0020 ; arr [ 2 ] [ 1 ] =21 ; for ( int a [ ] : arr ) { for ( int c : a ) { System.out.println ( c ) ; } }
Why 0010 give different result in array in java
Java
I am running in to a lot of boilerplate code when creating language files for the application I am making . I currently have a class with all the language strings in it and then I use reflection to write these strings to the file.What I run into quite often is that I have certain placeholders in my strings that I want ...
@ Retention ( RetentionPolicy.SOURCE ) @ Target ( ElementType.FIELD ) public @ interface Arguments { String [ ] value ( ) ; } @ Arguments ( value = { `` % balance % '' , `` % name % '' } ) public static String USER_INFO = `` Username : % name % - money : % balance % '' ; public static String USER_INFONameReplacement ( ...
Auto generate replace methods
Java
This was actually an interview question . I had to print the following using Java : During the interview , I wrote an embarrassing piece of code , but it worked nonetheless - using an outer loop , two inner loops ( one for the decrementing sequence and one for the incrementing sequence ! ) and a ton of variables . One ...
99 8 99 8 7 8 99 8 7 6 7 8 9. . .. . . int rowCnt = 5 ; for ( int i = 1 ; i < = rowCnt ; i++ ) { int val = 9 ; int delta = -1 ; int rowLen = i * 2 - 1 ; for ( int j = 1 ; j < = rowLen ; j++ ) { System.out.print ( val + `` `` ) ; val += delta ; if ( j > = rowLen / 2 ) delta = 1 ; } System.out.println ( ) ; }
How to print the following sequence , while satisfying these conditions
Java
I was excepting the value of i : 20 , but it is giving me the value 0 , Why I am getting value 0 in java 1.7 version ?
public class InvalidValue { private int i = giveMeJ ( ) ; private int j = 20 ; private int giveMeJ ( ) { return j ; } public static void main ( String [ ] args ) { System.out.println ( `` i : `` + new InvalidValue ( ) .i ) ; } }
How is this code giving me 0 as value of i , instead of 20 ?
Java
I want to create a list ( or collection in general ) by calling a method x times . In Python it would be something like this.I tried to code something similar in JDK 8.It works , but somehow it does n't feel allright . Is there a more proper way of doing it ?
self.generated = [ self.generate ( ) for _ in range ( length ) ] this.generated = IntStream.range ( 0 , length ) .mapToObj ( n - > this.generate ( ) ) .collect ( Collectors.toList ( ) ) ;
How to generate a list of given length in Java 8 ?
Java
Is either option 1 or option 2 below correct ( e.g . one preferred over the other ) or are they equivalent ? Option 1or Option 2
collectionOfThings . stream ( ) . filter ( thing - > thing.condition1 ( ) & & thing.condition2 ( ) ) collectionOfThings .stream ( ) .filter ( thing - > thing.condition1 ( ) ) .filter ( thing - > thing.condition2 ( ) )
Java 8 Streams Filter Intention of Lazy Evaluation
Java
I want to create a List < String > with the numerical values from 72-129 and 132-200 . I thought about using an IntStream and mapping the values to strings and collecting to a list . I used this code : However , if I debug the actual values of strings72to200 , I get this : I believe that the Stream.concat ( ) as well a...
List < String > strings72to200 = Stream .concat ( Stream.of ( IntStream.range ( 72 , 129 ) ) , Stream.of ( IntStream.range ( 132 , 200 ) ) ) .map ( e - > String.valueOf ( e ) ) .collect ( Collectors.toList ( ) ) ; [ java.util.stream.IntPipeline $ Head @ 56d13c31 , java.util.stream.IntPipeline $ Head @ 5f9127c5 ] List <...
How do I concatenate two IntStreams ?
Java
Is it acceptable to use method-chaining , when working with a service that is managed by a dependency injection framework ( say HK2 ) ? I 'm unsure if it is allowed to `` cache '' the instance , even if its only within the scope of the injection.Example Service that creates a pizza : Here the service is injected into a...
@ Servicepublic class PizzaService { private boolean peperoni = false ; private boolean cheese = false ; private boolean bacon = false ; public PizzaService withPeperoni ( ) { peperoni = true ; return this ; } public PizzaService withCheese ( ) { cheese = true ; return this ; } public PizzaService withBacon ( ) { bacon...
Java : method-chaining and dependency injection
Java
I 'm letting the user import plugin-like classes from a remote location using URLClassLoader , so these imported classes do NOT exist in the build path ( however , they all implement an interface IPlugin which is included ) . I assumed one could simply use ObjectOutputStream to save all the loaded plugins to file , and...
ObjectOutputStream oos = new ObjectOutputStream ( *fileoutputstream* ) ; oos.writeObject ( activePlugins ) ; oos.close ( ) ; ObjectInputStream ois = new ObjectInputStream ( *fileinputstream* ) ; activePlugins = ( ArrayList < IPlugin > ) ois.readObject ( ) ;
Equivalent of ObjectOutputStream , saving not only its state but the whole object ?
Java
I have a string like a1wwa1xxa1yya1zz.I would like to get every groups starting with a1 until next a1 excluded . ( In my example , i would be : a1ww , a1xx , a1yyand a1zzIf I use : myGroup capture 1 group every two groups.So in my example , I can only capture a1ww and a1yy.Anyone have a great idea ?
Matcher m = Pattern.compile ( `` ( a1.* ? ) a1 '' ) .matcher ( `` a1wwa1xxa1yya1zz '' ) ; while ( m.find ( ) ) { String myGroup = m.group ( 1 ) ; }
java regex matching each group starting with specific string
Java
What does redis.publish ( ) ; method do in the following module.redis.publish ( `` WordCountTopology '' , exclamatedWord.toString ( ) + `` | '' + Long.toString ( count ) ) ;
public void execute ( Tuple tuple ) { String word = tuple.getString ( 0 ) ; StringBuilder exclamatedWord = new StringBuilder ( ) ; exclamatedWord.append ( word ) .append ( `` ! ! ! `` ) ; _collector.emit ( tuple , new Values ( exclamatedWord.toString ( ) ) ) ; long count = 30 ; redis.publish ( `` WordCountTopology '' ,...
What does the Redis 'redis.publish ( ) ' method do ?
Java
Assume class B inherits from class A . The following is legal Java : In terms of the specification , this means that List < A > assignsTo List < ? super B > . However , I am having trouble finding the part of the spec that says this is legal . In particular , I believe we should have the subtype relationbut section 4.1...
List < A > x ; List < ? super B > y = x ; List < A > < : List < ? super B >
Where does the Java spec say List < T > assigns to List < ? super T > ?
Java
I tried to deploy a web service with 2 ways SSL in java using the class ‘ javax.xml.ws.Endpoint ’ . My SSL setup is very restrictive . I have to set a specific set of options and settings . That ’ s a requirement I can not discuss.In order to setup SSL , I need to provide a Server Context object . After doing some sear...
private static HttpsServer createHttpsServer ( ) throws KeyStoreException , NoSuchAlgorithmException , CertificateException , FileNotFoundException , IOException , UnrecoverableKeyException , KeyManagementException , NoSuchProviderException { final String keyStoreType = `` ... '' ; final String keyStoreFile = `` ... ''...
'javax.xml.ws.Endpoint ' and 2 ways SSL
Java
I try to understand final fields semantic.Lets research code : I have some questions : Does jmm guarantee , that if application terminates then it output [ 1,2 ] ? Does jmm guarantee that instance.data not null after loop termination ? P.S . I do n't know how to make title correct , feel free to edit.AdditionalIs there...
public class App { final int [ ] data ; static App instance ; public App ( ) { this.data = new int [ ] { 1 , 0 } ; this.data [ 1 ] = 2 ; } public static void main ( String [ ] args ) { new Thread ( new Runnable ( ) { public void run ( ) { instance = new App ( ) ; } } ) .start ( ) ; while ( instance == null ) { /*NOP*/ ...
JMM guarantees about final as field and non final reference to the object
Java
I got two examples : Example 1 : Compile all three classes . Remove A.class . Run main . No exception is thrown.Example 2 : Compile the classes . Remove D.class . Run main method . Why ? D is never referenced .
public class A { } public class B { public void m ( A a ) { } } public class C { public static void main ( String [ ] args ) { B b = new B ( ) ; System.out.println ( `` hello ! `` ) ; } } public class D { } public class E { public void omg ( D d ) { } public static void main ( String [ ] args ) { E e = new E ( ) ; } } ...
When a class is loaded in JVM
Java
This has got to be one of the strangest things I have ever observed . Consider the following Java program : I compiled it with javac StrangeError.java , copied it to my server running Windows Server 2012 R2 , and ran it with java StrangeError.Here 's where things start to get weird . The program hangs , waiting for the...
import java.io.IOException ; public class StrangeError { public static void main ( String [ ] args ) { try { Process process = new ProcessBuilder ( `` cmd '' , `` /c '' , `` \ '' C : \\Program Files ( x86 ) \\Microsoft Visual Studio 14.0\\VC\\vcvarsall.bat\ '' amd64 & & set '' ) .start ( ) ; process.waitFor ( ) ; } cat...
cmd.exe is hanging unexpectedly depending on where the file I use is located
Java
This is sort of a strange bug I discovered.But if I have a RecyclerView in a fragment and I open then close my DrawerLayout , my RecyclerView comes in focus . That means closing my DrawerLayout will cause the ScrollView to jump to my RecyclerView . Obviously , I would like the ScrollView 's position to not move when th...
< ScrollView xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' > < LinearLayout android : orientation= '' vertical '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' > < Relati...
RecyclerView Becomes Focused when DrawerLayout is Closed
Java
It 's looks like java.io.File . ( File , String ) is JDK version dependent.Code example was run on Windows 10.Code example : Could you please address is there any known issue or solution for the case
public static void main ( String ... args ) { String path = `` C : \\Workspace\\project '' ; File file = null ; for ( String part : path.split ( `` \\\\ '' ) ) { file = new File ( file , part ) ; } System.out.println ( file ) ; // prints `` C : Workspace\project '' for JDK 9+ // prints `` C : \Workspace\project '' for ...
java.io.File. < init > ( File , String ) JDK version dependent
Java
I am trying to use the Reddit API to save a post . I know I am formatting the request wrong , but I ca n't seem to find any documentation on how to do it correctly . If anyone could either lead me in the right direction , or help me format the request correctly . This is what I have so far.I am very very new to using A...
public void save ( View v ) { OkHttpClient client = new OkHttpClient ( ) ; String authString = MainActivity.CLIENT_ID + `` : '' ; String encodedAuthString = Base64.encodeToString ( authString.getBytes ( ) , Base64.NO_WRAP ) ; System.out.println ( `` myaccesstoken is : `` + myaccesstoken ) ; System.out.println ( `` the ...
How to preform a Reddit post with okhttp
Java
This is Android specific.I derive all of my Activities in Android from a custom class that provides a nice , clean place to put common code used by all layouts in the application , especially some common setContentView ( ) override code that injects layouts into my layouts . So here is what a typical hierarchy looks li...
MyActivity extends MyBaseClass - > MyBaseClass extends Activity - > Activity MyActivity extends MyBaseClass < MapActivity > - > MyBaseClass < T > extends T - > T MyActivity extends MyBaseMapClass - > MyBaseMapClass extends MapActivity - > MapActivity MyActivity extends MyBaseClass - > MyBaseClass extends Activity - > A...
Java 's lack of template inheritance is causing major code duplication headaches in Android . Any solutions ?
Java
Just like in title . Is it okay to make something like this : Or maybe there 's better container that allow adding values at any index ? When saying `` better '' I mean `` having better performance '' , and then `` having less RAM usage '' .A want to do something like in this code above , but this of course does n't wo...
HashMap < Integer , Object > foo = new HashMap < > ( ) ; ArrayList < Object > bar = new ArrayList < > ( ) ; bar.add ( 10_000 , new Object ( ) ) ;
Is it okay to make Integer-keyed Maps in Java ?
Java
I ca n't seem to get my date with variable whitespace to parse . This is the format I have to acceptI can get the top to pass if I change my formatter to the below , but it will break with a 2 digit number
DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` EEE MMM d HH : mm : ss yyyy '' ) ; LocalDateTime dateTime = LocalDateTime.parse ( date , formatter ) ; Sat Jul 2 08:52:13 2016Sat Jul 12 08:52:13 2016 EEE MMM d HH : mm : ss yyyy
Java 8 Time with variable day
Java
How do I take a String [ ] , and make a copy of that String [ ] , but without the first String ? Example : If i have this ... How would I make a new string that 's like the string collection colors , but without red in it ?
String [ ] colors = { `` Red '' , `` Orange '' , `` Yellow '' } ;
Java string [ ] partial copying
Java
I find the generics whose generics params extends itself ( here ) . I do n't understand that well.I suspect that it is wrong at the beginning , but no one put forward . I have some questions about this : How to use the Variant generics , can you give me a example ? What the benefit or effect of this generics style.here...
abstract class Base < T extends Base < T > > { } class Variant < T extends Variant < T > > extends Base < T > { }
what the usefulness about Java generics involving inheritance and generics extends self
Java
I am working with some java code , that has the following statement : I have searched the regex syntax and ca n't find a rule that uses \\p { all } . So what 's the meaning of this expression ?
if ( sql1.matches ( `` ( ? i ) ^CREATE\\s+TABLE\\p { all } * '' ) ) { // do something ; }
what 's the meaning of `` \\p { all } '' in regex ?
Java
I am calculating used memory with the following ColdFusion code.Then in a loop I do the following to calculate the used memory.This tells me that almost 200 MB are used right from the beginning of my page . Is this how much is being used by the CF server or is this just some overhead from my page ?
runtime = CreateObject ( `` java '' , `` java.lang.Runtime '' ) .getRuntime ( ) ; var usedGB = ( runtime.totalMemory ( ) - runtime.freeMemory ( ) ) / 1024.^3 ; // bytes - > KB - > MB - > GB
Does java.lang.Runtime report the memory usage for the whole Coldfusion server or just one page ?
Java
I can not understand the two statements in the main method ( new my_class ( ) ; ) .I have never seen this statement except in object definition . I know that the new keyword allocates memory for an object and assigns a reference address but what is happening in this case is totally ambiguous ; allocate memory for what ...
class my_class { int a = 8 ; my_class ( ) { System.out.println ( a ) ; } } public class NewClass { public static void main ( String [ ] argue ) { new my_class ( ) ; new my_class ( ) ; } }
What does the new keyword do here ?
Java
I 'm working on getting Json objects from a service to a List View in Android ... the date format looks like this `` /Date ( 1354222800000+0300 ) / '' ... how can I change it to a readable format ?
for ( int i = 0 ; i < json.length ( ) ; i++ ) { HashMap < String , String > map = new HashMap < String , String > ( ) ; JSONObject e = json.getJSONObject ( i ) ; map.put ( `` mDate '' , `` '' + e.getString ( `` mDate '' ) ) ; mylist.add ( map ) ; }
Date format retrieved from a service
Java
I have an if-then-else statement and I want to transform it to a ternary operator , but I do not know why I can not do it . The code is the following : And the code with the ternary operator is : The following errors are given by the IDE : Line 1 : The target type of this expression must be a functional interfaceLine 2...
public Movie create ( NewMovieDTO newMovieDTO ) { Movie movieForSaving = NewMovieDTOToMovie.map ( newMovieDTO ) ; List < Actor > actorsForSaving = new ArrayList < Actor > ( ) ; movieForSaving.getActors ( ) .forEach ( ( actor ) - > { Optional < Actor > actorInDatabase = actorService .findByNameAndSurname ( actor.getName...
How to transform in ternary operator ?
Java
Consider this : And this : I am able to compile both - so I definitely did some basic checks here .
public abstract class AbstractHibernateDao < T extends Serializable > { private T clazz ; } public abstract class AbstractHibernateDao < T extends Serializable > { private Class < T > clazz ; }
Difference between these 'generic ' syntaxes in Java
Java
The following code sometimes prints `` valueWrapper.isZero ( ) '' on my Windows-PC and a Mac , both running their JVM in server mode.Ok this happens because the value field is n't final in the ValueWrapper class , so its possible that some thread sees the stale value 0.But what about the following modification , here i...
public class ConcurrencyApp { private final Random rand = new Random ( System.currentTimeMillis ( ) ) ; private ValueWrapper valueWrapper ; private static class ValueWrapper { private int value ; public ValueWrapper ( int value ) { this.value = value ; } public boolean isZero ( ) { return value == 0 ; } } private void ...
semantic of local final variable in the Java Memory Model ?
Java
My parent stage `` stage1 '' is opening child stage `` stage2 '' and i have set child stage 's modality as below . Now when i open stage2 from stage1 , stage1 is appears behind stage2 that is expected , but when i press `` Ctrl+Tab '' key , control switches to 3rd paty applicaton for example `` Outlook '' , then I agai...
stage2.initModality ( Modality.APPLICATION_MODAL ) ;
Parent Stage hidden on switching to the 3rd party window and again switching to Application Stage
Java
I 'm no Java guy , so I ask myself what this means : Is Button a method ? I ask myself , because it takes an input parameter light . But if it was a method , why would it begin with a capital letter and has no return data type ? Here comes the full example : I know , this question is really trivial . However , I have n...
public Button ( Light light ) { this.light = light ; } public class Button { private Light light ; public Button ( Light light ) { this.light = light ; } public void press ( ) { light.turnOn ( ) ; } }
java question : Is it a method ?
Java
I have an Object with a List of another object.It 's mapped like this : On the Image side , that 's the maaping : What happens is:1 . I create my Product object and save it on the database.2 . I update this product object by adding images to it later like this : This is what I get on my console everytime I add a new im...
@ Entity @ Inheritance ( strategy = InheritanceType.JOINED ) @ Table ( name = `` products '' ) public class Product extends DateAudit { private static final long serialVersionUID = 1L ; @ Id @ GeneratedValue ( strategy = GenerationType.IDENTITY ) private Long id ; @ NotBlank @ Size ( min = 3 , max = 30 ) private String...
What the common behaviour when updating an unidirectional @ OneToMany List of objects with Spring Data-JPA ?
Java
As per my knowledge , final variables must/can be initialized only once otherwise compiler is supposed to throw an error.If the final instance variable x is not initialized an error is thrown but I faced no error when the local variable y is kept uninitialized in the following code :
import java.util . * ; public class test { final int x = 5 ; // if final variable x uninitialized , compilation error occurs public static void main ( String [ ] args ) { final int y ; // y is not initialized , **no error is thrown** System.out.println ( `` test program '' ) ; } }
Un-initialized final local variable vs un-initialized final instance variable
Java
I came across simple java program with two for loops . The question was whether these for loops will take same time to execute or first will execute faster than second . Below is programs : After executing this I found that first for loop takes more time than second . But after swapping there location the result was sa...
public static void main ( String [ ] args ) { Long t1 = System.currentTimeMillis ( ) ; for ( int i = 999 ; i > 0 ; i -- ) { System.out.println ( i ) ; } t1 = System.currentTimeMillis ( ) - t1 ; Long t2 = System.currentTimeMillis ( ) ; for ( int j = 0 ; j < 999 ; j++ ) { System.out.println ( j ) ; } t2 = System.currentT...
Comparing logically similar `` for loops ''
Java
For my list view on tablets , I 'm trying to get my selected list item selection to keep its state when selected but unfortunately I 'm seeing some weird behaviour . For some reason whenever I scroll through the list to the point where the selected item is not visible and then scroll back to the point where the selecte...
public class VictoriaListAdapter extends BaseAdapter { private List < Victoria > mData ; private LayoutInflater mInflater ; public VictoriaListAdapter ( List < Victoria > data , Context context ) { mData = data ; mData = new ArrayList ( mData ) ; mInflater = ( LayoutInflater ) context.getSystemService ( Context.LAYOUT_...
Selected list item background colour unexpectedly reused after list scroll on tablets
Java
Why definition of overriding methods f1 ( ) and f3 ( ) in Derived class give no compile error , like definition of overriding f2 ( ) method in Derived class ( which gives compile error `` return type is incompatible with Base.f2 ( ) '' ) ? Subsignature override rule in JLS allows overriding method ( in Derived class ) ...
public class Base { < T > List < ? extends Number > f1 ( ) { return null ; } List < ? extends Number > f2 ( ) { return null ; } < T extends Number > List < T > f3 ( ) { return null ; } } class Derived extends Base { List < String > f1 ( ) { return null ; } // compiles fine ! ! ! List < String > f3 ( ) { return null ; }...
Why subsignature and unchecked rules work this way on return types when overriding a generic method with a non-generic one ?
Java
With Java , is there a way to make a custom class that can have the [ ] accessor used on it like an array ? Normal arrayCustom Class
int [ ] foo = int [ 5 ] ; foo [ 4 ] = 5 ; print ( foo [ 4 ] ) ; //Output : `` 5 '' class Bar { //Custom class that uses index as a ref } Bar foo = new Bar ( 5 ) ; foo.set ( 4 , 5 ) ; print ( foo [ 4 ] ) ; //Output : `` 5 ''
Is there a way to make a custom class that can have [ ] used on it in Java , similar to an array ?
Java
I am using criteria api to check If the user name exists or not . After that I am checking the password . But the user name is not case sensitive . I want to make it case sensitive.Any help will be appreciated .
Criteria criteria2 = session.createCriteria ( UserMaster.class ) ; criteria2.add ( Restrictions.eq ( `` userName '' , userName ) ) ; userDetails = ( UserMaster ) criteria2.uniqueResult ( ) ; if ( userDetails ! = null ) { //logic goes here }
Criteria in hibernate is incasesensitive ?
Java
We are getting a mustache play error in production ( amazon linux EC2 AMI ) but not in development ( MACs ) and we have tried upgrading the jvm , using the jdk instead , and changing from a tomcat deploy model to match our development environments as much as possible but nothing is working . Please any help would be gr...
@ 6al2dd0poInternal Server Error ( 500 ) for request GET /mystuff/peopleExecution exception ( In { module : mustache-0.2 } /app/play/modules/mustache/MustacheTags.java around line 32 ) NullPointerException occured : nullplay.exceptions.JavaExecutionException at play.templates.BaseTemplate.throwException ( BaseTemplate....
Java Play Mustache NPE Error
Java
I have this code : and in main class : If I run this code , I get this output : but if I uncomment the peek function , I get this output : My question is , can anybody tell me , why the keys order differs in the map regionNames when the peek function is in place ?
public enum Continent { ASIA , EUROPE } public class Country { private String name ; private Continent region ; public Country ( String na , Continent reg ) { this.name = na ; this.region = reg ; } public String getName ( ) { return name ; } public Continent getRegion ( ) { return region ; } @ Override public String to...
Why Stream < T > collect method returns different key order ?
Java
I 've searched everywhere trying to figure out what is the val $ editorkit or the $ sign below means , but no luck ... please help ...
private synchronized void updateHtmlEditor ( HTMLEditorKit editorkit , StringReader reader ) { Runnable runnable = new Runnable ( editorkit , reader ) { public void run ( ) { try { this.val $ editorkit.read ( this.val $ reader , LinkParser.this.htmlViewEditor.getDocument ( ) , LinkParser.this.htmlViewEditor.getDocument...
What is the $ sign in Java ? Please have a look in the Java code below
Java
I have always used to check for null likeWhen I compiled my code and looked into .class file after decompiling , I could see that my code got changed toI know in java null==obj and obj==nulldoes n't matter . But I 'm curious to know why compiler changed it ?
if ( null==obj ) if ( obj==null )
obj == null vs null == obj
Java
I was surprised to see that this program even compiles , but the result surprised me even more : The swap function is implemented in the library as : where the List is a mutable Java list , not an immutable Kotlin one . So I thought that other Java functions will work as well . For instance : works , but others , such ...
import java.util.Collections.swapfun main ( args : Array < String > ) { val immutableList = List ( 2 ) { it } // contents are [ 0 , 1 ] swap ( immutableList , 0 , 1 ) println ( immutableList ) // prints [ 1 , 0 ] } public static void swap ( List < ? > list , int i , int j ) { list.set ( i , list.set ( j , list.get ( i ...
Why are some Java functions able to change an immutable Kotlin object ?
Java
2 objects will be created . str1 and str2 refer to same object because of String literal pool concept and str3 points to new object because using new operator and str4 points to the same object points by str1 and str2 because intern ( ) method checks into string pool for string having same value.One object will be elig...
String str1= '' JAVA '' ; String str2= '' JAVA '' ; String str3=new String ( `` JAVA '' ) ; String str4=new String ( `` JAVA '' ) .intern ( ) ; str1=str2=str3=str4=null ;
Total Number of String objects created in the process ?
Java
In the following code it appears to be that functions fn1 & fn2 are applied to inRDD in sequential manner as I see in the Stages section of Spark Web UI . How is is different when streaming job is run this way . Are the below functions run in parallel on input Dstream ?
DstreamRDD1.foreachRDD ( new VoidFunction < JavaRDD < String > > ( ) { public void call ( JavaRDD < String > inRDD ) { inRDD.foreach ( fn1 ) inRDD.foreach ( fn2 ) } } DStreamRDD1.foreachRDD ( fn1 ) DStreamRDD2.foreachRDD ( fn2 )
Concurrent transformations on RDD in foreachDD function of Spark DStream
Java
There is a problem on CodingBat called repeatSeparator . I know how to solve it but my solution and most solutions I find on the internet uses a loop . Is there a way to solve this problem without a loop ? A pseudocode of my need return ( word+rep ) *count ; which wo n't work but is there a way to achieve similiar resu...
Given two strings , word and a separator sep , return a big string made of count occurrences of the word , separated by the separator string.repeatSeparator ( `` Word '' , `` X '' , 3 ) → `` WordXWordXWord '' repeatSeparator ( `` This '' , `` And '' , 2 ) → `` ThisAndThis '' repeatSeparator ( `` This '' , `` And '' , 1...
How to solve the `` repeatSeparator '' problem without a loop in Java ?
Java
I sometimes assume that if oldObject ! = newObject then the object has changed - which seems a fair assumption in most cases but is it truly a bad assumption ? In short , under what situation could the following code print `` Same ! `` ? I realise that this is indeed remotely possible because an object reference is ess...
static WeakReference < Object > oldO = null ; ... Object o = new Object ( ) ; oldO = new WeakReference ( o ) ; // Do some stuff with o - could take hours or even days to complete ... .// Discard o ( or let it go out of scope ) .o = null ; // More stuff - could be hours or days later ... .o = new Object ( ) ; // Later s...
What are the chances of getting exactly the same object reference twice
Java
I want to get the following output : Hello Steve Andrews ! These are my variables : I tried this : I do n't know where to put .toUpper ( ) for steve . The s should be in uppercase . How do I do this ?
a = `` steve '' ; b = `` Andrew '' System.out.print ( `` Hello `` + a + `` `` + b + `` s '' ) ;
simple string concat manipulation in java
Java
I looked at the source code java.util.HashMap and saw the following code : ( Windows , java version `` 1.8.0_111 '' ) On my MacBook it looks like this : ( MacOs X Sierra , java version `` 1.8.0_121 '' ) Why do both variants declare a local variable ks ? Why is it not written like this : or
public Set < K > keySet ( ) { Set < K > ks ; return ( ks = keySet ) == null ? ( keySet = new KeySet ( ) ) : ks ; } public Set < K > keySet ( ) { Set < K > ks = keySet ; if ( ks == null ) { ks = new KeySet ( ) ; keySet = ks ; } return ks ; } public Set < K > keySet ( ) { if ( keySet == null ) { keySet = new KeySet ( ) ;...
Why is the local variable ks declared in the HashMap.keySet ( ) ?
Java
Is there a way to extract a common pattern in a list of strings in Java ? For example , if we have a list of values : Is there a way to deduce that we have 3digits , followed by '- ' , then a letter L and finally a numerical character ? I think it has something to do with common substrings or something like that but I ...
001-L1002-L2003-L3004-L4 ...
Finding a pattern in a set of values in Java
Java
I want to reassign a variable within a for loop traversing over an ArrayList of Objects . But whatever I try it seems that nothing has any effect . Basically my code looks like this : What am I doing wrong ?
for ( int i = 0 ; i < enemies.size ( ) ; i++ ) { AbstractEnemy enemy = enemies.get ( i ) ; if ( enemy.intersects ( bullet ) ) { enemy.getsHit ( bullet.getDamage ( ) ) ; bulletList.remove ( bullet ) ; if ( enemy.isDead ( ) ) { // This does not work enemy = new ExplodingEnemy ( enemy.x , enemy.y ) ; } } }
Reassign variable in a List within for-loop
Java
I have a classAnd using Supplier in java 8 , I can store the constructor reference like But what if my constructor accepts parameter age likeNowdoes n't works , so what should be correct signature for the personSupplier ? Obviously I can do something like.But age must be different for each person , so it does n't solve...
public class Person { private int age ; } Supplier < Person > personSupplier = Person : :new public class Person { private int age ; public Person ( int age ) { this.age = age ; } } Supplier < Person > personSupplier = Person : :new Supplier < Person > personSupplier = ( ) - > new Person ( 10 ) ;
Store constructor that accepts parameter in reference
Java
Why does the condition key < x [ mid ] below cause the compiler to complain that the operator is undefined ? In C++ this would be a compile time warning only if the type T did n't support operator < semantics . How do you do the equivalent in Java ?
package search ; public class BinarySearch < T > { public boolean binary_search_iterative ( T [ ] x , T key ) { int size = x.length ; if ( size == 0 ) { return false ; } int end = size - 1 ; int start = 0 ; while ( start < = end ) { int mid = ( end + start ) /2 ; if ( key < x [ mid ] ) { end = mid - 1 ; } else if ( key...
why does operator < have a compiler error for Java generics ?
Java
Today while searching for a certain piece of code from google , I came across one Q/A blog , where its been said that we can declare a local variable inside a method of a class to be final . However , the author was reluctant enough to explain the need/ benefit of doing so.like I would seek java gurus ' help to educate...
public class A { private void show ( ) { final String s= '' checking '' ; } }
local variable made final in method of a class -- but why ?
Java
One of our application just suffered from some nasty deadlocks . I had quite a hard time recreating the problem because the deadlock ( or stacktrace ) did not show up immediately in my java application logs . To my surprise the marklogic java api retries failing requests ( e.g because of a deadlock ) . This might make ...
public static void main ( String [ ] args ) throws Exception { final Logger root = ( Logger ) LoggerFactory.getLogger ( Logger.ROOT_LOGGER_NAME ) ; final Logger ok = ( Logger ) LoggerFactory.getLogger ( OkHttpServices.class ) ; root.setLevel ( Level.ALL ) ; ok.setLevel ( Level.ALL ) ; final DatabaseClient client = Data...
MarkLogic Java API deadlock detection
Java
Let me show you my code : Class FooMain method ( focus on getFooMultiMapCode ( ) method ) : Main prints correctly this string : I would like to rewrite getFooMultiMapCode method in a more succint way using for example java8 or also libraries such lambdaj , guava , etc but I do n't want to change method signature .
public class Foo { String code ; String value ; public Foo ( String code , String value ) { super ( ) ; this.code = code ; this.value = value ; } // getters/setters } public class FooMain { public static void main ( String [ ] args ) { Foo foo1 = new Foo ( `` 100 '' , '' foo1 '' ) ; Foo foo2 = new Foo ( `` 200 '' , '' ...
From List < Foo > to Map < String , List < Foo > > : looking for a better implementation
Java
Consider : First question : I get an error saying `` b should be static '' . Why ca n't I use the default value ( 3 ) for b in this way ? Second question : In the first constructor , if I use the comment outed part , I do not get an error . Is it an acceptable usage ?
int a = 0 ; int b = 3 ; //Constructor 1 public ClassName ( int a ) { this ( a , b ) ; //Error //new ClassName ( a , b ) //No error } //Constructor 2 public ClassName ( int a , int b ) { this.a = a ; this.b = b ; }
Using a constructor within another in Java
Java
It is necessary to repeat the character , as many times as the number behind it . They are positive integer numbers . I already finish it in the following way : But I wonder is there some better solution with less and cleaner code ?
case # 1input : `` abc3leson11 '' output : `` abccclesonnnnnnnnnnn '' String a = `` abbc2kd3ijkl40ggg2H5uu '' ; String s = a + `` * '' ; String numS = `` '' ; int cnt = 0 ; for ( int i = 0 ; i < s.length ( ) ; i++ ) { char ch = s.charAt ( i ) ; if ( Character.isDigit ( ch ) ) { numS = numS + ch ; cnt++ ; } else { cnt++...
parsing/converting task with characters and numbers within
Java
I have many JSP files with EL expressions of the form $ { foo.bar.baz.phleem1 } , $ { foo.bar.baz.phleem2 } etc . ( the first two or three segments are equal ) . To reduce EL lookups I am in the process of refactoring these pages : Source : After refactoring : I know I can do most of this with searching / replacing , b...
< c : out value= '' $ { foo.bar.baz.phleem1 } '' / > < c : out value= '' $ { foo.bar.baz.phleem2 } '' / > < c : out value= '' $ { foo.bar.baz.phleem3 } '' / > < c : set var= '' baz '' value= '' $ { foo.bar.baz } '' / > < c : out value= '' $ { baz.phleem1 } '' / > < c : out value= '' $ { baz.phleem2 } '' / > < c : out v...
Refactor EL expressions in JSPs
Java
Given some class SomeBaseClass , are these two method declarations equivalent ? and
public < T extends SomeBaseClass > void myMethod ( Class < T > clz ) public void myMethod ( Class < ? extends SomeBaseClass > clz )
Java Generics - are these two method declarations equivalent ?
Java
I run this code : when I run this line : I get this exception :
private void notify ( String date , int space ) throws IOException { String ACCOUNT_SID = `` dddddd '' ; String AUTH_TOKEN = `` ggggggg '' ; String TWILIO_PHONE = `` +my twilio project '' ; String ELAD_PHONE = `` +my real number '' ; TwilioRestClient client ; client = new TwilioRestClient ( ACCOUNT_SID , AUTH_TOKEN ) ;...
java.lang.reflect.InvocationTargetException at com.twilio.sdk.AppEngineClientConnection.flush ( AppEngineClientConnection.java:204 )
Java
UpdateMy small showcase is stored on Bitbucket https : //bitbucket.org/solvapps/animationtestI have an Activity with a view in it . Contentview is set to this view.A MovieTask is an Asynctask and refreshes the view periodically.But invalidate ( ) does n't refresh the view.Can someone help ?
public class MainActivity extends AppCompatActivity { private MyView myView ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; myView = new MyView ( this ) ; setContentView ( myView ) ; startMovie ( ) ; } public void startMovie ( ) { MovieTask movieTask = new Mo...
AsyncTask : invalidating view does not take effect
Java
the output is : why use the `` isInstance '' is false and use `` == '' is true ? because the `` instance of '' ca n't judge implements relationship ?
Parameter [ ] ps = method.getParameters ( ) ; Map < String , Integer > map = new HashMap < String , Integer > ( ) ; for ( int ij = 0 ; ij < ps.length ; ij++ ) { Parameter p = ps [ ij ] ; RequestParam rp = p.getAnnotation ( RequestParam.class ) ; if ( rp ! = null ) { //do something } else { System.out.println ( p.getTyp...
why parameter.getType ( ) .isInstance ( HttpServletRequest.class ) return is false , but use `` == '' is true
Java
I want my program exceptions to be sent to each of the following , preferably simultaneously : the console which starts it ( not necessarily ) a guia txt file.How can I achieve this ? My attempts : System.setErr ( PrintStream err ) will forward all exceptions to a new stream . I am not able to state more thanone stream...
/* ErrorOutput.java */public static t_ErrBuffer t_activeErrBuffer = new t_ErrBuffer ( `` '' ) ; public static void setStdErrToFile ( final File file ) { ps = new PrintStream ( fos ) { @ Override public void write ( byte [ ] buf , int off , int len ) { byte [ ] bn = new byte [ len ] ; for ( int i = off , j = 0 ; i < ( l...
Processing all exceptions in multiple streams
Java
I have 2 class : RecursiveFibonacci and MemorizedRecursiveFibonacci . This is what I have so far . RecursiveFibonacci Classand MemorizedRecursiveFibonacci ClassAs I see , there are some duplicated code in MemorizedRecursiveFibonacci Classand How can I keep it DRY ? remove duplicated code ?
public class SimpleRecursiveFibonacci { public BigInteger fibonacci ( int n ) { if ( n < 2 ) { return BigInteger.ONE ; } return fibonacci ( n - 2 ) .add ( fibonacci ( n - 1 ) ) ; } } public class MemoizedRecursiveFibonacci { private Map < Integer , BigInteger > cache = new HashMap < > ( ) ; public BigInteger fibonacci ...
How can I remove duplicated code between classes ?
Java
I 've recently installed and tried to use Grakn.ai for visualization . Following the instructions on grakn.ai 's website , I ran into the following problem when trying to run : \grakn-dist-0.15.0 > .\bin\grakn.sh startin Windows 10 command prompt , 64 bit , the following lines are displayed before exiting : I have also...
Starting redisCassandra already runningStarting engine.Error : Could not find or load main class ai.grakn.engine.GraknEngineServerError : Could not find or load main class ai.grakn.client.Client.Error : Could not find or load main class ai.grakn.client.Client.Error : Could not find or load main class ai.grakn.client.Cl...
grakn.ai installation error : Could not find or load main class ai.grakn.client.Client
Java
I 've a question regarding encapsulation : Is it recommended to use encapsulation when a class has lots of data-fields ? Using the following class as an example : Would storing most of the data-fields in different classes , such as strength and constitution in a Stats class , be considered as a better design ?
abstract public class Character { private String name ; private String characterClass ; private int level ; private int hitDice ; private int strength ; private int constitution ; private int dexterity ; private int intelligence ; private int wisdom ; private int charisma ; private int hp ; private int currentHp ; priv...
Object-Oriented design - how important is encapsulation when there 're lots of data-fields in one class ?
Java
I am trying a simple index creation on a jar file . However it fails with : On obvious work-around is simply : However it is ugly and error-prone . Is there any other way I can tell jar -i where to search for a different vtk.jar location ? I will need a portable solution which works on Windows/Linux/MacOSX.For informat...
$ jar -i /tmp/vtk-dicom/bin/lib/vtkdicom.jarjava.io.FileNotFoundException : /tmp/vtk-dicom/bin/lib/vtk.jar ( No such file or directory ) at java.util.zip.ZipFile.open ( Native Method ) at java.util.zip.ZipFile. < init > ( ZipFile.java:215 ) at java.util.zip.ZipFile. < init > ( ZipFile.java:145 ) at java.util.jar.JarFil...
Add index to jar file , referencing external jar file
Java
As discussed in Bounding generics with 'super ' keyword the Java type system is broken/incomplete when it comes to lower bounds on method generics . Since Optional is now part of the JDK , I 'm starting to use it more and the problems that Guava encountered with their Optional are starting to become a pain for me . I c...
public class A { } public class B extends A { } public class Cache { private final Map < String , B > cache ; public < T super B > Optional < T > find ( String s ) { return Optional < T > .ofNullable ( cache.get ( s ) ) ; } } A a = cache.find ( `` A '' ) .orElse ( new A ( ) ) B b = cache.find ( `` B '' ) .orElse ( new ...
Safe workaround for broken contravariant bounds in Java ?
Java
I have three classesThis example is taken from Eckel 's Thinking in Java . I ca n't understand why we ca n't call wi = new WithInner ( ) ; instead of .super ( ) ? And while calling wi.super ( ) we are calling Object 's default constructor , are n't we ?
class WithInner { class Inner { } } public class InheritInner extends WithInner.Inner { //constructorInheritInner ( WithInner wi ) { wi.super ( ) ; } }
Use super ( ) with reference in Java
Java
I am facing a weird behavior of java.util.Calendar . The problem is when I add a method call Calendar # getTime ( ) in between only than I get correct result but when I directly get the Dates of the week without calling Calendar # getTime ( ) it refers to the next week instead of current week . Please consider followin...
public class GetDatesOfWeek { public static void main ( String [ ] args ) { SimpleDateFormat sdf = new SimpleDateFormat ( `` dd-MM-yyyy '' ) ; Calendar cal = Calendar.getInstance ( ) ; cal.set ( 1991 , Calendar.DECEMBER , 11 ) ; //System.out.println ( cal.getTime ( ) ) ; //LINE NO : 14 for ( int i = Calendar.SUNDAY ; i...
Weird behavior of Calendar
Java
There is a function that I call once in a day : The function arguments keep on growing . Initially it was like : and now it has 5 more arguments . It is expected to contain more arguments in a week.Now I do not like this.Maintaining functions with so many arguments does n't seem to be a good thing to me . Is there any ...
new SubmitLogs ( ) .mail ( IP , date_time_UTC , date_time_IST , pageVisited , userCountry , userRegion , city , userAgent ) ; new SubmitLogs ( ) .mail ( IP , date_time_UTC , userAgent ) ;
Is there any workaround for functions having large number of arguments ?
Java
I have the following code . When I execute the program and print the value of `` this '' , in both super class constructor as well as in child class constructor , the value of this ( address location ) is displayed as childClassName @ someValue .. My question is , why dont I get the value of Test i.e , Test @ someVal (...
class Test { int i = 0 ; Test ( ) { System.out.println ( this ) ; System.out.println ( this.i ) ; } } public class Demo extends Test { int i = 10 ; Demo ( ) { super ( ) ; System.out.println ( `` calling super '' ) ; System.out.println ( this ) ; System.out.println ( this.i ) ; } public static void main ( String [ ] arg...
confusion in inheritance - value of `` this '' when printed in constructor
Java
I am using google datastore to persist data as objects of a model class- 'zone ' . This model has been updated with more parameters recently . When I deployed the new code , get calls on the existing 'zone ' entities is resulting in an error . Existing zone entities do not have the newly added parameter ( Marked in the...
ERROR : Error in Service { } at com.tryout.cdapp.exceptions.handler.CNDApplicationExceptionHandler . ( CNDApplicationExceptionHandler.java:30 ) on 2014-10-14 03:21:48,002java.lang.NullPointerException at com.google.appengine.datanucleus.scostore.FKListStore.getIndexPropertyName ( FKListStore.java:965 ) at com.google.ap...
App-Engine throws NullPointerException on getByObjectId call of an entity that has been updated
Java
I Have a Spring rest controller which is calling an asynchronous method using Spring 's @ Async methodology and return immediately an http 202 code ( Accepted ) to the client . ( The asynchronous job is heavy and could lead to a timeout ) . So actually , at the end of the asynchronous task , i 'm sending an email to th...
@ Configuration @ EnableAsyncpublic class AsyncConfig implements AsyncConfigurer { @ Override public Executor getAsyncExecutor ( ) { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor ( ) ; executor.setCorePoolSize ( 4 ) ; executor.setMaxPoolSize ( 8 ) ; executor.setQueueCapacity ( 100 ) ; executor.setThreadN...
Recover an Asynch ThreadPoolTaskexecutor after server crashed/shut down
Java
This is the code I am talking about : Why not simply keep the last line as elements = Arrays.copyOf ( elements , 2 * size ) ; ? The only case where it might have been valid would be if the initial size of Stack was 0 . But in this case it is a constant - DEFAULT_INITIAL_CAPACITY ( a non zero value ) . And there is no o...
public class Stack { private Object [ ] elements ; private int size = 0 ; private static final int DEFAULT_INITIAL_CAPACITY = 16 ; public Stack ( ) { elements = new Object [ DEFAULT_INITIAL_CAPACITY ] ; } public void push ( Object e ) { ensureCapacity ( ) ; elements [ size++ ] = e ; } public Object pop ( ) { if ( size ...
Why did Joshua Bloch use 2*size + 1 for resizing the stack in Effective Java ?
Java
I 'm trying to figure out why the setPitch in the PointPlacemarkAttributes does not seem to work correctly.I believe this JOGL code in PointPlacemark.java is where things are going wrong : Here is a simple driver I 've been using to play with it : If I set no pitch , it looks fine : But when I set a pitch of 45 degrees...
Double heading = getActiveAttributes ( ) .getHeading ( ) ; Double pitch = getActiveAttributes ( ) .getPitch ( ) ; // Adjust heading to be relative to globe or screen if ( heading ! = null ) { if ( AVKey.RELATIVE_TO_GLOBE.equals ( this.getActiveAttributes ( ) .getHeadingReference ( ) ) ) heading = dc.getView ( ) .getHea...
Worldwind PointPlacemark Pitch
Java
How can I Use Collectors to collect in a ConcurrentHashMap instread of putting manually into ConcurrentHashMapHelp will be appreciated .
ConcurrentHashMap < String , String > configurationMap = new ConcurrentHashMap < > ( ) ; List < Result > results = result.getResults ( ) ; results.stream ( ) .forEach ( res - > { res.getSeries ( ) .stream ( ) .forEach ( series - > { series.getValues ( ) .stream ( ) .forEach ( vals - > { configurationMap.put ( vals.get ...
How can I use Collectors instead of manually putting into ConcurrentHashMap in java 8
Java
I 'm trying to implement a mechanism that deletes cached files when the objects that hold them die , and decided to use PhantomReferences to get notified on garbage collection of an object . The problem is I keep experiencing weird behavior of the ReferenceQueue . When I change something in my code it suddenly does n't...
public class DeathNotificationObject { private static ReferenceQueue < DeathNotificationObject > refQueue = new ReferenceQueue < DeathNotificationObject > ( ) ; static { Thread deathThread = new Thread ( `` Death notification '' ) { @ Override public void run ( ) { try { while ( true ) { refQueue.remove ( ) ; System.ou...
Why wo n't my objects die ?