lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I 've been thinking about creating a Java framework that would allow programmers to specify invariants ( pre- and post-conditions ) on interfaces . The purpose would be to make code more robust and reduce the number of unit tests that would need to be written for different implementations of the same interface.I envisa...
interface Sort { int [ ] sort ( int [ ] nums ) ; }
Adding Invariants to Interfaces in Java
Java
Constructors of non static member classes take an extra hidden parameter which is a reference to an instance of the immediately enclosing class . There is also a syntactic extension of 'new ' . In the below code , Can you please help me understand the meaning of Kb ( ) in K.Ka.Kb ( ) .new Kc ( ) .new Kd ( ) ? I underst...
class K { static class Ka { static class Kb { class Kc { class Kd { } } } } } class Test { K.Ka.Kb.Kc.Kd k = new K.Ka.Kb ( ) .new Kc ( ) .new Kd ( ) ; }
Syntax for 'new ' in java
Java
Caller : It will call the following 2 methods : The questionAs you can see , the getNextXXXXX ( ) method are pretty the same , just return different object , the logic is same , how to DRY ? the actOnXXXX ( ) seems falls in the DRY category as well , but it all about the same , use same logic against different object ....
switch ( type ) { case `` creature '' : Creature returnActor2 = getNextCreature ( ) ; boolean isEat2 = actOnNearby ( getRightChromosome ( Config.HardCode.creature ) , returnActor2.getLocation ( ) ) ; if ( isEat2 ) { actOnCreature ( returnActor2 ) ; } break ; case `` monster '' : Monster returnActor3 = getNextMonster ( ...
How to DRY these block of code in Java ?
Java
I am creating a new namespace and the most apt name for one of the class seems to be the same name as the namespace . Is this a good practice ? If not , what is the alternative ? For example : Related questions discussing the same issue : Should a class have the same name as the namespace ? How to avoid having the same...
com.person| -- - Person . ( java/cs ) | -- - PersonDetailChecker . ( java/cs ) | -- - PersonNameGenerator . ( java/cs )
Is it a good practice to have a package/namespace and class within with the same name ?
Java
i would like to know if there is a more efficient way to sum all tree lists - summing their values at the same index.The reason why i am asking its because , probably using Streams API , its possible to make it more generic , for any number of lists.thanks for any insight .
List < Double > listA = getListA ( ) ; List < Double > listB = getListB ( ) ; List < Double > listC = getListC ( ) ; int listsSize = listA.size ( ) ; List < ? > collect = IntStream.range ( 0 , listsSize ) .mapToObj ( i - > listA.get ( i ) + listB.get ( i ) + list ( C ) .get ( i ) ) .collect ( toList ( ) ) ;
Java Streams API summing Lists at index
Java
I have a Map which is read by multiple threads but which is ( from time to time ) cleared and rebuilt by another thread.I have surrounded all the access to this map with ... or the writeLock ( ) equivalents , depending on the type of access.My question is ... will the ReadWriteLock ensure the updates to myMap are visib...
readWriteLock.readLock ( ) .lock ( ) try { ... access myMap here ... } finally { readWriteLock.readLock ( ) .unlock ( ) }
ConcurrentHashMap needed with ReadWriteLock ?
Java
I have this vexing source written to demonstrate a layout for a game screen mentioned on another question . It puts buttons ( or labels , choosable at start-up ) into a GridBagLayout . If you choose to not use buttons when prompted ( before the GUI appears ) the entire GUI is nice and compact with no gaps . But if you ...
import java.awt . * ; import java.awt.image.BufferedImage ; import javax.swing . * ; import java.net.URL ; import javax.imageio.ImageIO ; public class SoccerField { private JPanel ui = null ; int [ ] x = { 0 , 35 , 70 , 107 , 142 , 177 , 212 , 247 , 282 , 315 } ; int [ ] y = { 0 , 45 , 85 , 140 , 180 , 225 , 265 , 280 ...
Removing space around buttons in GridBagLayout
Java
Here is my whole activity code , if nessery I can post my xml as well.The code works perfectly without the clickListener , but I want an action to happen when clicking on a certain child of the array but right now it says Can not resolve method setOnChildClickListener ( anonymous android.widget.ExpendableListView.OnChi...
public class Main_Activityextends AppCompatActivity { private RecyclerView recyclerview ; @ Overrideprotected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; setContentView ( R.layout.main ) ; recyclerview = ( RecyclerView ) findViewById ( R.id.recyclerview ) ; recyclerview.setLayo...
Can not resolve method setOnChildClickListener
Java
I 'm not sure why the last statement in the following code is illegal . Integer should be a subtype of ? , so why ca n't I assign it to b ?
List < String > a = new ArrayList < String > ( ) ; a.add ( `` foo '' ) ; // b is a List of anythingList < ? > b = a ; // retrieve the first elementObject c = b.get ( 0 ) ; // This is legal , because we can guarantee// that the return type `` ? '' is a subtype of Object// Add an Integer to b.b.add ( new Integer ( 1 ) ) ...
Understanding wildcards in Java generics
Java
In C and C++ , the compiler is not allowed to reorder data members of structs , so if you 're not careful with how you order them , you end up wasting space . For example : On a platform with 32-bit ints and 64-bit pointers , i will be placed first , followed by 32 bits of padding so that p can be 64-bit–aligned . i2 t...
struct S { int i ; void *p ; int i2 ; } ;
Does member order make a performance difference in Java like in C or C++ ?
Java
I am distributing a library jar for internal clients , and the library includes a certificate which it uses to call a service that is also internal to our network.The trust manager is set up as followsAll of this works fine except in cases where users need other certificates or the default certificate.I tried thisRegis...
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance ( TrustManagerFactory.getDefaultAlgorithm ( ) ) ; KeyStore keystore = KeyStore.getInstance ( `` JKS '' ) ; InputStream keystoreStream = clazz.getClassLoader ( ) .getResourceAsStream ( `` certs.keystore '' ) ; // ( on classpath ) keystore.load ( k...
How can my library with built in ssl certificate also allow use with default certs
Java
Is there a way to parameterize a superclass with a static member class of the subclass ? Contrived ExampleExampleSuperClass.java : ExampleSubClass.java : Compilation fails on ExampleSubClass.java with error : or in Eclipse with : Member can not be resolved to a typein Eclipse the super invocation also has the error : T...
package foo ; public class ExampleSuperClass < T > { protected T field ; public ExampleSuperClass ( T field ) { this.field = field ; } public T getField ( ) { return field ; } } package foo ; public class ExampleSubClass extends ExampleSuperClass < Member > { static class Member { } public ExampleSubClass ( ) { super (...
Parameterizing superclass with static member class from subclass
Java
I need to add some HTML contents into mail body . this is what i have tried so far.If i get the Out put only the last field display in the body of mail which is Employee ID . i want to display all three fields in the Body of the mail.Thank you .
message.setContent ( `` < h1 > You Have a Promotion < /h1 > '' , `` text/html '' ) ; message.setContent ( `` < h3 > Your First Name : < /h3 > '' + FirstNm , `` text/html '' ) ; message.setContent ( `` < h3 > Your Last Name : < /h3 > '' + LastNm , `` text/html '' ) ; message.setContent ( `` < h5 > Your Employee ID : < /...
Java Mail API setContent ( ) not written in the mail body as HTML
Java
Consider we have a scheduled executor service : And for some logic we want to retry a task execution . The following approach seems to be smelling for me , but I ca n't understand why : The one obvious problem I see is that this code is not possible to convert to lambda : ^^ this wo n't compile , as we can not refer th...
ScheduledExecutorService threadPool = Executors.newScheduledThreadPool ( ... ) ; threadPool.submit ( new Runnable ( ) { @ Override public void run ( ) { // ... if ( needToBeScheduled ( ) ) { threadPool.schedule ( this , delay , TimeUnit.MINUTES ) ; } else if ( needToBeResubmitted ( ) ) { threadPool.submit ( this ) ; } ...
Resubmitting/scheduling task from the task itself - is it a good practice ?
Java
Possible Duplicate : Why this is not compiling in Java ? In java , curly braces are optional for one line for loops , but I 've found a case where it is n't allowed . For instance , this code : wo n't compile , but if you add curly braces , like so : it will . Why wo n't this code compile ?
for ( int i = 0 ; i < 10 ; i++ ) Integer a = i ; for ( int i = 0 ; i < 10 ; i++ ) { Integer a = i ; }
Why ca n't you assign an int to an Integer in a loop without curly braces ?
Java
I am attempting to use J/Link to get an image from Mathematica to Java . I am able to print the image in Mathematica like this : I 've tried returning the data from the Mathematica function in various ways : My Java code : When debugging , I get a large byte array in res . The image does get saved , but it 's blank ( i...
Print [ Graphics [ Raster [ img [ [ 1 ] ] ] , AspectRatio- > Automatic , ImageSize- > 530 ] ] ; Return [ Image [ Graphics [ Raster [ img [ [ 1 ] ] ] , AspectRatio- > Automatic , ImageSize- > 530 ] ] ] ; Return [ Graphics [ Raster [ img [ [ 1 ] ] ] , AspectRatio- > Automatic , ImageSize- > 530 ] ] ; Return [ Raster [ no...
Getting a Mathematica image in Java
Java
I tried to compile following code but got errorI donot know why it is ambiguous . means if I am passing an int value it should auto-box and test ( Integer..x ) should get called..on similar line test ( long..x ) should be get called..this is my understanding..can someone explain this why it is ambiguous ?
static void test ( long ... x ) { System.out.println ( `` long ... '' ) ; } static void test ( Integer ... x ) { System.out.println ( `` Integer ... '' ) ; } public static void main ( String [ ] args ) { int no=5 ; test ( no , no ) ; //getting error at this point in eclipse 'The method test ( long [ ] ) is ambiguous ' ...
Ambiguity error while overloading var args method and wrapper methods in java
Java
I compiled a very simple java program with gcj-4.4 and -o option . I loaded it in gdb-7.2 and tried to do some debugging . I noticed at I could print the variables in int type but I could not print an array of int . I received this error message : So my question is how can I print a Java array in gdb ? My OS is openSUS...
( gdb ) p orderFinish [ 0 ] can not find java.lang.Object ( gdb ) p ( int ) orderFinish $ 8 = -136261440 ( gdb ) p orderFinish [ 3 ] can not find java.lang.Object ( gdb ) p in $ 9 = 1 ( gdb ) whatis orderFinish type = int [ ]
How do I print a Java array in gdb ?
Java
Why does n't a.compareTo ( b ) compile ( int can not be dereferenced ) ? I know that compareTo requires objects , but I thought autoboxing would automatically make an int an Integer when necessary . Why does n't autoboxing occur in this case ? And what other cases will it not occur ?
class Test { public static void main ( String [ ] args ) { int a = 1 ; int b = 5 ; Integer c = new Integer ( 1 ) ; Integer d = 5 ; //autoboxing at work System.out.println ( c.compareTo ( d ) ) ; System.out.println ( a.compareTo ( b ) ) ; } }
Java no autoboxing for int for compareTo method ?
Java
Why are generics declared as part of a method ? For instance , when creating a method that uses generics , the generics must be included after the method modifiers : The generics portion of a method is not shown as part of a method declaration . According to java documentation , methods contain the following items : Mo...
public static < T , K > void delete ( AbstractDao < T , K > dao )
Java methods and generics
Java
I want to override equals ( ) method in generic class and to do that I must cast Object to my generic type Pair.I added @ SuppressWarnings ( `` unchecked '' ) to `` mute '' the warnings , but the problem is still there . Methods getType ( ) and getClass ( ) are n't working with generic types too , so using T.getType ( ...
public class Pair < T , U > { private T first ; private U second ; public Pair ( T _first , U _second ) { first = _first ; second = _second ; } public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) ! = obj.getClass ( ) ) return false ; //Problem ahea...
Generic classes in java and equals ( ) method : type safety
Java
I am learning recursion and below is one example that I am tracing through to better understand itBelow is what I have understood so far.- In the first call to strRecur ( `` abc '' ) , the method gets added to execution stack . It prints `` abc '' before pausing due to a recursive call with parameter `` abc* '' .The se...
public static void main ( String [ ] args ) { new TestRecursion ( ) .strRecur ( `` abc '' ) ; } public void strRecur ( String s ) { if ( s.length ( ) < 6 ) { System.out.println ( s ) ; strRecur ( s+ '' * '' ) ; } } abcabc*abc** public class TestRecursion { public static void main ( String [ ] args ) { new TestRecursion...
Recursion - why use return statement
Java
Following a review of the var feature as seen here : I have encountered difficulties with setting up my Eclipse/IntelliJ IDEA IDEs with JDK 10 and am therefore asking help from Stack Overflow users who have a working Java 10 environment.Consider the following : When using var , I expect the JVM to recognize the derivin...
public class A { public void someMethod ( ) { ... } } public class B extends A { @ Override public void someMethod ( ) { ... } } ... ... ... var myA = new A ( ) ; // Works as expectedmyA = new B ( ) ; // Expected to fail in compilation due to var being // syntactic sugar for declaring an A typemyA = ( A ) ( new B ( ) )...
Java 10 'var ' and inheritance
Java
With Eclipse it is possible to find all references of a method , member or class . Is it also possible to find all references to the monitor of a synchronized ? If this is not possible with Eclipse then is it possible with another Java IDE ? My problem is that the monitor object hat many references . A search for all r...
public class LockClass { public synchronized void add ( Object any ) { } } public class AnyOther { private LockClass lock ; public AnyOther ( LockClass lock ) { this.lock = lock ; } public void doSomethings ( ) { synchronized ( lock ) { // ... } }
How can I find all synchronized on the same monitor in Java with Eclipse ?
Java
I am currently working on a project where I want to implement a login mechanism using a username and a password that gets compared against a database.I had something like this in mind : when I noticed that my unit tests were failing . So I took a deeper look at it an noticed that the Object : :equals method is not over...
public boolean verifyUser ( String username , char [ ] password ) { List < char [ ] > dbpass = getPasswords ( username ) ; if ( dbpass.contains ( password ) ) { overwriteWithNonsense ( password ) ; return true ; } overwriteWithNonsense ( password ) ; return false ; } if ( dbpass.stream ( ) .anyMatch ( pw - > Arrays.equ...
Why is the .equals ( ) method not overriden for arrays of primitives in Java ?
Java
I have created custom widget for my android application and i want to create custom styles for it . But while parsing it in the class returns always null . Gone through several links and could n't figure out what the problem is ? Can anyone help ? My atttr.xml is Widget class And the layout file Arrays.xml is
< resources > < declare-styleable name= '' Widget '' > < attr name= '' headers '' format= '' reference '' / > < attr name= '' height '' format= '' integer '' / > < /declare-styleable > < /resources > public Widget ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; TypedArray attr = context.obtainSty...
Android parsing styles for custom widget not working
Java
I 'm trying to parse times in the format of 01:20pm . If I run the above code , I get the following exception : As far as the format I put in the SimpleDateFormat constructor , I do n't see anything wrong . What went wrong here ?
DateFormat formatter = new SimpleDateFormat ( `` hh : mmaa '' ) ; formatter.parse ( `` 01:20pm '' ) java.text.ParseException : Unparseable date : `` 01:20pm '' at java.text.DateFormat.parse ( DateFormat.java:366 )
Parsing simple times in hh : mmaa format
Java
IssueWhen benchmarking a simple QuickSort implementation in Java , I faced unexpected humps in the n vs time graphics I was plotting : I know HotSpot will attempt to compile code to native after it seems certain methods are being heavily used , so I ran the JVM with -XX : +PrintCompilation . After repeated trials , it ...
@ iteration 6 - > sorting.QuickSort : :swap ( 15 bytes ) @ iteration 7 - > sorting.QuickSort : :partition ( 66 bytes ) @ iteration 7 - > sorting.QuickSort : :quickSort ( 29 bytes ) public class QuickSort { public < T extends Comparable < T > > void sort ( int [ ] table ) { quickSort ( table , 0 , table.length - 1 ) ; }...
Jvm native code compilation crazyness - I seem to suffer odd performance penalties for some time even after the code is compiled . Why ?
Java
I am working on a program that integrates Hadoop 's MapReduce framework with Xuggle . For that , I am implementing a IURLProtocolHandlerFactory class that reads and writes from and to in-memory Hadoop data objects.You can see the relevant code here : https : //gist.github.com/4191668The idea is to register each BytesWr...
java.lang.RuntimeException : could not open : byteswritable : d68ce8fa-c56d-4ff5-bade-a4cfb3f666feat com.xuggle.mediatool.MediaReader.open ( MediaReader.java:637 ) XugglerJNI.IContainer_open__SWIG_0
Xuggle ca n't open in-memory input
Java
I am just learning java and have to do something using the java swing library , and the Graphics2D class . Basically I have to draw a construction crane that has multiple parts : a body ( the body of the crane ) , and a number of attached arms ( basically it looks like this : http : //i.imgur.com/4YIkYqW.jpg ) . My que...
public class CraneSimulator { ... public JFrame frame ; public MyPanel panel ; public CraneSimulator ( ) { frame = new JFrame ( `` CraneSimulator '' ) ; ... panel = new MyPanel ( ) ; frame.add ( panel ) ; } public static void main ( String [ ] args ) { CraneSimulator simulator = new CraneSimulator ( ) ; } } class MyPan...
Am I using the Java swing and graphics correctly ?
Java
In Delphi / Pascal there is a mechanism by which local variables in a method can remember a value from one method call to the next . This is done using typed constants . For example : On each call to blah ( ) i will increment . The output will look like:12345 ... ( each number on separate lines , but the editor here pu...
procedure blah ( ) ; const i : integer = 0 ; begin i : = i + 1 ; writeln ( i ) ; end ;
In Java , is there an equivalent of Pascal 's typed constants
Java
Java 7 will have closures ( finally ) , and I wonder how the existing code using single method classes/interfaces ( like Runnable , Comparator , etc ) will be used now.Would that code be replaced ? Will be a conversion of some sort ? An extra method using the closure will be added ? Does anyone knows how is this going ...
... .File [ ] files = directory.listFiles ( new FileFilter ( ) public boolean accept ( File file ) { return file.getName ( ) .endsWith ( `` .java '' ) ; } } ) ; File [ ] files = directory.listFiles ( # ( File file ) { return file.getName ( ) .endsWith ( `` .java '' ) ; } ) ;
How are the interfaces going to be replaced/augmented by the closures in Java ?
Java
Ok , so it 's the first time I am posting out here , so bear with me . I have a name in the format of `` Smith , Bob I '' and I need to switch this string around to read `` Bob I. Smith '' . Any ideas on how to go about doing this ? This is one way that I 've tried , and while it does get the job done , It looks pretty...
public static void main ( String [ ] args ) { String s = `` Smith , Bob I . `` , r = `` '' ; String [ ] names ; for ( int i =0 ; i < s.length ( ) ; i++ ) { if ( s.indexOf ( ' , ' ) ! = -1 ) { if ( s.charAt ( i ) ! = ' , ' ) r += s.charAt ( i ) ; } } names = r.split ( `` `` ) ; for ( int i = 0 ; i < names.length ; i++ )...
Swapping the position of elements within an array in java ?
Java
I am installing this application on the said tablet and I intend to supply this tablet to my client for a day or two , what I want is : After checking the operations , the client should not be able to use the said application after the expiry date . for this I am calling the calander function and comparing the extracte...
public void expire ( ) { Calendar c = Calendar.getInstance ( ) ; int sDate = c.get ( Calendar.YEAR ) ; int sMonth = c.get ( Calendar.MONTH ) +1 ; int sDay = c.get ( Calendar.DAY_OF_MONTH ) ; int sHour = c.get ( Calendar.HOUR_OF_DAY ) ; int sMin = c.get ( Calendar.MINUTE ) ; Toast.makeText ( getApplicationContext ( ) , ...
How to make an application work for only 3 days
Java
Consider adding an equality method to the following class of simple points : // my definition of equalsWhat 's wrong with this method ? At first glance , it seems to work OK : However , trouble starts once you start putting points into a collection : How can it be that coll does not contain p2 , even though p1 was adde...
public class Point { private final int x ; private final int y ; public Point ( int x , int y ) { this.x = x ; this.y = y ; } public int getX ( ) { return x ; } public int getY ( ) { return y ; } // ... } public boolean equals ( Point other ) { return ( this.getX ( ) == other.getX ( ) & & this.getY ( ) == other.getY ( ...
How to Write an Equality Method in Java
Java
The grammar in chapter 18 of JLS v7 seem to differ from the constructs elsewhere in the documentation , but to me there seem to be differences . Specifically in chapter 15 the rules are : which makes foo instanceof Bar a RelationalExpression ( and therefore an EqualityExpresson ) which in turn can be used as LHS in the...
RelationalExpression : ShiftExpression RelationalExpression < ShiftExpression RelationalExpression > ShiftExpression RelationalExpression < = ShiftExpression RelationalExpression > = ShiftExpression RelationalExpression instanceof ReferenceType Expression2 : Expression3 [ Expression2Rest ] Expression2Rest : { InfixOp E...
Is the grammars in Java7 spec really equivalent ?
Java
I was trying unary postfix and prefix operators in javaHere 's the codeThis line of code does not give compile time errorBut this line doeswhereas this line even doesn'tI ca n't understand the pattern of how compiler interprets these queries .
int a=10 ; System.out.println ( a+++ a +++a ) ; System.out.println ( a++ +++a ) ; System.out.println ( a+++ ++a ) ;
prefix and postfix operators java
Java
Why does this program print `` wrong '' ? If I remove the lambda , or if I break apart the multi-catch clause , then it prints `` right '' .
import java.io . * ; import java.net . * ; public class Test { public static void main ( String [ ] arguments ) throws Exception { Runnable runnable = ( ) - > { try { throwException ( ) ; } catch ( SocketException|EOFException exception ) { System.err.println ( `` wrong '' ) ; } catch ( IOException exception ) { System...
Java bug when combining lambdas and multi-catch clauses ?
Java
String class has some methods that i can not understand why they were implemented like this ... replace is one of them . Are there some significant advantages over a simpler and more efficient ( fast ! ) method ? Stats with Java 7:1,000,000 iterationsreplace `` b '' with `` x '' in `` a.b.c '' result : `` a.x.c '' Time...
public String replace ( CharSequence target , CharSequence replacement ) { return Pattern.compile ( target.toString ( ) , Pattern.LITERAL ) .matcher ( this ) .replaceAll ( Matcher.quoteReplacement ( replacement.toString ( ) ) ) ; } public static String replace ( String string , String searchFor , String replaceWith ) {...
JVM String methods implementation
Java
I have some Scala code like this : Calling it from Java like so : Removing the catch block results in an error from the Java compiler saying 'unhandled exception type MyCheckedException ' . Adding the catch block for MyCheckedException results in the compiler complaining about the catch block being unreachable , becaus...
class Callee { @ throws ( classOf [ MyCheckedException ] ) def doStuff ( ) { } } public class Caller { public static void main ( String [ ] args ) { // this wo n't compile ; the Java compiler complains that the catch block is unreachable // however without the catch block , it complains `` unhandled exception MyChecked...
@ throws in Scala does not allow calling Java to catch correct exception type
Java
I 'm in the process of upgrading an environment with new versions of Ubuntu , Consul and Spring Boot . At first glance , everything seems to be working just fine . The app connects to Consul , requests its configuration and boots up . After a few minutes however , something breaks and this message is repeated approxima...
com.ecwid.consul.transport.TransportException : javax.net.ssl.SSLHandshakeException : Remote host terminated the handshake at com.ecwid.consul.transport.AbstractHttpTransport.executeRequest ( AbstractHttpTransport.java:77 ) at com.ecwid.consul.transport.AbstractHttpTransport.makeGetRequest ( AbstractHttpTransport.java:...
Why is the SSL connection between a Spring Boot app and Consul failing after a few minutes ?
Java
This arose from a discussion on formalizing regular expressions syntax . I 've seen this behavior with several regular expression parsers , hence I tagged it language-agnostic.Take the following expression ( adjust it for your favorite language ) : it will return an empty string . Why ? More curiously even , the expres...
replace ( `` input '' , `` ( . * ) * '' , `` $ 1 '' )
Why does ( . * ) * make two matches and select nothing in group $ 1 ?
Java
Assume I have 2 adjacent synchronized blocks with a Thread.holdsLock ( ) call between them : Now , what if at some point the JVM decides to coarsen the lock and merge the above synchronized blocks ? Will Thread.holdsLock ( ) call still return false , or will the code fail with an exception ?
final Object lock = new Object ( ) ; // ... synchronized ( lock ) { // do stuff } if ( Thread.holdsLock ( lock ) ) { throw new IllegalStateException ( ) ; } synchronized ( lock ) { // do more stuff }
Thread.holdsLock ( ) and lock coarsening
Java
Okay , so as far as I know , I understand these things about a final variable.It should be assigned only onceAll the final variables should be initialized before the constructor completesNow using the above , I do not understand how the below does n't work : Here , before the constructor completes the final variables a...
public class FinalTest implements AnotherClass { private final Something something ; private final otherthing ; @ Override public void setStuff ( Something something ) { this.something = something ; this.otherthing = new SomeClass ( something ) ; } public FinalTest ( Something something ) { setStuff ( something ) ; } }
Complaint against final variable
Java
In one of the forum I found below code as a question : And asked what would be the result ? I thought it would be a compile time error , since I have not seen Test : code in java . I was wrong , surprisingly both line is printed after compiling and running above code.Can any one tell me what is the use of this Test : k...
public class Test { public static void main ( String [ ] args ) { System.out.println ( `` Hello '' ) ; Test : System.out.println ( `` World '' ) ; } }
What is the use of text with colon operator ( eg : Test : ) in java
Java
I am new with Regular Expression and might be my question is very basic one.I want to create a regular expression that can search an expression on a particular line number.eg . I have dataAnd I want to search the number 1234 on 7th Line . It may or may not be present on other lines also . I have tried with but am not g...
`` \nerferf erferfre erferf 12545 '' + `` \ndsf erf '' + `` \nsdsfd refrf refref '' + `` \nerferf erferfre erferf 12545 '' + `` \ndsf erf '' + `` \nsdsfd refrf refref '' + `` \nerferf erferfre erferf 12545 '' + `` \ndsf erf '' + `` \nsdsfd refrf refref '' + `` \nerferf erferfre erferf 12545 '' + `` \\n.*\\n.*\\n.*\\n.*...
Search on a particular line using Regular Expression in Java
Java
I 'm a big fan of the singleOrEmpty stream operator . It 's not in the std lib , but I find it very useful . If a stream has only a single value , it returns that value in an Optional . If it has no values or more than one value , it returns Optional.empty ( ) .I asked a question about it earlier and @ ThomasJungblut c...
Optional < Int > value = someList.stream ( ) . { singleOrEmpty } [ ] - > Optional.empty ( ) [ 1 ] - > Optional.of ( 1 ) [ 1 , 1 ] - > Optional.empty ( ) etc . public static < T > Optional < T > singleOrEmpty ( Stream < T > stream ) { return stream.limit ( 2 ) .map ( Optional : :ofNullable ) .reduce ( Optional.empty ( )...
Java 8 Spliterator ( or similar ) that returns a value iff there 's only a single value
Java
Java does n't appear to apply DST offset when the OS uses a POSIX time zone description rather than a time zone name . Is the use of a TZ description unsupported by the JRE or is this behavior a bug ? More details ... I 'm working on a Linux ( Debian ) based system where the TZ environment variable is set to a POSIX fo...
import java.util.Date ; import java.util.TimeZone ; public class CheckTime { public static void main ( String [ ] args ) { TimeZone tz = TimeZone.getDefault ( ) ; Date now = new Date ( ) ; System.out.println ( `` Current time `` + now.toString ( ) ) ; System.out.println ( `` Current time zone `` + tz.getDisplayName ( )...
Does the JRE support posix TZ description rather than TZ name ?
Java
I have a string containing the variable name . I want to get the value of that variable.Is it possible to access the value 10 by using temp_name ?
int temp = 10 ; String temp_name = `` temp '' ;
Accessing the value of a variable by its name as string in Java
Java
I wrote a small program shown below that counts how many times an infinite recursive loop will go before causing a StackOverflow error . The thing is , it errors on a different number each time , normally between 8000 and 9000 . Can anyone explain why this happens ? EDIT : I 'm using the Eclipse IDE , have n't tested i...
public class Testing { static void p ( int i ) { System.out.println ( `` hello '' + i ) ; i++ ; p ( i ) ; } public static void main ( String [ ] args ) { p ( 1 ) ; } }
Why does a recursive function stop on random numbers ?
Java
How can I list all uppercase/lowercase permutations for any letter specified in a character array ? So , say I have an array of characters like so : [ ' h ' , ' e ' , ' l ' , ' l ' , ' o ' ] and I wanted print out possible combinations for say the letter ' l ' so it would print out [ hello , heLlo , heLLo , helLo ] . T...
import java.util.ArrayList ; import java.util.HashSet ; public class Main { public static void main ( String [ ] args ) { //Sample Word String word = `` Tomorrow-Today '' ; //Sample Letters for permutation String rule_char_set = `` tw '' ; ArrayList < Character > test1 = lettersFound ( word , rule_char_set ) ; printPer...
Specific element permutation within an array of characters in JAVA ?
Java
What is the difference betweenandDo either forms occupy any memory ? Are there any similarities / differences ?
type [ ] a = new type [ 0 ] ; type [ ] a = null ;
difference between new type [ 0 ] and null - java
Java
When using extremely short-lived objects that I only need to call one method on , I 'm inclined to chain the method call directly to new . A very common example of this is something like the following : The point here is that I have no need for the Regex object after I 've done the one replacement , and I like to be ab...
string noNewlines = new Regex ( `` \\n+ '' ) .Replace ( `` `` , oldString ) ;
Any reason not to use ` new object ( ) .foo ( ) ` ?
Java
I 'm working on a fork of FernFlower from Jetbrains and I 've been adding minor improvements to it.One thing that really annoys me about FernFlower is that it bases the type of the local variable based on its value in bpush/spush etc . While Jode and Procyon somehow find a way to find the original value of a local vari...
public static void main ( String [ ] args ) throws Exception { int hello = 100 ; char a2 = 100 ; short y1o = 100 ; int hei = 100 ; System.out.println ( a2+ '' `` +y1o+ '' , `` +hei+ '' , `` +hello ) ; } public static void main ( String [ ] args ) throws Exception { byte hello = 100 ; char a2 = 100 ; byte y1o = 100 ; by...
JVM Bytecode , how can I find the type of local variables ?
Java
I 'm running Java in a GraalVM to use it to execute python.The question is how the python code should receive `` arguments '' . The graal documentation states that if this were JS , I would do something like this : Indeed , that works . The python equivalent might be : This fails , as there 's no such module . I ca n't...
Context context = Context.create ( ) ; Value v = context.getPolyglotBindings ( ) ; v.putMember ( `` arguments '' , arguments ) ; final Value result = context.eval ( `` python '' , contentsOfMyScript ) ; System.out.println ( result ) ; return jsResult ; const args = Interop.import ( 'arguments ' ) ; import Interopargs =...
Getting outer environment arguments from java using graal python
Java
I am using Spring Tool Suite 3.6.3 and M2E eclipse plugin 1.4.1 , when I opened the POM file from one of the project , I observed not all the dependencies are getting added , I have added depnedecy configuration for jaxws-rt with version 2.2.8 which has many dependencies as followsIn STS when I open the POM , and navig...
< dependency > < groupId > javax.xml.bind < /groupId > < artifactId > jaxb-api < /artifactId > < /dependency > < dependency > < groupId > javax.xml.ws < /groupId > < artifactId > jaxws-api < /artifactId > < /dependency > < dependency > < groupId > javax.xml.soap < /groupId > < artifactId > javax.xml.soap-api < /artifac...
M2E Failed to load all dependencies
Java
Looking at the ArrayUtils class from apache commons , the doc says : ArrayUtils instances should NOT be constructed in standard programming.I was looking at the source code of this class , and I saw they made the constructor public : Since all the methods/fields of the class are static , I understand that it makes no s...
ArrayUtils ( ) public ArrayUtils ( ) { super ( ) ; }
Why not a private no args constructor ?
Java
I must have spent over an hour trying to figure out the reason for some unexpected behavior . I ended up realizing that a field was n't being set as I 'd expect . Before shrugging and moving on , I 'd like to understand why this works like this.In running the example below , I 'd expect the output to be true , but it '...
public class ClassOne { public ClassOne ( ) { fireMethod ( ) ; } protected void fireMethod ( ) { } } public class ClassTwo extends ClassOne { boolean bool = true ; public ClassTwo ( ) { super ( ) ; } @ Override protected void fireMethod ( ) { System.out.println ( `` bool= '' +bool ) ; } public static void main ( String...
Why are n't fields initialized to non-default values when a method is run from super ( ) ?
Java
I am trying to calculate a^ ( 1/n ) , where ^ denotes exponentiation.However , the following : returns 1.0 instead of returning 2.0.Why is that ?
Math.pow ( 8 , 1/3 )
How to calculate a^ ( 1/n ) ?
Java
I have three interfaces : and 4 classes that implement some or all of these interfaces : I would like to have a generic method that does the following : Realizing that this could create an infinite loop ( unless the bottom class -- Grandchild -- implemented Sublistable and set hasSublist ( ) { return false ; } , or som...
public interface Combinable < V > { V add ( V other ) ; } public interface Sublistable < V > { boolean hasSublist ( ) ; List < V > getSublist ( ) ; void setSublist ( List < V > sublist ) ; } public interface HasUniqueIdentifier { String getUniqueIdentifier ( ) ; } public class Grandparent implements HasUniqueIdentifier...
Using Java Generics to recurse over an object with a list of objects ( each with another list of objects )
Java
So , this is how mp3 is encoded from mic to file in android : Everything above is working correctly and providing a new mp3 file which is played ok from audio playersNow i just read that mp3 file from InputStream and get the file bytes array : So how to add some new audio data to existing mp3 file , or maybe there is a...
private void startBufferedWrite ( final File file ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { output = null ; try { output = new DataOutputStream ( new BufferedOutputStream ( new FileOutputStream ( file ) ) ) ; while ( mIsRecording ) { int readSize = mRecorder.read ( buffer , 0 , buffer.length ...
Add some sound data to existing mp3 file Android , lame encoder
Java
I am trying to make a 2D game with Java and Swing , and the window refreshes too slow . But if I move the mouse or press keys , the window refreshes as fast as it should ! Here is a GIF showing how the window refreshes quickly only when I move the mouse.Why does the window refresh slowly like that ? Why does the mouse ...
import java.awt.Graphics ; import java.awt.Dimension ; import java.awt.Color ; import javax.swing.JFrame ; import javax.swing.JPanel ; import javax.swing.SwingUtilities ; import javax.swing.Timer ; class Game { public static final int screenWidth = 160 ; public static final int screenHeight = 140 ; /** * Create and sho...
Why does my custom Swing component repaint faster when I move the mouse ? ( Java )
Java
I have a two overloaded methods : foo and barNow when I use them like : I am getting Here is the question : why do we have 2 different outputs ? Integer [ ] can be implicitly cast to both Object , and Object [ ] .
//Object [ ] ... vs Integer [ ] ... public static String foo ( Object [ ] ... args ) { return `` Object [ ] args '' ; } public static String foo ( Integer [ ] ... args ) { return `` Integer [ ] args '' ; } //Object ... vs Integer [ ] ... public static String bar ( Object ... args ) { return `` Object args '' ; } public...
Overloading varargs arrays , choosing method
Java
I have a POJO defined as follows : When I am doing , with str as : In this , there is no otherData field . Even then , GSON.fromJson is not failing . Why is it so ? Then , is there any significance of marking the field as @ NonNull ?
@ Valuepublic class Abc { @ NonNull private final String id ; @ NonNull private final Integer id2 ; @ NonNull private final List < String > data ; @ NonNull private final String otherData ; } GSON.fromJson ( str , Abc.class ) ; { `` id '' : `` dsada '' , '' id2 '' : 12 , '' data '' : [ `` dsadsa '' ] }
Gson.fromJson not failing if some fields are not given even though marked as @ NonNull
Java
While trying to devise an algorithm , I stumbled upon this question . It 's not homework.Let P_i = an array of the first i primes . Now I need the smallest i such that ( if such i exists ) .An approximation for the i'th prime is i*log ( i ) . So I tried this in Java : However the above does n't finish because it conver...
Sum < n=0..i > 1 / ( P_i [ n ] *P_i [ n ] ) > = 1. public static viod main ( String args [ ] ) { double sum = 0.0 ; long i = 2 ; while ( sum < 1.0 ) { sum += 1.0 / ( i*Math.log ( i ) *i*Math.log ( i ) ) ; i++ ; } System.out.println ( i+ '' : `` +sum ) ; } sum += 1.0 / ( i*i )
sum ( 1/prime [ i ] ^2 ) > = 1 ?
Java
I have an instance where I used to pass my View onto a new method to manipulate a couple of things . here I will provide an example . So Basically I am using a RecyclerView and I am inflating the view when the recylerview creates the viewSo now I have the inflated View object now I just pass it to my method to manipula...
ViewDataBinding viewDataBinding = DataBindingUtil.inflate ( layoutInflater , getLayoutResource ( ) , viewGroup , false ) ; ViewStub viewStub = ( ViewStub ) viewDataBinding.getRoot ( ) .findViewById ( R.id.stub ) ; viewStub.setLayoutResource ( getLayoutResource ( ) ) ;
ViewBinding manipulate view after inflating
Java
I am wondering , is any nice way ( if it is possible at all ) to implement an alpha-equivalence comparison in Java-8 ? Obviously these two lambda-s are alpha-equivalent . Let us suppose that for some circumstances we want to detect this fact . How it can be achieved ?
Predicate < Integer > l1 = x - > x == 1 ; Predicate < Integer > l2 = y - > y == 1 ;
Java 8 lambda and alpha equivalence
Java
I 'm trying to create a proper regex for my problem and apparently ran into weird issue.Let me describe what I 'm trying to do..My goal is to remove commas from both ends of the string . E , g , string , , , , , , , , Hello , my lovely , world , , , , should become just Hello , my lovely , world.I have prepared followi...
output = input.replaceAll ( `` ^ ( , ? \\W ? ) + '' , `` '' ) ; //replace commas at the beginningoutput = output.replaceAll ( `` ( , ? \\W ? ) + $ '' , `` '' ) ; //replace commas at the end
Java Regex lookahead takes too much time
Java
I 've got plenty of these lying around , and I 'm wondering if I 'm going to face any trouble - or performance problems.I have method A : Or method B : On a functional level , they both do the same thing . Right now , I 'm using method A . Is that a bad way of doing things ? Which is going to perform better ?
MyClass monkey ; ... if ( monkey ! = null ) { ... } boolean hasMonkey ; //This is set to TRUE when monkey is not nullMyClass monkey ; ... if ( hasMonkey ) { ... }
Which is the 'correct ' way to do this ( if statement )
Java
What is the difference betweenandjust I got time limit exception in first case and got accepted in second case when doing binary search
int x = ( right + left ) / 2 ; int x = left + ( right - left ) / 2 ;
mid value of two integers
Java
Suppose I have this code ( it really does not matter I think , but just in case here it is ) : And here is how I am invoking it ( using java-9 ) : What I am trying to find out is what methods were replaced by intrinsic code . The first one that is hit ( inside Unsafe ) : And this method is indeed present in the output ...
public class AtomicJDK9 { static AtomicInteger ai = new AtomicInteger ( 0 ) ; public static void main ( String [ ] args ) { int sum = 0 ; for ( int i = 0 ; i < 30_000 ; ++i ) { sum += atomicIncrement ( ) ; } System.out.println ( sum ) ; } public static int atomicIncrement ( ) { ai.getAndAdd ( 12 ) ; return ai.get ( ) ;...
java9 intrinsic method unclear
Java
In the source code of @ Retention annotation in java , @ Retention is used in its definition itself , hows that possible.Even the RetentionPolicy is set at RUNTIME , so how could it get executed before its not ready to run .
package java.lang.annotation ; @ Documented @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( ElementType.ANNOTATION_TYPE ) public @ interface Retention { /** * Returns the retention policy . * @ return the retention policy */ RetentionPolicy value ( ) ; }
Recursive usage of @ Retention annotation , how is it possible ?
Java
In Java a bitwise operation causes type casting to integer and also causes sign extension . For instance the following is expected : In Java chars are encoded in UTF-16 and each unit is represented with 2 bytes . I was expecting -1 instead of 32767 . Why is the sign not extended during the type cast before the bitwise ...
byte b = -1 ; System.out.println ( b > > 1 ) ; //-1 char c = 0xFFFF ; //I assume now the sign bit is 1.System.out.println ( c > > 1 ) ; //32767 ? ? ? ? WHY
In Java , why does type casting of a character to an integer NOT extend the sign bit
Java
I understand that constructor chaining goes from the smallest constructor to the biggest . For example Also as I understand that the call to this ( ) and super ( ) must be in the first line . But is it possible ( and if yes , is it efficient ) to bypass that limit and chain constructors different ? For example I have t...
public MyChaining ( ) { System.out.println ( `` In default constructor ... '' ) ; } public MyChaining ( int i ) { this ( ) ; System.out.println ( `` In single parameter constructor ... '' ) ; } public MyChaining ( int i , int j ) { this ( j ) ; System.out.println ( `` In double parameter constructor ... '' ) ; } public...
Constructor Chaining without this ( )
Java
I need to create a custom menu in my blackberry application so that I can manage its appearance . I managed to create my custom menu by creating a class which extends a PopupScreen and having my MenuItem as a customized LabelField with abstract invokeAction ( ) method . I made the invokeAction ( ) method as abstract to...
public CustomMenu ( MainScreen screen ) { super ( vfm ) ; Menu menu = screen.getMenu ( 0 ) ; for ( int i = 0 ; i < menu.getSize ( ) ; i++ ) { final MenuItem finalMenu = menu.getItem ( i ) ; vfm.add ( new CustomMenuItem ( finalMenu.toString ( ) , Field.FOCUSABLE ) { protected boolean invokeAction ( int action ) { finalM...
invoking native MenuItem ( Switch Application , Close , etc . ) in my CustomMenu in blackberry
Java
Below are two ways how to create ArrayList : What is the difference ? Which method should be used ?
List < String/*or other object*/ > arrList = new ArrayList ( ) ; //Imports List , ArrayListArrayList < String/*or other object*/ > arrList = new ArrayList ( ) ; //Imports just ArrayList
How to create ArrayList properly ?
Java
I was playing with OOM errors today and I found something I ca n't explain myself.I try to allocate an array bigger than the heap , expecting a `` Requested array size exceeds VM limit '' error , but I get a `` Java heap space '' error instead.According to the JDK 11 documentation `` 3 Troubleshoot Memory Leaks > Under...
public class MemOverflow { public static void main ( final String [ ] args ) { System.out.println ( `` Heap max size : `` + ( Runtime.getRuntime ( ) .maxMemory ( ) / 1024 / 1024 ) + `` MB '' ) ; long [ ] array = new long [ 100_000_000 ] ; // ~800MB System.out.println ( array.length ) ; } } $ javac MemOverflow.java & & ...
Unexpected OutOfMemoryError when allocating an array larger than the heap
Java
In new , third edition of Effective Java Joshua Bloch mentions piece of code from Java Puzzlers ( it 's about closing resources in try-finally ) : For starters , I got it wrong on page 88 of Java Puzzlers , and no one noticed for years . In fact , two-thirds of the uses of the close method in the Java libraries were wr...
} finally { if ( in ! = null ) { try { in.close ( ) ; } catch ( IOException ex ) { // There is nothing we can do if close fails } } if ( out ! = null ) { try { out.close ( ) ; } catch ( IOException ex ) { // Again , there is nothing we can do if close fails } } } try { OutputStream out = new FileOutputStream ( dst ) ; ...
What is wrong with this Java Puzzlers piece of code ?
Java
I 'm using GWT and the GWT GoogleMaps API ( v3.8.0 ) . I have everything up and running perfectly.However , I 'd like to disable a few of the default features that come with GoogleMaps , such as street names , the ability to click on restaurants , etc . Basically I 'd like a very barebones map layer that I add my own c...
package com.test.client ; import com.google.gwt.ajaxloader.client.AjaxLoader ; import com.google.gwt.ajaxloader.client.AjaxLoader.AjaxLoaderOptions ; import com.google.gwt.core.client.EntryPoint ; import com.google.gwt.core.client.JsArray ; import com.google.gwt.dom.client.Document ; import com.google.maps.gwt.client.G...
GWT GoogleMaps Hide Default Layers Using Styles
Java
I am trying to get to grips with JCStress . To ensure I understand it , I decided to write some simple tests for something that I know must be correct : java.util.concurrent.locks.ReentrantReadWriteLock.I wrote some very simple tests to check lock mode compatibility . Unfortunately two of the stress tests are failing :...
true , true 32,768 FORBIDDEN No default case provided , assume FORBIDDEN true , true 32,767 FORBIDDEN No default case provided , assume FORBIDDEN import org.openjdk.jcstress.annotations . * ; import org.openjdk.jcstress.infra.results.ZZ_Result ; import java.util.concurrent.locks.ReentrantReadWriteLock ; /* * | -- -- --...
Confused by jcstress test on ReentrantReadWriteLock # tryLock failing
Java
I have tried below code : I have tried many different literals.Could anyone please explain why intern ( ) does n't work as expected with literal `` java '' ? Why do the above reference comparisons evaluate to true , except when the literal is `` java '' ?
public class TestIntern { public static void main ( String [ ] args ) { char [ ] c1= { ' a ' , ' b ' , ' h ' , ' i ' } ; String s1 = new String ( c1 ) ; s1.intern ( ) ; String s2= '' abhi '' ; System.out.println ( s1==s2 ) ; //true char [ ] c2= { ' j ' , ' a ' , ' v ' , ' a ' } ; String sj1 = new String ( c2 ) ; sj1.in...
Why intern ( ) does not work with literal 'java ' ?
Java
When I write thisI would expect that at compile time the array and the strings are created , like it would happen for similar code in C. Is it correct ? Are array and their content generally created at compile time or at run-time ?
String [ ] fruits = { `` Apple '' , `` Pear '' } ;
When are array initialized in Java ?
Java
I have read that in order to access the call object representing a primitive type , I can do this : But how do primitive types have classes to represent them ? They are primitive , which should mean they have no class . Why does the example above work , and what class contains int ( Integer class maybe ) ?
Class intClass = int.class ;
Accessing call object representing a primitive type
Java
I want to have the table of vowels with diacritics , but do n't want to search symbol tables manually . Is it possible to generate this table by crossing the list of vowels and the list of diacritics in some of the following languages : Java , PHP , Wolfram Mathematica , .NET languages and so on ? I need to have charac...
public static void main ( String [ ] args ) { String vowels = `` aeiou '' ; char [ ] diacritics = { '\u0304 ' , '\u0301 ' , '\u0300 ' , '\u030C ' } ; StringBuilder sb = new StringBuilder ( ) ; for ( int v=0 ; v < vowels.length ( ) ; ++v ) { for ( int d=0 ; d < diacritics.length ; ++d ) { sb.append ( vowels.charAt ( v )...
How to generate diacritized vowel table automatically ?
Java
I 'm wondering if I can use or in switch-case in Java ? Example
switch ( value ) { case 0 : do ( ) ; break ; case 2 OR 3 do2 ( ) ; break ; }
Can I use OR statements in Java switches ?
Java
In the class comments at the top of PersistentValve there is a usage constraint : Why is this constraint here ? Perusing the code I see three reasons : Concurrent requests for the same session on different Tomcat instances may be subject to `` last write wins '' and thus potential loss of session data.Concurrent reques...
/** ... * < b > USAGE CONSTRAINT < /b > : To work correctly it assumes only one request exists * per session at any one time ... . */
Why should Tomcat 's PersistentValve not be used where there may be concurrent requests per session ?
Java
I have Dataset < Tuple2 < String , DeviceData > > and want to transform it to Iterator < DeviceData > . Below is my code where I am using collectAsList ( ) method and then getting Iterator < DeviceData > . I can not use collectAsList ( ) as my data is huge and it will hamper performance . I looked into Dataset API but ...
Dataset < Tuple2 < String , DeviceData > > ds = ... ; List < Tuple2 < String , DeviceData > > listTuple = ds.collectAsList ( ) ; ArrayList < DeviceData > myDataList = new ArrayList < DeviceData > ( ) ; for ( Tuple2 < String , DeviceData > tuple : listTuple ) { myDataList.add ( tuple._2 ( ) ) ; } Iterator < DeviceData >...
How to transform Dataset < Tuple2 < String , DeviceData > > to Iterator < DeviceData >
Java
I havea TableView , and I access properties of the list 's objects as follows . This works just fine.However , I 'd like to access a nested property of the object , for example : where my list object has a getHouse ( ) , and House has a getBathroom ( ) . Unfortunately , this does n't work . I 've tried a few spelling v...
< TableColumn fx : id= '' dateColumn '' editable= '' false '' prefWidth= '' 135.0 '' text= '' Date '' > < cellValueFactory > < PropertyValueFactory property= '' date '' / > < /cellValueFactory > < /TableColumn > < TableColumn prefWidth= '' 100.0 '' text= '' Course '' > < cellValueFactory > < PropertyValueFactory proper...
Accessing nested properties in JavaFx TableView / TableColumn
Java
Here 's a minimal example of the code I 'm working with : The compiler output is : I have found that this can be worked around by replacing t - > t with Function.identity ( ) or ( SomeEnum t ) - > t , but I 'm not understanding why this is the case . What limitation in javac is causing this behavior ? I originally foun...
public class Temp { enum SomeEnum { } private static final Map < SomeEnum , String > TEST = new EnumMap < > ( Arrays.stream ( SomeEnum.values ( ) ) .collect ( Collectors.toMap ( t - > t , a - > `` '' ) ) ) ; } Temp.java:27 : error : can not infer type arguments for EnumMap < > private static final Map < SomeEnum , Stri...
Why does this code fail to compile , citing type inference as the cause ?
Java
I 'm running a Java EE application which uses Hibernate 5.2.10.Final with an Apache Derby storage backend on Payara 4.1.1.172 . I 'm seeing error messages likewhich indicates that either Hibernate or Derby or both are not using english error messages in all parts of the message.I tried toadd ato a class , but I do n't ...
Caused by : java.sql.SQLDataException : A truncation error was encountered trying to shrink VARCHAR ( ) FOR BIT DATA ' ( Binärer Datenwert wird nicht angezeigt ) ' to length 255. static { System.setProperty ( `` user.language '' , `` en '' ) ; System.setProperty ( `` user.region '' , `` en_US '' ) ; }
How to get Apache Derby and Hibernate to print english exception messages in a Java EE application ?
Java
While analyzing the results of a recent question here , I encountered a quite peculiar phenomenon : apparently an extra layer of HotSpot 's JIT-optimization actually slows down execution on my machine.Here is the code I have used for the measurement : The code is quite subtle so let me point out the important bits : th...
@ OutputTimeUnit ( TimeUnit.NANOSECONDS ) @ BenchmarkMode ( Mode.AverageTime ) @ OperationsPerInvocation ( Measure.ARRAY_SIZE ) @ Warmup ( iterations = 2 , time = 1 ) @ Measurement ( iterations = 5 , time = 1 ) @ State ( Scope.Thread ) @ Threads ( 1 ) @ Fork ( 2 ) public class Measure { public static final int ARRAY_SI...
Strange JIT pessimization of a loop idiom
Java
The following snippet ( abstracted from real-world code ) compiles and runs in Eclipse.package1/Outer.java : package2/Bar.java : However , it fails with this error when compiling using javac : Now , if I switch the order of the import statements , like so : ... then it compiles in both Eclipse and javac . Clearly the o...
package package1 ; import package1.Outer.Mid.Inner ; import package2.Bar ; public class Outer { final Mid mid = new Mid ( ) ; public Outer ( ) { mid.setInner ( new Inner ( ) { @ Override public void foo ( ) { System.out.println ( `` In Outer.foo ( ) '' ) ; } } ) ; } public static class Mid implements Bar { private Inne...
Strange compiler difference between Eclipse and javac
Java
I am getting null pointer exception in fragment using Gridview.My code isCan anyone guide why it is happing ? I do n't use fragments commonly .
public class HomeFragment extends Fragment { GridView grid ; String [ ] web = { `` Bata '' , `` Service '' , `` puma '' , `` Hush '' } ; int [ ] imageId = { R.drawable.shoesmall , R.drawable.shoe1 , R.drawable.shoe3 , R.drawable.shoe4 } ; public HomeFragment ( ) { } @ Override public View onCreateView ( LayoutInflater ...
I am getting Null Pointer Exception in GridView Android
Java
I have just encountered an error in my opensrc library code that allocates a large buffer for making modifications to a large flac file , the error only occurs on an old PC machine with 3Gb of memory using Java 1.8.0_74 25.74-b02 32bit Originally I used to just allocate a bufferBut for some time I have it as My ( mis )...
ByteBuffer audioData = ByteBuffer.allocateDirect ( ( int ) ( fc.size ( ) - fc.position ( ) ) ) ; MappedByteBuffer mappedFile = fc.map ( MapMode.READ_WRITE , 0 , totalTargetSize ) ;
How do I avoid mapFailed ( ) error when writing to large file on system with limited memory
Java
I have implemented a simple profiler with JVMTI to display the invocation on wait ( ) and notifyAll ( ) . As a test case I am using the . producer consumer example of Oracle . I have the following three events : notifyAll ( ) is invokedwait ( ) is invokedwait ( ) is leftThe wait ( ) invocation and when its left it prof...
// Profiler : Thread-1 invoked notifyAll ( ) Thread-0 invoked notifyAll ( ) Thread-0 invoked notifyAll ( ) Thread-0 invoked notifyAll ( ) Thread-0 invoked notifyAll ( ) Thread-0 invoked notifyAll ( ) Thread-1 invoked notifyAll ( ) Thread-1 invoked notifyAll ( ) Thread-1 invoked notifyAll ( ) Thread-1 invoked notifyAll ...
notifyAll ( ) number of invocations difference while profiling
Java
I want to draw a grid and draw stuff in the cells ( to keep things easy just fill them ) .Overall I 've got it pretty much working only in some panel sizes the cell is about 1 pixel off of where it should be placed ( overlapping the line ) .TBH I have n't really done enough calculating to possibly find the answer mysel...
public class Gui extends JFrame { public static void main ( String [ ] args ) { new Gui ( ) .setVisible ( true ) ; } public Gui ( ) { setDefaultCloseOperation ( WindowConstants.EXIT_ON_CLOSE ) ; add ( new JPanel ( ) { public static final int SIZE = 3 ; /** Line thickness ratio to a block */ public static final float LI...
Calculate cell sizes and draw ( with lines in between ) them
Java
I wonder if the following two swnippest are semantically identical , and , if not , what are the differences ( we assume that we want to compute a result of type R , and want to guard against exception X that may be thrown in the course of doing so ) : and the following : As far as I can see , it boils down to if a try...
public R tcf ( ... . ) { try { R some = ... ; ... compute the result ... . return some ; } catch ( X exception ) { ... exception handling ... . } finally { ... clean up ... . } } public R tc ( ... . ) { try { R some = ... ; ... compute the result ... . return some ; } catch ( X exception ) { ... exception handling ... ...
Factoring out the finally { ... } block
Java
I am running this code with IntelliJ IDEA , but it looks like the submodule is not running.The following is the output of the program:
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -package org.zpf.service ; public interface Services { void test ( ) ; } module org.zpf.service.Services { exports org.zpf.service ; } -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -package org.zpf.impl ; import org.zpf.service.Servic...
Why is my Java9 module service not working ?
Java
Is there a way in Java 8 to transform an Array/Collection using map ( ) without having to reassign the created copy , e.g.instead of ? If not , what 's the reason for this design decision ?
Arrays.stream ( array ) .mapInPlace ( x - > x / 100 ) ; list.stream ( ) .mapInPlace ( e - > e.replaceAll ( `` `` , `` '' ) ) ; array = Arrays.stream ( array ) .map ( x - > x / 100 ) .toArray ( ) ; list = list.stream ( ) .map ( e - > e.replaceAll ( `` `` , `` '' ) ) .collect ( Collectors.toList ( ) ) ;
Java 8 - Map an Array/Collection in place
Java
I 've tried to scan JEP-286 about local type inference . I see that this works only for local variables - understood . So this does work indeed : I do see that this on the other hand does not compile : It 's obvious that it does not , since the JEP says so . Now my question : It makes perfect sense for a public/protect...
public class TestClass { public static void main ( String [ ] args ) { var list = new ArrayList < > ( ) ; list.add ( `` 1 '' ) ; System.out.println ( list.get ( 0 ) ) ; // 1 } } public class TestClass { public var list = new ArrayList < > ( ) ; public static void main ( String [ ] args ) { } }
Local Type Inference vs Instance