lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
While looking through the Selenium source code I noticed the following in the PageFactory : What is the benefit of having the following line ? Would n't it have made sense to just make the parameter final , and then passing that along to the next method without declaring the new reference ?
public static < T > T initElements ( WebDriver driver , Class < T > pageClassToProxy ) { T page = instantiatePage ( driver , pageClassToProxy ) ; initElements ( driver , page ) ; return page ; } public static void initElements ( WebDriver driver , Object page ) { final WebDriver driverRef = driver ; initElements ( new ...
Redeclaration of parameters
Java
I 'm wondering what the following pattern is called , if it has a name at all.PurposeStore data that is associated with an object ( MyObject ) , but that is private to an implementation of an interface that deals with that object . Clients of the object have no business looking at this data . AlternativesSome alternati...
public interface MyApi { void doSomething ( MyObject x ) ; } public class MyObject { public interface Attachment { } // empty interface , type bound only private Attachment attachment ; public void setAttachment ( Attachment attachment ) { this.attachment = attachment ; } public < T extends Attachment > T getAttachment...
What 's this java pattern called ?
Java
I was analyzing case where DecimalFormat rounded one BigDecimal number and on other machine , it is truncated . I have verified all configurations on both machines ( and all are same , i assume ) .Only difference which i have figured out is JDK version . Machine 1 is running on JDK1.6 . But , i have tried same with JDK...
DecimalFormat decimalFormat = new DecimalFormat ( `` # , # # # .00 '' ) ; BigDecimal anObject = new BigDecimal ( `` 3.8880 '' ) ; String str = decimalFormat.format ( ( ( Number ) anObject ) .doubleValue ( ) ) ; System.out.println ( str ) ;
DecimalFormat results in two different results on different machines
Java
I 'm relatively new with Java and I 've always had problems with the Try/Catch functions in the code so I was wondering if you guys could help me out.The issue I 'm having is that I 've written a try/catch but I get an error message saying that the exception is never thrown . I 've written a similar statement in anothe...
public String getMatchedLogs ( String matchStr , File logFile ) { String fileLine = `` '' ; try { Scanner ipScan = new Scanner ( fileLine ) ; if ( fileLine.indexOf ( matchStr ) > -1 ) { output += fileLine ; } else { System.out.println ( fileLine.indexOf ( `` '' ) ) ; } } catch ( FileNotFoundException fnfe ) { System.ou...
Java Try/Catch Issues
Java
I am facing problem of duplicate rows in the JXTable . If I sort the JXTable data while the new rows are being inserted in JXTable , the final result in JXTable shows duplicate rows that make invalid result in table . Even it also shows correct count of rows that has been inserted but some rows are completely missing w...
public void addingItems ( DefaultTableModel defaultTableModel ) { for ( int i=0 ; i < numberofItems ; i++ ) { Vector vobject = new Vector ( ) ; vobject.add ( `` ... '' ) ; vobject.add ( `` xxx '' ) ; vobject.add ( `` yyy '' ) ; ... ..vobject.add ( `` '' ) ; defaultTableModel.addRow ( vobject ) ; } tableheader.addMouseL...
How to handle table which sorting and adding data parallel ?
Java
Here 's the example I tried to reproduce from Java Performance : The Definitive Guide , Page 97 on the topic of Escape Analysis . This is probably what should happen : getSum ( ) must get hot enough and with appropriate JVM parameters it must be inlined into the caller main ( ) .As both list and sum variables do not es...
import java.math.BigInteger ; import java.util.ArrayList ; import java.util.stream.IntStream ; public class EscapeAnalysisTest { private static class Sum { private BigInteger sum ; private int n ; Sum ( int n ) { this.n = n ; } synchronized final BigInteger getSum ( ) { if ( sum == null ) { sum = BigInteger.ZERO ; for ...
Why getSum does not get inlined by hotspot jvm ?
Java
To my understanding , < ? extends Object > and < ? > are same.However , when I run the following code < ? extends Object > does not get compiled and is working as expected but < ? > is getting compiled successfully.Can some one help me understand this behavior .
public class Test1 { interface I1 { } interface I2 < T extends I1 > extends Comparable < I2 < ? > > { Comparator < I2 < ? extends I1 > > A = null ; //Comparator < I2 < ? extends Object > > B = A ; // expected compilation fail Comparator < I2 < ? > > B = A ; // compiling successfully.This should n't get compile } }
Generic notation < ? > and < ? extends Object > behaving differently
Java
The goal is to compute F ( n ) modulo m ( m up to 10 power 5 ) , where n may be really huge : up to 10 power 18.My algorithm is too slow.My approach : Calculate and store all Fibonacci numbers up to m , then iterate through that array and apply modulo on the fibonacci's.Once the length of the pisano period is found , i...
import java.math.BigInteger ; import java.util . * ; public class FibonacciAgain { private static ArrayList < BigInteger > calc_fib ( ) { ArrayList < BigInteger > fib = new ArrayList < > ( ) ; fib.add ( BigInteger.ZERO ) ; fib.add ( BigInteger.ONE ) ; for ( int i = 2 ; i < = 100000 ; i++ ) { fib.add ( fib.get ( i - 2 )...
My algorithm for calculating the modulo of a very large fibonacci number is too slow
Java
I have the following code that returns the number of nodes in a tree when a complete Binary Tree is layer layers tall : The odd thing is , when I input 63 into the function ( the minimum value that produces this ) , it gives me back -1 . At 62 , it gives back 9223372036854775807 , so this seems to be caused by an overf...
public static long nNodesUpToLayer ( int layer ) { if ( layer < 0 ) throw new IllegalArgumentException ( `` The layer number must be positive : `` + layer ) ; //At layer 0 , there must be 1 node ; the root . if ( layer == 0 ) return 1 ; //Else , there will be 1 + 2 * ( the number of nodes in the previous layer ) nodes ...
Why is this long overflowing to -1 , instead of the minimum value for the type ?
Java
In this example , the 2nd catch block is unreachable and therefore my code does not compile . However , if I make LimpException extend RuntimeException instead of Exception , it compiles without any trouble . Why ?
public class Finals { public void run ( ) { try { spit ( ) ; } catch ( HurtException e ) { System.out.println ( `` '' ) ; } catch ( LimpException ex ) { // does not compile , unreachable code System.out.println ( `` '' ) ; } } public void spit ( ) throws HurtException { // method that throws the Exception } public stat...
Why does multi-catch RuntimeException compile but multi-catch Exception does not ?
Java
Taking a class in OOP Java and since I am completely new to the language and as of yet unaware of the many tools it has to offer I find myself fumbling in the dark for solutions to simple things , I can hardcode these problems but I feel there is far simpler ways to do this with java.util . Assume I have a list of stri...
String [ ] stringOne = { `` a '' , '' b '' , '' c '' , `` potato '' } ; String [ ] stringTwo = { `` potato '' , `` 13 '' } ;
How do I check two lists of strings against eachother ?
Java
Kind of a long title , but that is generally the question.I want to know if you think its a good idea to do the following.Instead of : I want to have something like : Do you think this is good/terrible/too fancy/too slow ? If you actually think its good I was thinking of using SpEL to implement it , does anyone have so...
public void buyItem ( int itemId , int buyerId ) { if ( itemId < = 0 ) { throw new IlleglArgumentException ( `` itemId must be positive '' ) ; } if ( buyerId < = 0 ) { throw new IlleglArgumentException ( `` buyerId must be positive '' ) ; } // buy logic } @ Defensive ( `` isPositive ( # itemId , # buyerId ) '' ) public...
Is it a good idea to use aspects as a method for removing defensive checks from application logic ?
Java
I 'm writing a program that sets up a GUI to start JUnit test scripts that utilize Selenium WebDriver in Java . The GUI sets up a queue of JUnit tests in the background ( or so i believe ) . On the GUI , I want to utilize a `` stop test '' button that will stop all future JUnit tests that are still in the Queue from ex...
Field field = JUnitCore.class.getDeclaredField ( `` fNotifier '' ) ; field.setAccessible ( true ) ; RunNotifier runNotifier = ( RunNotifier ) field.get ( runner ) ; runNotifier.pleaseStop ( ) ;
Is there a way to stop queued JUnit tests and still keep the JavaFX Gui running ?
Java
This is the module declaration of the java.rmi module : So , there is a cyclic dependency between java.rmi and java.base , right ? Are cycles allowed between platform modules ?
module java.rmi { requires java.base ; requires java.logging ; exports java.rmi.activation ; exports com.sun.rmi.rmid to java.base ; // < -- cycle ... }
Are cycles allowed between platform modules ?
Java
I 'm writing a library that inserts already unit-tested example code ( its source-code , output , and any input files ) into JavaDoc , with lots of customization possibilities . The main way of using this library is with inline taglets , such asSince custom taglets ( and even doclets ) require com.sun , this means they...
{ @ .codelet.and.out my.package.AGreatExample } { @ .codelet my.package.AGreatExample } { @ .file.textlet examples\doc-files\an_input_file.txt } { @ .codelet.and.out my.package.AGreatExample % eliminateCommentBlocksAndPackageDecl ( ) }
How to make inline taglets ( which require com.sun ) more cross-platform ? Is there a non-Oracle/more-cross-platform javadoc parser ?
Java
code should do this : a ) Given an unsorted array of integers , your task is to sort the array by applying the following algorithm ( Assume that the input doesn ’ t contain duplicates ) : Execute the following steps starting from the first element in the array : – Count the number of smaller elements to find the correc...
public class Assignment1_T11_25_2729_Sara_Aly { private int [ ] a ; private int max ; private int n ; int position=0 ; public Assignment1_T11_25_2729_Sara_Aly ( int max ) { a= new int [ max ] ; } public void insert ( int x ) { a [ n ] =x ; n++ ; } public void sort ( ) { int out=0 , smaller=0 ; while ( out < n ) { for (...
why wo n't my sorting algorithm work ?
Java
In order to re-produce the problem as stated in a recent question - Why does ( . * ) * make two matches and select nothing in group $ 1 ? I tried various combination of * and + , inside and outside the brackets , and the result I got was not expected.I would have expected the output , same as one explained in the accep...
String str = `` input '' ; String [ ] patterns = { `` ( . * ) * '' , `` ( . * ) + '' , `` ( .+ ) * '' , `` ( .+ ) + '' } ; for ( String pattern : patterns ) { Matcher matcher = Pattern.compile ( pattern ) .matcher ( str ) ; while ( matcher.find ( ) ) { System.out.print ( `` ' '' + matcher.group ( 1 ) + `` ' : ' '' + ma...
Strange issue with ` ( . * ) * ` , ` ( . * ) + ` , ` ( .+ ) * ` in Java regex
Java
I 'm trying to convert a Map < String , String > to a List < String > using lambdas.Essentially I 'd like to concatenate the key and value with an '= ' in between . This seems trivial but I ca n't find how to do it.E.g .
Map < String , String > map = new HashMap < > ( ) ; map.put ( `` a1 '' , '' b1 '' ) ; map.put ( `` a2 '' , '' b2 '' ) ; map.put ( `` a3 '' , '' b3 '' ) ; // Lambda// Result contains [ `` a1=b1 '' , `` a2=b2 '' , `` a3=b3 '' ] List < String > result ;
Map < S , S > to List < S >
Java
I know double should not be compared by == operator directly , but how about if I define an initial value as 0.0 ? eg : If a is not modified , does a*b==0 always true ?
double a=0.0 ; double b= ...
If double a=0.0 , can I compare a*b==0 directly ?
Java
In Java I can specify generic with wildcard `` ? '' . It is possible to create a map like this one : Map < String , ? > .I 'm working with C # and I need a Dictionary < String , SomeInterface < ? > > ( where ? can be int , double , any type ) . Is this possible in C # ? EDIT : Example : I was trying to map this objects...
interface ISomeInterface < out T > { T Method ( ) ; void methodII ( ) ; } class ObjectI : ISomeInterface < int > { ... } class ObjectII : ISomeInterface < double > { ... } class ObjectIII : ISomeInterface < string > { ... . } Dictionary < String , ISomeInterface < ? > > _objs = new Dictionary < String , ISomeInterface ...
Question about generics in C # comparing to Java
Java
There is no compiler error . I am getting this error in runtime.I am using many library in my project . Library link : https : //github.com/nguyenhoanglam/ImagePickerI added glide libraryChanged compileSdkVersion & targetSdkVersion from 28 to 29.Migrated project to AndroidXThere was no problem before the change.Project...
error : package com.nguyenhoanglam.imagepicker.activity does not exist // Top-level build file where you can add configuration options common to all sub-projects/modules.buildscript { repositories { google ( ) jcenter ( ) maven { url 'https : //maven.google.com ' } maven { url `` https : //jitpack.io '' } } dependencie...
error : package com.nguyenhoanglam.imagepicker.activity does not exist
Java
I 'm using Hibernate and MySql and today I setted a composite primary key in one of my table , so below : DefSelfLearningAnd this entity is OneToMany with SelfLearning : This is my java entity : the class for the composite key : and SelfLearning class : but when I create a defSelfLearning all work fine , but when I cre...
@ Entity @ Table ( name = `` defselflearning '' , catalog = `` ats '' ) public class DefSelfLearning implements java.io.Serializable { /** * */ private static final long serialVersionUID = 1L ; @ EmbeddedId private DefSelfLearningKeys defSelfLearningKeys ; private Ecu ecu ; private String excelColumn ; @ JsonIgnore pri...
Composite primary Key and Data truncation error
Java
What costs for sure less time for execution between the two options : A : or : B :
if ( something ! =null ) { ... } else { //log } try { something.getField ( ) ; ... } catch ( Exception e ) { //log }
What is more time optimal : if or exception
Java
So , I made this relatively simple code , and neither me nor IntelliJ IDEA see anything wrong with it , but javac keels over on the marked line , complaining it ca n't infer the types : Splitting the problematic line into 2 with explicit types helps , but the type signature is longer than the lambda , completely defeat...
import java.util.List ; import java.util.stream.Collectors ; public class GenericsBreakJavac8 { public interface Edge < N > { N getNode ( ) ; } @ FunctionalInterface public interface EdgeCreator < N , E extends Edge < N > > { E createEdge ( N node ) ; } public static < N > List < Edge < N > > createEdges ( List < N > n...
Why does type inference fail here ?
Java
The Cassandra connector fails after confluent upgrade to 3.3.0 . The version of Cassandra driver is 3.3 . The stack is given below.I have tried by updating the guava and io.netty dependencies , but it does n't resolved the issue .
[ 2017-09-14 08:56:28,123 ] ERROR java.lang.reflect.InvocationTargetException ( com.cantiz.nucleus.kafka.connector.cassandra.CassandraSinkTask:72 ) java.lang.RuntimeException : java.lang.reflect.InvocationTargetExceptionat com.google.common.base.Throwables.propagate ( Throwables.java:240 ) at com.datastax.driver.core.N...
Kafka-cassandra connector fails after confluent 3.3 upgrade
Java
I came across the following java code . Here interface contains two methods out of which only one method is implemented in the enum . It is written that name ( ) is implemented automatically . My question is how is it possible ? I have not read any rule regarding automatic method implementation in enum before . So what...
interface Named { public String name ( ) ; public int order ( ) ; } enum Planets implements Named { Mercury , Venus , Earth , Mars , Jupiter , Saturn , Uranus , Neptune ; // name ( ) is implemented automagically . public int order ( ) { return ordinal ( ) +1 ; } }
java enum confusion
Java
I threw together a quick Java implementation of a Taylor series expansion for the exponential function , because it was easy and fun : I 'm ashamed to admit that my employer is still using JDK 6 and JDK 7 ; I 'm not writing on JDK 8 during my work day yet . I have not groked all new features in the JDK , including lamb...
package math.series ; import java.util.stream.IntStream ; /** * Created by Michael * Creation date 3/6/2016 . * @ link https : //stackoverflow.com/questions/35826081/calculating-ex-in-c-sharp * @ link https : //en.wikipedia.org/wiki/Leibniz_formula_for_ % CF % 80 */public class TaylorSeries { public static final int DE...
Remember last value returned from a JDK 8 lambda
Java
ScenarioI have built an API for my app that sits behind a gateway with request throttling . Before I built the API my app coordinated requests itself and thus could start many many requests in milliseconds to synchronize data for the app across the 9 providers being used to fetch data . Now , this logic has been pushed...
/luna/locations/xtide/ { id } - Luna Event detail ( read : tide times ) /solar/locations/xtide/ { id } - Solar Event detail ( read : sunrise/sunset ) /water/locations/ { provider } / { id } { ? daysData } - Water Event detail ( read : swell measures ) /meteo/wwo/weather { ? query , daysData } - Meteo Event detail ( rea...
Using RxJava to chain a series of operations - where to go next ?
Java
I have a complex situation that I 'm trying to deal with involving character encoding.I have a perl program which is communicating with a java endpoint via thrift , the java is then using the data to make a request to a legacy php service . It 's ugly , but part of a migration plan so needs to work for a short while . ...
'offer_message ' = > `` < & lt ; > & gt ; & & amp ; \x { c3 } \x { 82 } \x { c2 } \x { a9 } & copy ; < script > alert ( \ '' XSS\ '' ) ; < /script > https : //url.com/imghp ? hl=uk '' , < & lt ; > & gt ; \\n & & amp ; \\n���© & copy ; \\n < script > alert ( \ '' XSS\ '' ) ; < /script > \\nhttps : //www.google.com.u...
thrift character encoding , perl to java
Java
Is it possible to rewrite the following a bit more concise that I do n't have to repeat myself with writing this.x = x ; two times ?
public class cls { public int x = 0 ; public int y = 0 ; public int z = 0 ; public cls ( int x , int y ) { this.x = x ; this.y = y ; } public cls ( int x , int y , int z ) { this.x = x ; this.y = y ; this.z = z ; } }
Java initializing classes without repeating myself
Java
This sample data is returned by Web Service 200,6 , `` California , USA '' I want to split them using split ( `` , '' ) and tried to see the result using simple code.Unfortunately this is the resultThe expected result should beI tried different regular expressions and no luck . Is it possible to escape the given regula...
String loc = `` 200,6 , \ '' California , USA\ '' '' ; String [ ] s = loc.split ( `` , '' ) ; for ( String f : s ) System.out.println ( f ) ; 2006 '' California USA '' 2006 '' California , USA ''
Java : Regular Expression escape Regular Expression
Java
Curious about how fast self addition would grow , I wrote a quick little loop in Java to see : The output was unexpected : Why is this ? count is initialized to 1 , so the inner addition should be doing count + count or 1 + 1 . Why is the result 0 ?
int count = 1 ; while ( true ) { System.out.println ( count ) ; count += count ; } 00000 ...
Why does this self addition equal 0 ?
Java
is there a difference between these two initializations of the final variable value ? and -- EDIT : A more complex example , involving subclasses . `` 0 '' is printed to stdout in this case , but 7 is printed if i assign the value directly .
class Test { final int value = 7 ; Test ( ) { } } class Test { final int value ; Test ( ) { value = 7 ; } } import javax.swing . * ; import java.beans.PropertyChangeListener ; class TestBox extends JCheckBox { final int value ; public TestBox ( ) { value = 7 ; } public void addPropertyChangeListener ( PropertyChangeLis...
Is there a difference between directly assigning a final variable and assigning a final variable in the constructor ?
Java
Netbeans IDE is good at spotting code that could give you trouble . Why is a warning not issued for given that I 'm calling the base class function foo ( ) in the child constructor ? Of course that 's perfectly legitimate as the base object is constructed by the point foo ( ) is called , but a foo ( ) is implicitly a v...
public class Base { Base ( ... ) { ... ; } public void foo ( ) { ... ; } } public class Child extends Base { Child ( ... ) { super ( ... ) ; foo ( ) ; } }
Netbeans IDE not issuing warnings about methods called in constructors
Java
I 'm trying to write a Map builder . One of the constructors will allow the client to specify the type of Map they wish to buildThe intent is that it should be possible to construct instances of the builder with : orIt seems that the type signature of the constructor argument does n't currently support this , because t...
public class MapBuilder < K , V > { private Map < K , V > map ; /** * Create a Map builder * @ param mapType the type of Map to build . This type must support a default constructor * @ throws Exception */ public MapBuilder ( Class < ? extends Map < K , V > > mapType ) throws Exception { map = mapType.newInstance ( ) ; ...
Restrict a generic Class parameter to classes that implement Map
Java
I am a little confuse about the dynamic programming solution for combination sum , that you are given a list of numbers and a target total , and you want to count how many ways you can sum up to this target sum . Numbers can be reused multiple times . I am confused about the inner loop and outer loop that whether they ...
int [ ] counts = new int [ total ] ; counts [ 0 ] = 1 ; // ( 1 ) for ( int i = 0 ; i < = total ; i++ ) { for ( int j = 0 ; j < nums.length ; j++ ) { if ( i > = nums [ j ] ) counts [ i ] += counts [ i - nums [ j ] ] ; } } // ( 2 ) for ( int j = 0 ; j < nums.length ; j++ ) for ( int i = nums [ j ] ; i < = total ; i++ ) {...
Dynamic programming with Combination sum inner loop and outer loop interchangeable ?
Java
How can I perform multiple unrelated operations on elements of a single stream ? Say I have a List < String > composed from a text . Each string in the list may or may not contain a certain word , which represents an action to perform . Let 's say that : if the string contains 'of ' , all the words in that string must ...
List < String > strs = ... ; List < Integer > wordsInStr = strs.stream ( ) .filter ( t - > t.contains ( `` of '' ) ) .map ( t - > t.split ( `` `` ) .length ) .collect ( Collectors.toList ( ) ) ; List < String > linePortionAfterFor = strs.stream ( ) .filter ( t - > t.contains ( `` for '' ) ) .map ( t - > t.substring ( t...
Perform multiple unrelated operations on elements of a single stream in Java
Java
Is n't it true that if you cast a float number like 1.0012 to an integer , it will become 1 ? Then why is it when I write : instead of 1.07592 ~ become 1 it becomes 0 ? ( Java compiled with Eclipse ) .
( int ) ( 14/13-0.001 )
Why ( int ) ( 14/13 - 0.001 ) yield 0 and not 1 ?
Java
For example , if elements are { 1 , 2 } ( n = 2 ) and m = 3 , the method should generate a list of arrays like this { [ 1,1,1 ] , [ 1,1,2 ] , [ 1,2,1 ] , [ 2,1,1 ] , [ 1,2,2 ] , [ 2,2,1 ] , [ 2,1,2 ] , [ 2,2,2 ] } . I know Python can do things like y = itertools.product ( ( 1 , 2 ) , repeat=3 ) , but how do I implement...
public static List < List < Integer > > permute ( List < Integer > list , int need ) { List < List < Integer > > result = new ArrayList < > ( ) ; if ( need -- ==0 ) { result.add ( list ) ; return result ; } for ( int current : list ) insert ( permute ( list , need ) , current , result ) ; return result ; } private stat...
How to generate a list of arrays ( all have the length M ) with N possible elements ( M > N ) in Java ?
Java
The question is more general and is not related to pros and cons of both styles . The question is should I prefer whenever it is possible to use Stream instead of for loops because it is declarative with a good readability ? I was arguing with my colleague about pros and cons of using streams and for loop . I agree tha...
try { Map < String , String > someResult= elements.stream ( ) .filter ( throwingPredicateWrapper ( element- > client.hasValue ( element ) ) ) .collect ( Collectors.toMap ( Function.identity ( ) , throwingFunctionWrapper ( element - > client.getValue ( element ) ) ) ) ; return someResult ; } catch ( Exception e ) { LOGG...
Streams or for loops
Java
I 'm downloading an attachment using Java mail API and whenever there is a small change in network state , my app gets stuck and I have to restart it , it 's not even crashing.This is the code snippet : What is the best way to deal with this issue ? Thanks .
InputStream is = bodyPart.getInputStream ( ) ; String fileName = MimeUtility.decodeText ( bodyPart.getFileName ( ) ) ; // Downloading the fileFile f = new File ( Constants.getPath ( ) + fileName ) ; try { FileOutputStream fos ; fos = new FileOutputStream ( f ) ; byte [ ] buf = new byte [ 8*1024 ] ; int bytesRead ; whil...
InputStream - Dealing with network changes
Java
I 'm using scala and every time I paste my code it changes the format . I reset the settings but it keeps doing it . I ca n't find the setting I tried to disable in Smart Keys but still . What I want to pasteaddItem : `` food '' , `` arroz '' , `` arroz.jpg '' , 300 , 1.50 ; What gets pasted
addItem //todo : labels is not supported '' food '' '' arroz '' '' arroz.jpg '' 3001.50
How to stop intellij from converting my code ?
Java
I am working on a golf application that includes a scorecard system . I am storing each score for each player in the database and I need to come up with a query to determine tee order . So for example if the players have played 3 holes and the scores look like this ... ... Then the order needs to look like this ... ......
Player 1 2 3 -- -- -- -- - - - -Player 1 : 3 , 4 , 3Player 2 : 2 , 3 , 3Player 3 : 2 , 4 , 3 1 . ) Player 22 . ) Player 33 . ) Player 1
SQL to Determine Tee Order in Golf Application
Java
Why are total_amount and tax_amount concatenated together as strings instead of added together as numbers in the below println statement ?
public class Test { int total_amount , tax_amount ; public void cal ( int total_amount , int tax_amount ) { System.out.println ( `` Total amount : `` +total_amount+tax_amount ) ; } public static void main ( String [ ] args ) { new Test ( ) .cal ( 100 , 20 ) ; } } Output Total amount : 10020Expected Total amount : 120
int variables being concatenated instead of added inside System.out.println ( )
Java
I have a class like followings.I am having a list like followings.Assume I am populating above list with some elements . I want to declare a method which performs grouping and summing operation in that list . As an example , assume I am giving the following elements in a list as the input for that method . That method ...
public class Votes { String name ; int likes ; int dislikes ; //constructors , getters and setters } List < Votes > votesList ; votesList.add ( new Votes ( `` A '' , 10 , 5 ) ) ; votesList.add ( new Votes ( `` B '' , 15 , 10 ) ) ; votesList.add ( new Votes ( `` A '' , 20 , 15 ) ) ; votesList.add ( new Votes ( `` B '' ,...
Using lambda expressions for summing up member variables ?
Java
I have read few posts about garbage collection in Java , but still I can not decide whether clearing a collection explicitly is considered a good practice or not ... and since I could not find a clear answer , I decided to ask it here.Consider this example : From what I saw in implementations of e.g . LinkedList or Has...
List < String > list = new LinkedList < > ( ) ; // here we use the list , perhaps adding hundreds of items in it ... // ... and now the work is done , the list is not needed anymorelist.clear ( ) ; list = null ;
Garbage collector vs. collections
Java
I 'm trying to read Unicode codepoints from a text file in Java . The InputStreamReader class returns the stream 's contents int by int , which I hoped would do what I want , but it does not compose surrogate pairs.My test program : This behaves as follows : My problem is that the surrogate pairs making up the pizza em...
import java.io . * ; import java.nio.charset . * ; class TestChars { public static void main ( String args [ ] ) { InputStreamReader reader = new InputStreamReader ( System.in , StandardCharsets.UTF_8 ) ; try { System.out.print ( `` > `` ) ; int code = reader.read ( ) ; while ( code ! = -1 ) { String s = String.format ...
Read text stream codepoint by codepoint
Java
Well my doubt is this one : In Java , it is disallowed to inherit from an array , ie , one ca n't do things like : Or even better : But arrays actually implement a specific interface and are considered objects . ie , one expects of array instances the same methods exposed by Object , plus a specific array field , the f...
class FloatVec extends float [ ] { // Vector methods . } FloatVec somevec = new FloatVec ( ) [ ] { 1 , 2 , 3 } ; // With array initializer . class FloatVec3 extends float [ 3 ] { // Regular accessor . public float getX ( ) { return this [ 0 ] ; } // Or say , make it the 'this ' implicit like with other fields : public ...
Is inheriting from a primitive array impossible from the JVM 's perspective ?
Java
I have a TableView which contains columns that always display a writable textfield . I would like to have the textfield change colour if the `` BigDecimal '' value of column1 's value is larger than the column2 's value . I can stylize the textfield in the EditableTextCell class ( for example if the text is not a valid...
package tester ; import java.util.Objects ; import javafx.beans.value.ObservableValue ; import javafx.beans.value.WritableValue ; import javafx.geometry.Pos ; import javafx.scene.control.TableCell ; import javafx.scene.control.TextField ; public class EditableTextCell < E > extends TableCell < E , String > { private fi...
How to apply conditional formatting to a TableCell textfield based on two properties on a row in TableView
Java
This is a design issue I keep running into , so I thought I would finally put it out there and see how people would approach it . The problem is as follows : I identify a certain class that for the most part describes all instances of objects I will use , both behaviour and data-wise . That 's great and works well for ...
public class Something { private int id ; private String fieldA ; private String fieldB ; private List < Data > list ; // Then we have getters , setters , and some base methods } public class SomethingElse extends Something { private String dataSpecificToSomethingElse ; // Then we have getters , setters , and some new-...
OO design : generic handling of sub classes that introduce new fields
Java
In `` Think in Java '' , the author says : You just leave the `` public '' keyword off the class , in which case it has package access . ( That class can be used only within that package . ) To prove this , I create one public class and one no-public class : But when I call them from another class in the same package :...
package com.ciaoshen.thinkinjava.chapter7 ; import java.util . * ; //My public classpublic class PublicClass { //default constructor public PublicClass ( ) { System.out.println ( `` Hello , I am PublicClass . `` ) ; } } //Non public class//It should be package reachableclass PackageReachableClass { //default constructo...
Is really “ No Public Class ” reachable within its package ?
Java
I have an int [ ] [ ] object . It is defined in my code as below : Would it be possible to get the value of the first value ( on the left ) within each of the pairs of parentheses and store them as individual int variables using a for loop ? Basically , is it possible to extract the `` 20 '' , `` 73 '' and `` 82 '' and...
public int [ ] [ ] position = { { 20 , 30 } , { 73 , 91 } , { 82 , 38 } } ;
Java : How to get individual int values out of int [ ] [ ]
Java
I have a java program which is basically a game . It has a class named 'World ' . The `` World '' class has a method 'levelChanger ( ) ' , and another method 'makeColorArray ( ) ' . The makeColorArray ( ) method makes a 2d array of type 'Color ' . This array stores Color-objects from a PNG image . This array is used by...
public class World { private BufferedImage map , map1 , map2 , map3 ; private Color [ ] [ ] colorArray ; public World ( int scrWd , int scrHi ) { try { map1 = ImageIO.read ( new File ( `` map1.png '' ) ) ; map2 = ImageIO.read ( new File ( `` map2.png '' ) ) ; map3 = ImageIO.read ( new File ( `` map3.png '' ) ) ; } catc...
How to stop one thread from modifying an array which is being used by another thread ?
Java
First I will try to explain the idea behind this code.I have a bunch of classes ( Processors ) that can process a certain type of other classes ( Processables ) . I have a List of Processors to execute them in a certain order . I have a Map that will retrieve me the data to process ( Processables ) for a certain Proces...
public abstract class AbstractProcessable { ... } public class DummyProcessable extends AbstractProcessable { ... } public abstract class AbstractProcessor < T extends AbstractProcessable > { public abstract void process ( List < T > listOfProcessables ) ; } public class DummyProcessor extends AbstractProcessor < Dummy...
How to use collections and generics with wildcards ?
Java
I 'm trying to port Java code to C # and I 'm running into odd bugs related to the unsigned shift right operator > > > normally the code : Would be the equivalent of Java 's : However for the case of -2147483648L which you might recognized as Integer.MIN_VALUE this returns a different number than it would in Java since...
long l = ( long ) ( ( ulong ) number ) > > 2 ; long l = number > > > 2 ;
Unsigned shift right in C # Using Java semantics for negative numbers
Java
We implemented a binding for some typical Grid usages in application . It works just fine , except if you modify a store , for example add a record , you 'd see n + TWO identical records in view.When I examined store 's state , it shown n + 1 values.It goes as if I have a grid with one record shown in it and call : gri...
freqsGrid = new AwesomeGridPanel ( ) { @ Override public void createColumns ( ) { /**/ } } ; freqBinding = AwesomeGridBinding.createGridBinding ( freqsGrid , `` frequencies '' ) ; public class AwesomeGridBinding { public static FieldBinding createGridBinding ( AwesomeGridPanel grid , String property ) { return new Fiel...
FieldBinding for Grid . View remains inconsistent after adding new record to Store
Java
So , I currently have a Board class that is composed of Pieces . Each Piece has a color and a string that describes the kind of piece . It also has a 2d matrix with bits either set on or off , that allows me to know which pixels to paint with the desired color or not.My question is , which class should have the respons...
Boolean [ , ] IsPixelSet ( int x , int y ) void DrawPieceOnBoard ( ) { for ( int y = 0 ; y < height ; ++y ) { for ( int x = 0 ; x < width ; ++x ) { if ( piece.IsPixelSet ( x , y ) { board.DrawPixelAt ( x , y , piece.GetColor ( ) ) ; } } } }
Which class has the responsibility of setting Piece 's pixels on a Board ( 2d matrix ) ? The Piece or the Board ?
Java
I have a use case where I want to convert a struct field to an Avro record . The struct field originally maps to an Avro type . The input data is avro files and the struct field corresponds to a field in the input avro records.Below is what I want to achieve in pseudocode.My question is : how can I implement the conver...
DataSet < Row > data = loadInput ( ) ; // data is of form ( foo , bar , myStruct ) from avro data . // do some joins to add more datadata = doJoins ( data ) ; // now data is of form ( a , b , myStruct ) // transform DataSet < Row > to DataSet < MyType > DataSet < MyType > myData = data.map ( row - > myUDF ( row ) , enc...
How to convert a struct field in a Row to an avro record in Spark Java
Java
Here is my snippet of code : I created a local class to see what kind of access modifier do i get when not written any modifier for variable in local class from compiler.This is what i got in JAVAP So basically flags field is left blank so i 'm confused what kind of access modifier does this variable get because if i a...
public class Test { public static void main ( String [ ] args ) { class EnglishHelloThere { int a=10 ; } } } Compiled from `` Test.java '' class com.Test $ 1EnglishHelloThere SourceFile : `` Test.java '' EnclosingMethod : # 21. # 23 // com.Test.main InnerClasses : # 27= # 1 ; //EnglishHelloThere=class com/Test $ 1Engli...
What does no flags for field means in Class format in JAVA ?
Java
Why are both c1 and c2 are not seen as two Strings but instead one String and one Integer ?
Arrays.asList ( `` duck '' , '' chicken '' , '' flamingo '' , '' pelican '' ) .stream ( ) .reduce ( 0 , ( c1 , c2 ) - > c1.length ( ) + c2.length ( ) , ( s1 , s2 ) - > s1 + s2 ) ;
Deciphering Stream reduce function
Java
I am required me to use RadioButtons and Checkboxes in my Java program so the user can easily select the options they would like to use ( It is a `` gas station '' ) .The error I am getting is at this partI do not understand why at bronzeG.addItemListener , it says
import javax.swing . * ; import java.awt . * ; import java.awt.event . * ; public class New_Gas_Bar extends JFrame { public JPanel panel1 , panel2 , panel3 , panel4 , panel5 ; public JLabel main1 , main2 , main3 ; public JLabel gasBar , total ; public JButton button1 , button2 , button3 , button4 ; public JRadioButton ...
Not sure what this issue is ?
Java
I wonder if its okay to comment methods in c in the same way you comment code in java-language ? that is in the same manner in cOf course its up to the programmer but I would like to know if c-programmers uses these @ param or not ?
/** * * @ param x * @ param y * @ return */protected boolean myMethod ( int x , int y ) { return true ; } /** * * @ param x * @ param y * @ return */int myMethod ( int x , int y ) { return 1 ; }
Commenting methods in c
Java
I came across the Java code below which looks good at first but never compiles : Below is the error message which comes in the IDE : variable USER_ID might already have been assigned.Is there any problem with the value assignment to the static final variable ?
public class UnwelcomeGuest { public static final long GUEST_USER_ID = -1 ; private static final long USER_ID ; static { try { USER_ID = getUserIdFromEnvironment ( ) ; } catch ( IdUnavailableException e ) { USER_ID = GUEST_USER_ID ; System.out.println ( `` Logging in as guest '' ) ; } } private static long getUserIdFro...
Why program is not allowing to initialize the static final variable ?
Java
I ran into a situation earlier where I tried the following two bits of code : andThe first one failed ( and obviously so , I 'm trying to implicitly cast a float to an int ) . But the second one worked perfectly fine . The compiler did n't complain and I did n't get any runtime errors . Why does the second one work , w...
int score = 100 ; score = score * 1.05 ; int score = 100 ; score *= 1.05 ;
Why does *= not give any errors when implicitly casting a float to an int ?
Java
I have a situation where I need to display a JOptionPane after clicking on a JButton . The JButton has a default icon , and a rollover icon ( which displays when , well , the mouse rolls-over the button ) . However , once the button is clicked and a JOptionPane appears , the rollover icon does not change back to the or...
import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import javax.swing.JButton ; import javax.swing.JDialog ; import javax.swing.JFrame ; import javax.swing.JOptionPane ; import javax.swing.JPanel ; import javax.swing.UIManager ; public class ButtonUnrollover { public static void main ( String [ ...
`` Un-rollover '' a JButton when a JOptionPane is displayed
Java
There is a Student class which has name , surname , age fields and getters for them.Given a stream of Student objects . How to invoke a collect method such that it will return Map where keys are age of Student and values are TreeSet which contain surname of students with such age.I wanted to use Collectors.toMap ( ) , ...
stream ( ) .collect ( Collectors.toMap ( Student : :getAge , Student : :getSurname , new TreeSet < String > ( ) ) ) ` .
Java API Streams collecting stream in Map where value is a TreeSet
Java
I 've got a piece of undocumented code , which I have to understand to fix an error . The following method is called optimization and it is supposed to find the maximum of a very complex function f. Unfortunately , it fails under some circumstances ( i.e . it reaches the `` Max iteration reached '' line ) .I already tr...
public static double optimization ( double x1 , double x2 , double x3 , Function < Double , Double > f , double epsilon ) { double y1 = f.apply ( x1 ) ; double y2 = f.apply ( x2 ) ; double y3 = f.apply ( x3 ) ; double a = ( x1* ( y2-y3 ) + x2* ( y3-y1 ) + x3* ( y1-y2 ) ) / ( ( x1-x2 ) * ( x1-x3 ) * ( x3-x2 ) ) ; double...
What is that optimization algorithm called ?
Java
For cleaning a list of data , I have created a method which accepts the list of data and list of cleaning operation to be performed.The issue here is that we are creating the whole list again as Collectors.toList ( ) returns a new list.Can we achieve the same result without using the extra space ? Below is the code for...
public < T > List < T > cleanData ( List < T > data , List < Function < T , T > > cleanOps ) { List < T > dataNew=data.stream ( ) .map ( ( str ) - > { T cleanData = str ; for ( Function < T , T > function : cleanOps ) { cleanData=function.apply ( cleanData ) ; } return cleanData ; } ) .collect ( Collectors.toList ( ) )...
Cleaning a list of data in Java8
Java
This answer to a very old question about Clojure-Java interop explains how to use gen-class with the : state and : init keywords to create a single public instance variable accessible from Java . This is enough if you only need one piece of data to be available to Java classes , or if you can require the Java classes t...
( ns students.Foo ( : gen-class : name students.Foo : state bar ; : state baz : init init ) ) ( defn -init [ ] [ [ ] 42 ] ) package students ; public class Bar { public static void main ( String [ ] args ) { Foo foo = new Foo ( ) ; System.out.println ( foo.bar ) ; // System.out.println ( foo.baz ) ; } }
How to create multiple Java member variables with Clojure 's gen-class
Java
I have a JTree where users can drop elements from other components . When the users hovers over nodes in the tree ( during `` drop mode '' ) the most near lying node is highlighted . This is achieved in the implementation of TransferHandler.Each time a new node is selected ( also during `` drop mode '' ) , this will ki...
@ Overridepublic boolean canImport ( TransferSupport support ) { //Highlight the most near lying node in the tree as the user drags the //mouse over nodes in the tree . support.setShowDropLocation ( true ) ;
Is there a way to detect if a drop is about to take place on a JTree ?
Java
Possible Duplicate : Variable scope in a switch case I 've got a code like this : and i 'm interesting why it 's possible to use variable declared after first case label in the second one even if first state will never be reached ?
switch ( a ) { case b : Object o = new Object ( ) ; return o ; case c : o = new Object ( ) ; return o ; }
Why object declared after one case label is available in others ?
Java
i have multiple Xml files , in a List < File > . What i want is to transform those xml into one Xml with an Xsl : My problem is that when i am looping and apply the transform with a TransformerFactory it always erase the output XML . I want to edit the output instead.I know that i can do it in java with a temporary XML...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < xsl : stylesheet version= '' 1.0 '' xmlns : xsl= '' http : //www.w3.org/1999/XSL/Transform '' > < xsl : output method= '' xml '' indent= '' yes '' / > < xsl : template match= '' testsuites '' > < xsl : call-template name= '' summary '' / > < /xsl : template > < xsl...
Write at the end of an xml
Java
This might not make much sense in terms of Android SDK , but , in C++ I am used to keeping my main.cpp ( and specifically main ( ) function ) as a place where I declare and initialize other classes/objects , and afterwards all the things that my application does take place in those classes . I never come back and check...
SomeTest test = new SomeTest ( MainActivity.this ) ;
Keeping things decentralized Android
Java
I have a list of Objects that I want to map to another list that is joined by another object of that type.i.e : This is just an example , the list can be of any type not just Integer.My use case is this : I have a list of objects of type X , and I need to insert a certain object between every 2 items of that list.I kno...
List < Integer > list = List.of ( 5,6,7,8 ) ; // is it possible to insert ` 1 ` between every item in the list ? // joined list = [ 5,1,6,1,7,1,8 ]
How to join list of non-string objects using streams
Java
My Java program needs to synchronously move a file on a server , ie . within the same set of local file systems . The obvious solution is to use Files.move ( ) . However , I 've read that in some cases , eg . across file systems , a move will fall-back to copy-and-delete . As I 'm moving large files I 'd like to be abl...
try { Files.move ( src , dest , CopyOption.ATOMIC_MOVE ) ; } catch ( AtomicMoveNotSupportedException e ) { // Perform a copy instead ( and report progress ) }
Is it possible to determine programmatically whether a file move will result in a copy ?
Java
I have a class with a constructor signature as follows : That 's fine . But I want to overload the constructor , for the case that if you do n't provide Function func , it will just use ( item ) - > { return item ; } . I 've written another constructor that looks like this : This is causing a type mismatch error , beca...
public class MyClass < U > { public < T > MyClass ( Set < T > data , Function < T , U > func ) ... } public < T > MyClass ( Set < T > data ) { this ( data , ( item ) - > { return item ; } ) ; }
Java Generic Types Mismatch Error
Java
I have a Map . The map has n elements ( lets take for this example these 9 ) Now I want to iterate over this map , and remove the n-th element using the iterator.From the javadoc , I 'd assume , the semantics of the remove are well defined.But depending on the implementation of the map - i.e . HashMap vs TreeMap there ...
Map < Integer , String > map = ... map.put ( 1 , '' one '' ) ; map.put ( 2 , '' two '' ) ; map.put ( 3 , '' three '' ) ; map.put ( 4 , '' four '' ) ; map.put ( 5 , '' five '' ) ; map.put ( 6 , '' six '' ) ; map.put ( 7 , '' seven '' ) ; map.put ( 8 , '' eigth '' ) ; map.put ( 9 , '' nine '' ) ; private void remove ( in...
TreeMap iterator.remove ( ) modifies the last Entry
Java
I tried to enable Java 8 features in Android Studio like suggested in https : //android.com : After that I added compile 'net.sourceforge.streamsupport : streamsupport:1.5.1 ' and was able to use lambdas . Since I 've done that , the Gradle build takes forever ( I killed the process after 20 minutes to try other soluti...
defaultConfig { ... jackOptions { enabled true } } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
Gradle building takes forever after upgrading to Java 8
Java
I have a Boolean array and I am trying to make a corresponding char array , so that to each true in the new array corresponds a 1 and for each false a 0. this is my code but it seems the new array is empty , because nothing prints , the Boolean nums [ ] prints fine .
char [ ] digits = new char [ n ] ; for ( int i = 0 ; i < n ; i++ ) { if ( nums [ i ] ) { digits [ i ] = 1 ; } else if ( ! nums [ i ] ) { digits [ i ] = 0 ; } } for ( int k = 0 ; k < n ; k++ ) { System.out.print ( digits [ k ] ) ; }
How to create a char [ ] using data from a boolean array ?
Java
I was reading Effective Java , and came across a condition where Joshua Bloch recommends something like XYZComparator is stateless , it has no fields . hence all instances of the class are functionally equivalent . Thus it should be a singleton to save on unnecessary object creation.So is it always safe to create a sta...
class MyComparator extends Comparator < String > { private MyComparator ( ) { } private static final MyComparator INSTANCE = new MyComparator ( ) ; public int compare ( String s1 , String s2 ) { // Omitted } }
Functional Equivalence in Java
Java
I have a number of occurrences in a new code base where there are a sequence of method calls like , in consecutive lines . I would like to find / count the total number of such a sequence in my code where the name of object `` something '' could be different , but I want treated the same.I want to pull these out as a m...
object o = something.foo ( ) ; bar ( o ) ; something.foobar ( ) ;
Static code analyzers , detect code patterns
Java
I 'm trying to verify if all the elements in an array list are same or not . This is my code :
ArrayList < Integer > arr = new ArrayList < > ( Arrays.asList ( 2,2,4,2 ) ) ; for ( int z = 0 ; z < arr.size ( ) ; z++ ) { if ( ! arr.get ( z++ ) .equals ( arr.get ( z -- ) ) ) { System.out.println ( `` same '' ) ; } else { System.out.println ( `` differnt '' ) ; } }
How can I tell if the elements in an Array List are same or different ?
Java
Many classes in the javax.sql package use new String ( str ) constructor . For example : Or And many more : javax.sql.rowset.serial.SerialStruct.SerialStruct ( SQLData , Map > ) javax.sql.rowset.serial.SerialStruct.SerialStruct ( Struct , Map > ) javax.sql.rowset.RowSetMetaDataImpl.setCatalogName ( int , String ) javax...
public void setCatalogName ( int columnIndex , String catalogName ) throws SQLException { checkColRange ( columnIndex ) ; if ( catalogName ! = null ) colInfo [ columnIndex ] .catName = new String ( catalogName ) ; else colInfo [ columnIndex ] .catName = new String ( `` '' ) ; } public void setUsername ( String name ) {...
Why do classes in the javax.sql package use new String ( str ) ?
Java
For reasons I do n't even want to begin to get into.. I have a maven hierarchy that looks like the one below . In a nutshell , everything requires commonslang3 , except one ancient artifact that requires commonslang2 . We have no issues with compile or runtime , the dependencies work as expected . The challenge we are ...
MyWar -- MyModuleJar1 -- ... -- MyModuleJar2 -- LibA -- commonslang -- ... -- LibB -- commonslang3 -- ... -- LibC -- commonslang3 -- ... -- ...
`` Hide '' a maven artifact from the eclipse autocomplete
Java
I have a class which treats Strings as a collection . These are two methods from the class : Just the signature from the methods are relevant to my question.Now , Eclipse does issue a warning that the two methods have the same erasure . But it still allows me to create them , and they work as expected : Whenever I supp...
@ Overridepublic < B > IndexedSeq < B > map ( final Function1 < ? super Character , B > function ) { ... } public RichString map ( final Function1 < ? super Character , Character > function ) { ... } @ Overridepublic IndexedSeq map ( final Function1 < Object , Object > function ) { ... } public RichString map ( final F...
Two methods with the same signature , why it works
Java
I just started to learn java , so now i read about such possibility as inheritance , so try to create class that must create object - box . And using inheritance implement new properties to created object.I try to put each class in separate file , so after creating class , try to use it in So class Inheritance : But , ...
public static void main ( String [ ] args ) public class Inheritance { double width ; double height ; double depth ; Inheritance ( Inheritance object ) { width = object.width ; height = object.height ; depth = object.depth ; } Inheritance ( double w , double h , double d ) { width = w ; height = h ; depth = d ; } Inher...
Inheritance for beginners
Java
I am trying to get a sample program working with JUNG , a graphing tool in Java . I downloaded and referenced all the .jar files in eclipse so my project hierarchy looks like this : alt text http : //img638.imageshack.us/img638/6787/hierarchy.pngIn Test.java I have the following code : For some reason though when I try...
public class Test { static public void main ( ) { System.out.print ( `` Hello '' ) ; } }
Code jumps out of a jar and runs ? What is causing this ?
Java
This is our codeFor idType we 're expecting two values it can either be primary key id or its corresponding identificationType . Table only has two columns id and identificationType . The problem is that it throws ResourceNotFoundException even if op1 or op2 is not empty . Now if I change my return like thisIts again t...
private IdentificationMaster validateIdentificationType ( String idType ) { if ( ! StringUtils.isNotBlank ( idType ) ) throw new IllegalArgumentException ( `` Invalid idType '' ) ; Optional < IdentificationMaster > op1 = specRepo.findById ( idType ) ; //testing purpose Optional < IdentificationMaster > op2 = specRepo.f...
JPA findBy method always goes to orElseThrow
Java
This probably does n't even need asking , but I want to make sure I 'm right on this . When you create an array of any object in Java like so : The variable objArr is located in stack memory , and it points to a location in the heap where the array object is located . The size of that array in the heap is equal to a 12...
Object [ ] objArr = new Object [ 10 ] ;
What is the memoy size of a Java object array after it has been created ?
Java
The result is : In binary format : Why casting infinity to int and long integers keeps sign bit as `` 0 '' , while sets sign bit to `` 1 '' for byte and short integers ?
System.out.println ( ( byte ) ( 1.0/0 ) ) ; System.out.println ( ( short ) ( 1.0/0 ) ) ; System.out.println ( ( int ) ( 1.0/0 ) ) ; System.out.println ( ( long ) ( 1.0/0 ) ) ; -1 -1 2147483647 9223372036854775807 1111 1111 1111 1111 1111 1111 0111 1111 1111 1111 1111 1111 1111 1111 0111 1111 1111 1111 1111 1111 1111 11...
Why casting division by zero to integer primitives gives different results ?
Java
Consider the following Exception printSince Java is a compiled language and what runs in JVM is the bytecode and not the source code itself how does the exception know on which line it occurred ? Example line 332 in above case ?
java.util.NoSuchElementException at java.util.StringTokenizer.nextToken ( StringTokenizer.java:332 ) at com.infoaxe.mr.homefeed.ReduceTwo.reduce ( MapReduce.java:290 )
How does JRE know the line number of code where exception occured ?
Java
I was doing some performance testing regarding object allocation , when I came across a weird result . I have the following java code : Expectation : First call will be slower then second call , due to requesting a larger memory space from the operating system and hotspot enhancements . But second and third will be nea...
public static long TestMethod ( ) { int len = 10000000 ; Object [ ] obs = new Object [ len ] ; long t = System.nanoTime ( ) ; for ( int i = 0 ; i < len ; i++ ) { obs [ i ] = new Object ( ) ; } return System.nanoTime ( ) - t ; } public static void main ( String ... args ) throws InterruptedException { for ( int i = 0 ; ...
Java : What causes the performance increase when repeatedly calling a function ?
Java
I 'm confused by checked exception of javaChecked Exception requires to be handled at compile time using try , catch and finally keywords or else compiler will flag errorRead more : http : //javarevisited.blogspot.com/2013/06/10-java-exception-and-error-interview-questions-answers-programming.html # ixzz3pk6OBSrjMy pro...
try { callingMethod ( ) ; } catch ( Exception ) { }
Checked Exception requires to be handled at compile time using try , catch and finally keywords or else compiler will flag error
Java
I 'm having trouble casting a List of Fruit down to the Fruit subclass contained in the List . How do I cast oranges so that it is a List of class Orange ? Is this a bad design pattern ? Basically I am getting a JSON Response from a server that is a List of Fruit . For each specific call to the Web Service , I know wha...
public class Response { private List < Fruit > mFruitList ; public List < Fruit > getFruitList ( ) { return mFruitList ; } } public class Fruit { } public class Orange extends Fruit { } List < Fruit > oranges = response.getFruitList ( ) ;
Inheritance and casting for List Objects
Java
Is there any difference between delaring an array likeand declaring it like ? Both are valid in Java but I havent found any differences ( initialization or something ? ) or is it just two different ways to describe the same thing for the compiler ?
int [ ] array = new int [ 10 ] ; int array [ ] = new int [ 10 ] ;
Difference between type [ ] varName and type varName [ ] ?
Java
I am confused . If I calculate Then I get a result of 0.9999999999999999 . But if I calculateThen I get a result of 1.0 . Why is there a difference ?
System.out.println ( 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 ) ; Double sum = DoubleStream.builder ( ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .add ( 0.1 ) .build ( ) .sum ( ) ; System.out.println ( sum ) ;
Why does DoubleStream.sum ( ) 's result differ from straight addition ?
Java
Is it possible to define a generic bound that : implements an interface SomeInterfaceis a superclass of some class MyClassSomething like :
Collection < ? extends SomeInterface & super MyClass > c ; // does n't compile
Can you define a generic bound that both has lower and upper bounds ?
Java
The method signature of ObjectOutputStream 's write method is As obj should implements Serializable ( know about markers ) . Why java developers do not write this method as is there any reason ?
public final void writeObject ( Object obj ) throws IOException public final void writeObject ( Serializable obj ) throws IOException
Java Serialization , writeObject ( Object obj ) why not writeObject ( Serializable obj )
Java
Problem & Question : I currently have a view pager , with just 2 pages/views inside it , which are next to each other horizontally.My views are custom ones which draw a two-color gradient and an image over the top of it at a low opacity/alpha value.I 'm finding that when I swipe across the screen to move from the first...
@ Overrideprotected void onDraw ( Canvas canvas ) { p.setShader ( new LinearGradient ( 0 , 0 , 0 , getHeight ( ) , startColor , endColor , Shader.TileMode.MIRROR ) ) ; canvas.drawPaint ( p ) ; //Pretty sure the mistake is around these two next lines overlayImage.setBounds ( canvas.getClipBounds ( ) ) ; overlayImage.dra...
Drawable in View getting squashed
Java
In which scenario can an interface have nested classes ? The following code is allowed and valid.I am also struggling to make object of class ifaceClass . EDIT : I am able to make object like thisI noticed if Test has not implemented the Iface then I needed following import , But it boiled down to same problem that why...
public interface Iface { void show ( ) ; class ifaceClass { int x ; public ifaceClass ( ) { System.out.println ( x ) ; } } } public class Test implements Iface { public static void main ( String [ ] args ) { ifaceClass ifaceClassObj = new ifaceClass ( ) ; } public void show ( ) { } } import com.jls.Iface.ifaceClass ;
Where it is useful to have nested classes in an interface ?