lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I have a Reactive Springboot application using Spring WebFlux . I 'm trying to connect to my /var/run/docker.sock Unix Domain Socket to query some information.From my terminal , I am able to fetch all running containers using the following command.I am following the Project Reactor guide , found here to create an HttpC... | curl -- unix-socket /var/run/docker.sock http : /v1.40/containers/json return client.get ( ) .uri ( `` /containers/json '' ) .responseContent ( ) .asString ( ) .collectList ( ) .flatMapMany ( new Function < List < String > , Publisher < ? extends Container > > ( ) { @ Override public Publisher < ? extends Container > a... | How to connect to docker.sock using Netty ? |
Java | Why is in the first case SomeClass only instantiated once , but in the second case n-times , where n is the number of elements in the stream ? The method `` method '' in this case return the object itself ( = return this ) .So in the first case the list contains only one object , but n-times . In the second case the li... | List < SomeClass > list = stream.map ( new SomeClass ( ) : :method ) .collect ( Collectors.toList ( ) ) ; List < SomeClass > list = stream.map ( a - > { return new SomeClass ( ) .method ( a ) ; } ) .collect ( Collectors.toList ( ) ) ; Arrays.asList ( true , false , true , false ) .stream ( ) .map ( new SomeClass ( ) : ... | Difference between normal instantiation and instantiation including method reference |
Java | I 'm attempting a simple regex execution . Essentially I want to determine if I 've got special characters in my string and if so check each character of the string for two specific characters i.e . hypen and dot.I seem to be having a problem in the first bit which involves determining if I 've got special characters i... | public static boolean stringValidity ( String input ) { int specials = 0 ; Pattern p = Pattern.compile ( `` [ ^a-zA-Z0-9 ] '' ) ; Matcher m = p.matcher ( input ) ; boolean b = m.find ( ) ; if ( b ) { System.out.println ( `` \nstringValidity - There is a special character in my string '' ) ; for ( int i = 0 ; i < input.... | Regex test failing - Java |
Java | I have the following function that itterates over an array , calls a method on each 'Refund ' object that returns a BigDecimal that contains some value e.g . 20.45 : The problem is that it always returns ' 0.00 ' . I know for a fact that the array that I 'm passing is not null , and the values that their 'getAmountPaya... | private String getTransactionTotals ( Refund [ ] refunds ) { BigDecimal total = new BigDecimal ( 0.00 ) ; /* * Itterates over all the refund objects and adds * their amount payables together to get a total */ for ( Refund refund : refunds ) { total.add ( refund.getAmountPayable ( ) ) ; } total = total.setScale ( 2 , Ro... | How to add to a BigDecimal |
Java | I 've been struggling reading the javadocs to determine how to use lambdas to elegantly combine a list of rows of one type into a grouped-up list of another type.I 've figured out how to use the Collectors.groupingBy syntax to get the data into a Map < String , List < String > > but since the results will be used in a ... | class RowData { private String id ; private String name ; public RowData ( ) { } public RowData ( String id , String name ) { this.id = id ; this.name = name ; } public String getId ( ) { return id ; } public void setId ( String id ) { this.id = id ; } public String getName ( ) { return name ; } public void setName ( S... | How to use Java lambdas to collect elements in a list of a new type ? |
Java | One can load a class dynamically using this method of java.lang.Class : According to the JavaDoc , the second parameter is used to control the timing of class initialization ( execution of static initialization code ) . If true , the class is initialized after loading and during the execution of this method ; if false ... | public static Class < ? > forName ( String name , boolean initialize , ClassLoader loader ) | When should classes be initialised - at load time or at first use ? |
Java | I 'm trying to understand this regex , can you help me out ? I do n't really understand the meaning of DOTALL : ( ? s ) why the double \\ before } ? what does this exactly mean : ( .+ ? ) ( should we read this like : the . , then + acting on the . , then ? responding to the result of .+ ? | ( ? s ) \\ { \\ { wotd\\| ( .+ ? ) \\| ( .+ ? ) \\| ( [ ^ # \\| ] + ) . * ? \\ } \\ } | regex that i do n't understand |
Java | I am counting votes for electronic election and I have only one party in my initial version . There will be different threads per voter and the threads will update the votes count of a given party.I decided to use ConcurrentHashMap , but the results are not what I expected ... The result is different every time - it ra... | Map < String , Integer > voting = new ConcurrentHashMap < > ( ) ; for ( int i = 0 ; i < 16 ; i++ ) { new Thread ( ( ) - > { voting.put ( `` GERB '' , voting.getOrDefault ( `` GERB '' , 0 ) + 1 ) ; } ) .start ( ) ; } for ( int i = 0 ; i < 100 ; i++ ) { voting.put ( `` GERB '' , voting.getOrDefault ( `` GERB '' , 0 ) + 1... | ConcurrentHashMap does not work as expected |
Java | The answer to this question explains the cause for the ambiguous constructor problem , but if I actually want to construct a third-party object which contains such constructors , and I want to pass the argument to be null , can I construct the object anyways by somehow telling java which constructor I mean ? In particu... | public Example ( String name ) { this.name = name ; } public Example ( SomeOther other ) { this.other = other ; } | Is there a way to explicitly specify a constructor in Java ? |
Java | Consider the following : Notice that java.lang.Class does not implement the hashCode ( ) method itself , but inherits it from java.lang.Object implicitly . I verified this in JDK 1.8.Is java.lang.Class safe to use as a key for a java.util.HashMap ? Will myMap.get ( Foo.class ) always return the values which I put like ... | Map < Class < ? > , Object > myMap = new HashMap < Class < ? > , Object > ( ) ; Foo fooObject = New Foo ( ) ; myMap.put ( fooObject.getClass ( ) , fooObject ) | Will the use of Class as key for a HashMap cause undesireable effects ? |
Java | Why does the following code compile cleanly without any warnings , even with xlint : all ? running : results in a clean compile without any warnings ( unchecked , etc. ) . What is the type parametrization of the instance of the generic class A that gets 's created on the first line and what on the second ? And how does... | class A < V > { public V v ; public < V > A ( ) { } public static < V > A < V > create ( ) { return new A < V > ( ) ; } } public class FooMain { public static void main ( String args [ ] ) { A.create ( ) .v = 5 ; A.create ( ) .v = `` a string '' ; } } javac -Xlint : all src/FooMain.java | why does this compile without any unchecked type warnings ? |
Java | I have two models , a List < ModelA > and I want to convert it to a List < ModelB > . Here are my models : Actual solution : But I think there is a simpler solution , do you have any idea how can I do it in a single stream , or simplify it somehow ? EDIT : I want to clarify that I can not use java9 and I need to group ... | class ModelA { private Long id ; private String name ; private Integer value ; public ModelA ( Long id , String name , Integer value ) { this.id = id ; this.name = name ; this.value = value ; } public Long getId ( ) { return id ; } public String getName ( ) { return name ; } public Integer getValue ( ) { return value ;... | Java-8 : stream or simpler solution ? |
Java | Example : I have some source code , FooBar.javathat gives me FooBar.class.Why does the JVM command line API take FooBar instead of FooBar.class ( working on UNIX FYI ) ? | javac FooBar.java | Why do you remove .class when executing on the JVM ? |
Java | One of my ES nodes has failed because of java.lang.OutOfMemoryError : Java heap space error . Here is the full stack trace from the logs : Because of the exception above , I am getting master_not_discovered_exception when I am hitting any of ES APIs.Question : Can anyone tell me the next steps that I should perform to ... | [ 2020-09-18T04:25:04,215 ] [ WARN ] [ o.e.a.b.TransportShardBulkAction ] [ search1 ] [ [ my_index_4 ] [ 0 ] ] failed to perform indices : data/write/bulk [ s ] on replica [ my_index_4 ] [ 0 ] , node [ cm_76wfGRFm9nbPR1mJxTQ ] , [ R ] , s [ STARTED ] , a [ id=BUpviwHxQK2qC3GrELC2Hw ] org.elasticsearch.transport.NodeDis... | Elasticsearch : restart node after java.lang.OutOfMemoryError : Java heap space |
Java | Please compare two ways of setting/returning an array : Both generate distinct bytecodes and both can be decompiled to their former state . After checking the execution times via profiler ( 100M iterations , unbiased , different environs ) , the time of _1 method is approx . 4/3 the time of _2 , even though both create... | static public float [ ] test_arr_speeds_1 ( int a ) { return new float [ ] { a , a + 1 , a + 2 , a + 3 , a + 4 , a + 5 , a + 6 , a + 7 , a + 8 , a + 9 } ; } // or e.g . field = new float ... in methodstatic public float [ ] test_arr_speeds_2 ( int a ) { float [ ] ret = new float [ 10 ] ; ret [ 0 ] = a ; ret [ 1 ] = a +... | preferred way of setting/returning arrays |
Java | I was experimenting with a Java port of some C # code and I was surprised to see that javac 1.8.0_60 was emitting a getfield opcode each time that an object field was accessed.Here is the Java code : As reported by javap , javac 1.8.0_60 produces the following bytecode : Note that a getfield opcode was emitted by the c... | public class BigInteger { private int [ ] bits ; private int sign ; // ... public byte [ ] ToByteArray ( ) { if ( sign == 0 ) { return new byte [ ] { 0 } ; } byte highByte ; int nonZeroDwordIndex = 0 ; int highDword ; if ( bits == null ) { highByte = ( byte ) ( ( sign < 0 ) ? 0xff : 0x00 ) ; highDword = sign ; } else i... | Would it be legal for a Java compiler to omit getfield opcodes after the first access ? |
Java | I am relatively new to Android/Java . Thanks to Stack Overflow , I was able to learn a lot from the questions asked here . However , I am now stuck on this problem.I have a password input AlertDialog that pops up when we start the app . It reads the password from the EditText and compare this with the one stored in a f... | LayoutInflater li = LayoutInflater.from ( context ) ; View passView = li.inflate ( R.layout.authdialog , null ) ; AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder ( context ) ; // set prompts.xml to alertdialog builderalertDialogBuilder.setView ( passView ) ; final EditText passInput = ( EditText ) pass... | Showing multiple AlertDialogs |
Java | I 've been doing some code archeology in some odd code and I came across something similar to this : The thing that struck me was that there was n't an unbounded wildcard type on Inner 's usage of the Outer type ( the < U extends Outer > bit ) .What is the implication of using Inner < U extends Outer < ? > > vs. Inner ... | public abstract class Outer < T > { protected Outer ( Inner < ? > inner ) { // ... } public static abstract class Inner < U extends Outer > { // ... } } | Understanding Raw vs Unbounded Wildcard in Static Nested Class Type Definition |
Java | I am trying to move an object to the end of the list if it has a boolean flag set to true . The following works where I am taking the route of deleting it and adding it back . Is there a better more elegant way to do this in Java 8 ? I have to work with that boolean flag to identify if object needs to go to end of list... | public class Main { public static void main ( String [ ] args ) { Item item1 = new Item ( ) ; item1.setName ( `` item1 '' ) ; Item item2 = new Item ( ) ; item2.setName ( `` item2 '' ) ; item2.setMoveToLast ( true ) ; Item item3 = new Item ( ) ; item3.setName ( `` item3 '' ) ; Item item4 = new Item ( ) ; item4.setName (... | Elegant way to move Object to end of list |
Java | I need to convert following : to where keys of outer map ( mapOfMaps ) are redundant ( for this operation ) . So basically , I can just use mapOfMaps.values ( ) .stream ( ) to start with.And for each map object e.g . : { `` apple '' : '' 1 '' , '' orange '' : '' 2 '' } I need to convert it to a list : { `` apple '' , '... | Map < Long , Map < String , String > > mapOfMaps List < List < String > > listOflists | Most efficient way to convert/flatten entire map to list ( keys & values together , not separately ) |
Java | Here I have two arrays of integer ( primitve , Wrapper ) type but I have got different result forinstanceof operator see the line number 2 and 4 line no 4 will compile successfully and give result true but in case of line 2 , why does it result in a compilation error ? From line 1 and 3 it is clear that the two arrays ... | int primitivI [ ] = { 1,1,1 } ; Integer wrapperI [ ] = { 2,22,2 } ; 1 . System.out.println ( primitivI instanceof Object ) ; //true2 . System.out.println ( primitivI instanceof Object [ ] ) ; //Compilation Error Why ? ? ? ? 3 . System.out.println ( wrapperI instanceof Object ) ; //true4 . System.out.println ( wrapperI ... | instanceof operator in case of primitive and wrapper type array |
Java | I am using QAF for my automation project . I have project specific meta-data which has group SMOKE , regression , P1 and author with x , y , z name.I want to run only `` smoke '' group and author with `` x '' or `` y '' . Is there any solution for these ? | SCENARIO : SampleTestMETA-DATA : { `` description '' : '' Sample Test Scenario '' , '' groups '' : [ `` SMOKE '' ] , '' author '' : [ `` x '' ] } # TODO : call test stepsEND | How can I filter testcases using custom meta-data in QAF ? |
Java | My whole rest service stops working when I 'm adding this code : It does n't really say why either , all I 'm getting is : And a bunch of errors saying `` caused by previous errors `` I must have done something really wrong here , are there any proffessional JPA enthusiasts that can help me out a little bit here ? Edit... | @ PUT @ Path ( `` upload/ { id } '' ) @ Consumes ( MediaType.MULTIPART_FORM_DATA ) public void addBlob ( @ PathParam ( `` id '' ) Integer id , @ FormDataParam ( `` file '' ) InputStream uploadedInputStream ) throws IOException { TheTempClient entityToMerge = find ( id ) ; try { ByteArrayOutputStream out = new ByteArray... | JPA rest stops working when trying to upload blob |
Java | File name : B.javajava B.java runs without errorjavac B.java gives a compile error : class A needs to be declared in a file A.javaI understand that a java file can not have more than one public class , but why can a java file run without error using the java command when you get compile errors for the code using javac ... | public class B { public static void main ( String [ ] args ) { } } public class A { } | Java File runs with java FileName.java command but does n't compile with javac Filename.java |
Java | If there are two methods like add ( int , long ) and add ( long , int ) , such call add ( 10,10 ) would be considered as ambiguity.But what if we have such example , why is it still considered as ambiguity ? ? I want to know how the compiler decided that it is ambiguity ? while ( in my mind ) it should n't because add ... | static void add ( short num1 , short num2 ) { System.out.println ( `` add ( short , short ) '' ) ; } static void add ( byte num1 , long num2 ) { System.out.println ( `` add ( byte , long ) '' ) ; } public static void main ( String [ ] args ) { byte num1 = 10 ; byte num2 = 10 ; add ( num1 , num2 ) ; } | Theoretical inquiry about overloading and type promotion in java |
Java | I 'm a bit confused . On the first iterations of fill loops I see some regression in filling time when using initial capacity for ArrayList vs without using initial capacity.According to the common sense and this question : Why start an ArrayList with an initial capacity ? it must be absolutely inversely.It is not well... | public class TestListGen { public static final int TEST = 100_000_000 ; public static void main ( String [ ] args ) { test ( false ) ; } private static void test ( boolean withInitCapacity ) { System.out.println ( `` Init with capacity ? `` + withInitCapacity ) ; for ( int i = 0 ; i < 5 ; i++ ) av += fillAndTest ( TEST... | Some regression when using initial capacity for ArrayList on the first iterations |
Java | I realized today that this compiles and runs fine : The two handle methods has the same name , and same number and type ( ? ) of parameters . The only difference is that the second handle method has a stricter generic bound . IDE does not complain at all , and the code compiles fine . At run time method is selected as ... | public class Test { public static < T > T handle ( T val ) { System.out.println ( `` T '' ) ; return val ; } public static < T extends String > T handle ( T val ) { System.out.println ( `` T extends String '' ) ; return val ; } } | Is generics bound part of method signature in Java ? |
Java | Out of curiosity I wrote Hello World and set a break point on my print statement.When the break point was hit , I pulled up Task Manager in windows to see how many threads were allocated by that JVM process . I was shocked to see 22 . Why are there so many threads spawned for this simple program ? | public class Program { public static void main ( String [ ] args ) { System.out.println ( `` Hello '' ) ; } } | Why does my single threaded hello world app use 22 OS threads ? |
Java | I have created a method to create a 128 bit UUID string , I now want to check if this is a prime number or not . I cant put the string into an int because it is too big . Can anyone suggest how I would go about checking ? This is the code I have used for creating the UUID | public static String uuid ( ) { UUID uuid = UUID.randomUUID ( ) ; long hi = uuid.getMostSignificantBits ( ) ; long lo = uuid.getLeastSignificantBits ( ) ; byte [ ] bytes = ByteBuffer.allocate ( 16 ) .putLong ( hi ) .putLong ( lo ) .array ( ) ; BigInteger big = new BigInteger ( bytes ) ; String numericUuid = big.toStrin... | Checking if UUID String is Prime |
Java | I am trying to sort an array in ascending order and I came across a problem . The code sorts the array but it takes the last number and places it in the first position of the array . So for example when ordering 2,3,4,1 the output is 4 , 1 , 2 , 3 . How do I take the number 4 and move it behind the number 3 ? Output : | public class Main { public static void main ( String [ ] args ) { int [ ] numbers = { 2 , 3 , 1 , 4 } ; int holder = 0 ; for ( int i = 0 ; i < numbers.length ; i++ ) { for ( int j = 1 ; j < numbers.length ; j++ ) { if ( numbers [ i ] < numbers [ j ] ) { holder = numbers [ i ] ; numbers [ i ] = numbers [ j ] ; numbers [... | Array sort leaves one element in the wrong position |
Java | My goal is to generate a pseudorandom String consisting of 500000 characters out of a small selection of characters . This is my loop for adding characters to the String : Unsurprisingly this is very slow , so I am looking for ways to get this to perform the > least slow < possible . | String alphabet= '' ABCD '' ; Random r = new Random ( ) ; for ( int i = 0 ; i < 500000 ; i++ ) { this.setCode ( ( this.getCode ( ) == null ? `` '' : this.getCode ( ) ) alphabet.charAt ( r.nextInt ( alphabet.length ( ) ) ) ) ; } | How can I optimize my code for generating a pseudorandom String for high speed in Java ? |
Java | I have the following entity : I want to get some entities with additional column from the database.To do this I created a simple Pair class.Then I prepared a query in JPQL that creates the expected result.The query returns correct results , but there is a problem with additional queries.Therefore , I have some question... | @ Getter @ Setter @ AllArgsConstructor @ NoArgsConstructor @ Entity @ Table ( name = `` simple_entity '' ) public class SimpleEntity { @ Id private Long id ; @ Column ( name = `` text '' ) private String text ; } @ Getter @ Setter @ AllArgsConstructorpublic class Pair < First , Second > { private First first ; private ... | Why does placing an entity in the POJO class using `` select new '' in JPA cause an N + 1 problem ? |
Java | Is this code bad practice as the method show ( ) is deprecated ? Is it okay to override here ? | public class Window extends JFrame { public Window ( ) { // Do things . } public void show ( ) { // < - Comes up with a warning as deprecated code . // Do other things . } } | Is it bad practice to override a deprecated method ? |
Java | Let us have a stream of objects , resulting from a sequence of operations ( e.g . mapping , filtering , flatmapping , etc. ) . Now I want to do a certain operation on them , but only if a given predicate is true . Otherwise I want to immediately return something else.A simple example . I have a stream of different food... | source.stream ( ) // some operations .ifAny ( food - > ! food.isEdible ( ) , new LinkedList < Food > ( ) ) // other operations if previous step not failed .peek ( food - > food.prepare ( ) ) .collect ( Collectors.toList ( ) ) ; | Is it possible to define an optional flow or exception-like behaviour in Java 8 streams API ? |
Java | I remember a couple years ago I was using static initializers to call class-level setup operations . I remember it having very bizarre behaviors and I just decided to steer clear from them . Maybe it was because I was messing up the top-bottom order or being a newbie . But I am encountering a need to revisit them and I... | public class StratBand { private static volatile ImmutableList < StratBand > stratBands = importFromDb ( ) ; private final int minRange ; private final int maxRange ; private static ImmutableList < StratBand > importFromDb ( ) { //construct list from database here } //constructors , methods , etc } public class StratBa... | Legitimate uses for static initializer ? |
Java | In Java8 , what is the type of the following lambda ? ? ? That is a function that takes no arguments and returns nothing.Stated differently : What should I replace the question marks with ? In Scala , this would be a Function0 [ Unit ] I think , but I do n't find anything alike in Java . | ( ) - > { } public class A { static void a ( ) { } static void main ( String [ ] args ) { ? ? ? ? a = A : :a } } | What is the type of ' ( ) - > { } ' in Java 8 ? |
Java | I 've encountered an `` unrecoverable stack overflow error '' that I ca n't figure out . From the docs : you need to create an interface object ( of any class ) and make it known to JavaScript by calling JSObject.setMember ( ) .Here 's the Java code sharing and using the interface object : And here 's the JavaScript co... | // somewhere in the codeJSObject window = ( JSObject ) engine.executeScript ( `` window '' ) ; window.setMember ( `` foo '' , new Foo ( ) ) ; // < -- shareswindow.call ( `` testFoo '' ) ; // < -- uses// somewhere elseclass Foo { public void bar ( ) { System.out.println ( `` baz '' ) ; } } window.testFoo = function ( ) ... | Unrecoverable stackoverflow error when making upcalls from JavaScript to Java |
Java | I have three Integer variables , where I am not allowed to change to primitive int and I need to check if at least one of them have a value greater than 0 . Is there a shorter / cleaner way to rewrite my code below : | Integer foo = // null or some valueInteger bar = // null or some valueInteger baz = // null or some valueboolean atLeastOnePositive = ( foo ! = null & & foo > 0 ) || ( bar ! = null & & bar > 0 ) || ( baz ! = null & & baz > 0 ) return atLeastOnePositive ; | Shorter way to check for not null for multiple variables |
Java | I have a list of roles in a database . They are of the formSo each role has an entry based on read/write permission.I want to convert the roles into a POJO which I can then send as JSON to a UI . Each POJO would have the role name , and a boolean for read or write permission.Here is the RolePermission class : I am doin... | application.Role1.readapplication.Role1.writeapplication.Role2.readapplication.Role3.read import com.fasterxml.jackson.annotation.JsonInclude ; @ JsonInclude ( JsonInclude.Include.NON_NULL ) public class RolePermission { private String roleName ; private boolean readAllowed ; private boolean writeAllowed ; public Strin... | How to convert a list of strings into a list of objects ? |
Java | I have come across below strange syntax , I have never seen such snippet , it is not necessity but curious to understand itAbove code gives output as strangethanks | new Object ( ) { void hi ( String in ) { System.out.println ( in ) ; } } .hi ( `` strange '' ) ; | Java strange syntax - ( Anonymous sub-class ) |
Java | I wrote my own Stack class ( for the relevant code , see below ) . In the next ( ) -method I am forced to cast current.item to Item , but I do not know why . The type of current.item should already be Item and thus casting should not be necessary - but if I do not cast it , I get an error . | public class Stack < Item > implements Iterable < Item > { private class Node { Item item ; Node next ; } private Node first= null ; public Iterator < Item > iterator ( ) { return new StackIterator ( ) ; } private class StackIterator < Item > implements Iterator < Item > { private Node current = first ; public Item nex... | Cast is forced when using generics in Java |
Java | In this code , T can be A , B , C , or D , but Eclipse shows that it is D.Is there any rule for how type inference is done and why it selects D ? | static class A { } static class B extends A { } static class C extends B { } static class D extends C { } static < T > void copy ( List < ? super T > dst , List < ? extends T > src ) { for ( T t : src ) dst.add ( t ) ; } public static void main ( String [ ] args ) { List < A > dst = new ArrayList < > ( ) ; List < D > s... | How does Java handle ambiguous type inference for generics ? |
Java | I 'm trying to add specific values to a map in Java , where the key is quite complex , but the value is a simple Double.Currently I 'm using , where foos is an instance of java.util.TreeMap < Foo , Double > , and amount is a Double , code like : but this looks quite dirty in that I have to reinsert the element , and I ... | for ( java.util.Map.Entry < Foo , Double > entry : foos.entrySet ( ) ) { foos.put ( entry.getKey ( ) , entry.getValue ( ) + amount ) ; } | Adding a value to terms in a Map |
Java | Can anyone explain why there is an untyped conversion warning on y assignment line ? Note that there is no warning on either x or z assignments . | public class Entity < T > { @ SuppressWarnings ( `` unchecked '' ) public < TX > Entity < TX > typed ( Class < TX > type ) { return ( Entity < TX > ) this ; } @ SuppressWarnings ( `` unchecked '' ) public static < TX > Entity < TX > typed ( Entity < ? > entity , Class < TX > type ) { return ( Entity < TX > ) entity ; }... | Unexpected unchecked conversion warning |
Java | The specific use where I thought of this problem is as follows , but it 's much more generalized.I have a custom JFrame class which also serves as an ActionListener for its components . So my constructor looks something like the following : My question is , how does this actually work behind the scenes ? If the constru... | private JButton myButton ; public MyCustomFrame ( ) { super ( ) ; myButton.addActionListener ( this ) ; // ... more stuff } | How can `` this '' be referenced/processed before the constructor has concluded ? |
Java | So I have a javadoc that looks like this ( censored for the public of course ) : So the reason for this is that doing */ in my example will end the javadoc . Having the braces confuses the @ code tag.The problem is that the generated javadoc shows the HTML entities codes instead of the actual character that I want to d... | /** * Description of my method * < p > * < b > Example : < /b > * < /p > * < pre > * { @ code * /** * * Sample Javadoc * * & # 47 ; * public final void testMyMethod ( ) * & # 123 ; * // some logic * & # 125 ; } * < /pre > * @ return Description of my return value . */ | How do I write a block comment in my javadoc example ? |
Java | Sir i am trying to print array 's 0th element but i can't.Here is my code when i am trying to print arr [ 0 ] its return blank but when i print arr [ 1 ] it returns the 0th element value . would you please help me to find my error . | import java.util.Scanner ; public class prog3 { public static void main ( String [ ] args ) { Scanner input = new Scanner ( System.in ) ; int size = input.nextInt ( ) ; String arr [ ] = new String [ size ] ; for ( int i=0 ; i < size ; i++ ) { arr [ i ] = input.nextLine ( ) ; } System.out.print ( arr [ 0 ] ) ; } } | Unable to print array 0th element |
Java | Hello I am trying to understand the code I have written and why does it print the output belowprints meASSUME THAT the given matrix is not symmetric here . How can I modify this code to give me back saying if the matrix is symmetric or not only once . | public void isSymmetricNow ( int [ ] [ ] matrix ) { for ( int i = 0 ; i < matrix.length ; i++ ) { for ( int j = 0 ; j < matrix.length ; j++ ) { if ( matrix [ i ] [ j ] ! = matrix [ j ] [ i ] ) { System.out.print ( `` matrix is not symmetric \n '' ) ; } } } System.out.print ( `` matrix is symmetric \n '' ) ; } matrix is... | Void method printing two times |
Java | I 've got a problem , I 'm getting a `` Dead Code '' warning in Eclipse and I really do n't know why . The code is from my Connect Four project , to be more precise it 's from the Class that checks if somebody has won . This method checks all the horizontal winning possibilities for red . The code is the following : Th... | /** * Method to check the horizontal winning possibilities for red * @ return true if red won or false if not */public boolean checkHorRed ( ) { for ( int line = 0 ; line < 6 ; line++ ) { for ( int column = 0 ; column < 4 ; column++ ) { //column++ is underlined and causes the `` dead Code '' warning if ( gw.buttons [ l... | Where does the dead code come from ? |
Java | I 'm writing a test class for my GiftSelector class using JUnit in BlueJ . When I run the testGetCountForAllPresents ( ) method , I get a NullPointerException on the line : The strange thing about this NPE , is that it rarely appears when I run the test once , but often appears the second time I run the test . It somet... | assertEquals ( true , santasSelector.getCountsForAllPresents ( ) .get ( banana ) == 3 ) ; import static org.junit.Assert . * ; import org.junit.After ; import org.junit.Before ; import org.junit.Test ; /** * The test class GiftSelectorTest . The GiftSelector that you are * testing must have testMode enabled for this cl... | Why Am I Getting An NPE That Only Appears Occasionally When The Program is Run ? |
Java | I 'm a newbie to Android and Java so please be nice : ) I have an EditText in my application which is used to search for a particular string in a String [ ] My code works well , but not as I want : This code produces these results : if I search for `` table is '' = > allProd_sort will be [ the table is brown ] but if I... | ArrayList < String > allProd = new ArrayList < String > ; ArrayList < String > allProd_sort = new ArrayList < String > ; allProd = [ the table is brown , the cat is red , the dog is white ] ; String [ ] allProdString = allProd.toArray ( new String [ allProd.size ( ) ] ) ; ... //inputSearch is the EditText inputSearch.a... | Improve search in array |
Java | I tried this : But I get an `` incompatible types '' error : As far as I know all enums inherit from Enum . Why is my enum incompatible to Enum ? | public static enum Types { A , B , C } Class < Enum > e = Types.class ; found : java.lang.Class < id.Types > required : java.lang.Class < java.lang.Enum > Class < Enum > e = Types.class ; | How to declare a variable which can contain only enum classes ? |
Java | Suppose you have a class that is frequently ( or even exclusively ) used as part of a linked list . Is it an anti-pattern to place the linkage information within the object ? For example : An often-cited recommendation is to simply use a generic container class ( such as java.util.LinkedList in Java ) , but this create... | public class Item { private Item prev ; private Item next ; ... } | Is linkage within an object considered an anti-pattern ? |
Java | I 've come across an interesting bit of Java code that IntelliJ flags as an error , but which javac accepts as legal . Either IntelliJ is wrong , and the code is legal , or the compiler is `` wrong '' , whether due to a bug or an intentional relaxation of rules.I like to think I understand the Java type system pretty w... | interface A < T > { } interface X extends A < String > { } interface Y extends A < Object > { } interface Z extends X , Y { } // COMPILE ERROR interface X < T > extends A < String > { } interface Y < T > extends A < Object > { } interface Z extends X , Y { } // OK according to javac , ERROR according to IntelliJ | Inheriting raw types w/ conflicting generic super-interfaces |
Java | I 'm wondering whether it 's a good practice to produce the code which being used like this : Here , TemplateProcessor contains only one public method . It seems the code above can be expressed with a static method , but I would like to avoid that . The reason is simple : object may contain encapsulated state , ( maybe... | new TemplateProcessor ( inputStream ) .processTemplate ( `` output-path.xhtml '' ) ; | Is this appropriate to create a class with one method ? |
Java | I am working on a business logic where I need to divide and multiply BigDecimal variable to produce business result but I am facing the problem to maintain the accuracy . Actual business I ca n't put here so I created a sample program and included here . I need to use only BigDecimal so I am strict to it but I am open ... | public class Test { public static void main ( String [ ] args ) { BigDecimal hoursInADay = new BigDecimal ( `` 24 '' ) ; BigDecimal fraction = BigDecimal.ONE.divide ( hoursInADay , 3 , RoundingMode.HALF_UP ) ; BigDecimal count = BigDecimal.ZERO ; for ( int i = 1 ; i < = 24 ; i++ ) { count = count.add ( fraction ) ; } i... | Maintain Accuracy Level Maximum |
Java | According to information from official site I added latest depedency and started to develop.First I created model with data I 'm interested : second step was to add service : Third one was to add implementation : But there is an error : Here is full error log trace | public class Data { String parametr1 ; //geters and setters ommited } public interface GitHubService { @ GET ( `` /repos/ { owner } / { repo } '' ) Call < Data > repoInfos ( @ Path ( `` user '' ) String owner , @ Path ( `` repo '' ) String repo ) ; Retrofit retrofit = new Retrofit.Builder ( ) .baseUrl ( `` https : //ap... | Retrofit usage in with API in Java |
Java | I need to inherit android.support.v4.view.ViewPager and two constructors . In Java , it is done by : I have searched on Google and here for a while , and some people suggested to implement this in Scala like this : The above Scala code compiles , but it it seems that the apply method is not invoked correctly when Andro... | class MyViewPager extend android.support.v4.view.ViewPager { public ViewPager ( Context context ) { super ( context ) ; } public ViewPager ( Context context , AttributeSet attrs ) { super ( context , attrs ) ; } } import android.support.v4.view.ViewPagertrait ViewPagerTrait extends ViewPager { // ... implement ViewPage... | Call different Java parent constructor from Scala with Android |
Java | I am trying to save the groups in a string to an array so that I can use them in individual variables if I need to . For this I use split but for some reason I only get the full string in the first position in the array : ultimate_array [ 0 ] . If I want to use ultimate_array [ 1 ] I get an exception like `` out of bou... | String string_final = `` '' ; String [ ] ultimate_array = new String [ 100 ] ; String sNrFact = `` '' ; string_final= '' Nrfact # $ idfact1 # $ valfact1 # $ idfact2 # $ valfact2 # $ idfact3 # $ valfact3 # $ idfact4 # $ valfact4 # $ idfact5 # $ valfact5 # $ idfact6 # $ valfact6 # $ idfact7 # $ valfact7 # $ idfact8 # $ v... | split not working correctly |
Java | I have some code as follows : Specifically I want to take the values from the list and put them into the map . That all works perfectly . My concern though is with ordering.For example if the list has : How do I ensure that the final map contains : Instead ofThe incoming list is ordered , stream ( ) .filter ( ) should ... | Map < RiskFactor , RiskFactorChannelData > updateMap = updates.stream ( ) .filter ( this : :updatedValueIsNotNull ) . // Remove null updated values collect ( Collectors.toMap ( u - > u.getUpdatedValue ( ) .getKey ( ) , // then merge into a map of key- > value . Update : :getUpdatedValue , ( a , b ) - > b ) ) ; // If tw... | Using java streams to put the last encountered value into a map |
Java | I have code in my project that looks like this : Eclipse gives a warning for the cast in addBar that the cast is unsafe . However , am I correct in assuming that the cast will not throw given the restrictions that I have put on the type parameters , and therefore the cast is indeed safe ? | public interface Bar < T extends Foo < ? > > { // ... } public class MyFoo implements Foo < String > { private List < Bar < Foo < String > > barFoo = ... public < U extends Foo < String > > boolean addBar ( Bar < ? extends U > b ) { barFoo.add ( ( Bar < Foo < String > > ) b ) ; //safe cast ? } } | Is this cast in my generic method safe ? |
Java | Are the two statements equal in Java ? | //code 1Object o1 [ ] = new Class [ ] { iface } ; //code 2Object o2 [ ] = new Class < ? > [ ] { iface } ; | Is 'new Class [ ] { iface } ' and 'new Class < ? > [ ] { iface } ' the same in Java |
Java | I have a Set of some objects . I need to get the two min objects from the Set.My example is as follows : In my example I can get the min object from this Set based on the value attribute.So , I need to get the two min values using Java stream operations.The answers should be fast because in my real program I call this ... | import java.util . * ; import java.util.stream.Collectors ; import java.util.stream.Stream ; public class Example { public static void main ( String [ ] args ) { SomeObject obj1 = new SomeObject ( 1 ) ; SomeObject obj2 = new SomeObject ( 2 ) ; SomeObject obj3 = new SomeObject ( 3 ) ; Set < SomeObject > set = Stream.of ... | Get the two min objects from a set using Java stream |
Java | Here 's my sample class , that compiles ( and runs ) with version 1.6.0_14 of Java : I know that you 're supposed to only have one public class per file in Java , but is this more of a convention than a rule ? | import java.util.List ; import java.util.ArrayList ; public class Sample { List < InnerSample > iSamples ; public Sample ( ) { iSamples = new ArrayList < InnerSample > ( ) ; iSamples.add ( new InnerSample ( `` foo '' ) ) ; iSamples.add ( new InnerSample ( `` bar '' ) ) ; } public static void main ( String [ ] args ) { ... | Why is javac not complaining about more than one public class per file ? |
Java | please , I want to know the difference between writingandand how would that affect the code | public class Something < T extends Comparable < T > > { // } public class Something < T extends Comparable > { // } | Difference in java generics |
Java | I managed to use a spinner in my code and wanted to change the textColor of a certain text in the MainActivity file trough that spinner , but he is located in another class file - Einstellungen.Is it possible to change the textColor in the current activity from another activity ? This is the main_activity.xml where I w... | < TextView android : id= '' @ +id/speedtext '' android : layout_width= '' match_parent '' android : layout_height= '' wrap_content '' android : layout_marginTop= '' 180dp '' android : gravity= '' center '' android : singleLine= '' true '' android : text= '' TEXT '' android : textColor= '' @ android : color/white '' and... | Change android : textColor with a spinner |
Java | User sends me byte / short / int / long value . I have to send it as the part of POST HTTP request and I have to send number as String.So right now I do the next : I 'm looking for faster alternative for Because this flow creates char [ ] , String and byte [ ] objects . While I need only byte [ ] . I wonder if there is... | //simplified versionbyte [ ] data = Integer.toString ( myInt ) .getBytes ( US_ASCII ) ; sendPost ( data ) ; Integer.toString ( myInt ) .getBytes ( US_ASCII ) ; | Is there is a faster alternative for Integer.toString ( myInt ) .getBytes ( US_ASCII ) ? |
Java | In Java , we use Interface to hide the implementations from users . Interface contains only abstract methods and as abstract methods do not have a body we can not create an object without constructor . Something like thisMy question is why Java allows creating an array of object Interface and where someone might use it... | public interface ExampleInterface { } public class Example implements ExampleInterface { private static void main ( String [ ] args ) { // This is not possible ExampleInterface objI = new ExampleInterface ( ) ; // However this is ExampleInterface [ ] arrI = new ExampleInterface [ 10 ] ; } } | Array of Data Type Interface |
Java | I have a created a simple Login Webservice in Java and I am calling it from the Android code . I am passing two String Parameters to the Webservice . But they become null in the Webservice.The Web service is hosted on Localhost Tomcat serverThe WSDL file is : I am new to both Android and Creating Web Service . I tried ... | WebService Code : public boolean authenicateUser ( @ WebParam ( name= '' username '' ) String username , @ WebParam ( name= '' password '' ) String password ) { System.out.println ( `` Inside Authenticae USER+========== '' +name+ '' -- -- - '' +Password ) ; //This becomes null and null final String LOGIN_SQL= '' SELECT... | Error in Callin Java webservice from Android using k-Soap |
Java | I have a list of objects of class A defined as below : Now I would like to create a stream which contains elements of both sOne and stwo . Is there a way to do it in Java 8 ? | class A { private Set < String > sOne ; private Set < String > sTwo ; // Constructor , getters and setters } | Joining 2 streams from same object in java |
Java | I had recently a discussion about the use of non-counter related conditions in for-loops in Java : Does anyone know if there are any `` official '' conventions for for-conditions like this ? In my opinion it 's easier to read compared to an equivalent while-loop because all loop-parameters are together in the first lin... | for ( int i = 0 ; o.getC ( ) < 10 ; i++ ) o.addC ( i ) ; int i = 0 ; while ( o.getC ( ) < 10 ) { i++ ; o.addC ( i ) ; } int i = 0 ; while ( o.getC ( ) < 10 ) o.addC ( ++i ) ; | For-loop condition conventions |
Java | I get a ClassCastException error when I run this because of the implicit cast of d to a double when I run the code . However , if I change reference to d in to Object [ ] then it ca n't be a parameter to the set function . If I change the set function to accept an Object [ ] then everything works fine , but then the cl... | public class Foo < N > { public static void main ( String [ ] args ) { Foo < Double > foo = new Foo < Double > ( ) ; Double [ ] d = foo.get ( ) ; // do stuff to d ... foo.set ( d ) ; } N [ ] data ; public Foo ( ) { data = ( N [ ] ) new Object [ 2 ] ; } public N [ ] get ( ) { return ( N [ ] ) data ; } public void set ( ... | Returning an Array from a generic class |
Java | I have came across the piece of code : and we can use this to create an instance of HashMap , like this : Now the question is the method newHashMap is called without passing the required type ( in this case its ( String , List < String > ) , but still java is creating the correct type . How ? I 'm confused here , how K... | public static < K , V > HashMap < K , V > newHashMap ( ) { return new HashMap < K , V > ( ) ; } Map < String , List < String > > anagrams = newHashMap ( ) ; Map < String , List < String > > newHashMap ( ) ; | Generics type parameters getting bounded , without passing real type |
Java | QuestionWhy does Spring 's RestTemplate use an excessive amount of heap ( particularly the G1 Old Generation ) when sending a file.ContextWe observed the RestTemplate to consume excessive amounts of memory when sending files via POST requests . We used Spring 's WebClient as comparison and it behaves completely sane.We... | private void sendFileAsOctetStream ( File file ) { final RequestEntity < FileSystemResource > request = RequestEntity.post ( URI.create ( `` http : //localhost:8080/file '' ) ) .contentType ( MediaType.APPLICATION_OCTET_STREAM ) .body ( new FileSystemResource ( file ) ) ; restTemplate.exchange ( request , void.class ) ... | Why does RestTemplate consume excessive amounts of memory ? |
Java | How the JVM chooses which method to execute ? Is it true that the choosing process is divided into 2 parts . First while compiling the JVM looks for a candidate method to execute . It selects the required signature into the declared object class ( not the effective one ) . Once it selected the candidate signature , it ... | - Class A : +f ( short x ) : int ; +f ( String x ) : int ; - Class B extends A : +f ( int x ) : int ; +f ( String x ) : int ; - Class C extends A : +f ( double x ) : int ; +f ( byte x ) : int ; - Class D extends C : +f ( byte x ) : int ; +f ( short x ) : int ; - Class E extends C : +f ( char x ) : int ; +f ( int x ) : ... | Methods selection with Overloading and Overriding |
Java | I am new using GlassFish Server and WS . I just deployed a Web app . generated with maven having this web.xmlI click on the Web Application LinksI have this class in the application : It seems that the WS is deployed since I saw it in EnginesI can access the spp . http : //localhost:8080/iberiafleet/ But I do n't now h... | < ! DOCTYPE web-app PUBLIC `` -//Sun Microsystems , Inc.//DTD Web Application 2.3//EN '' `` http : //java.sun.com/dtd/web-app_2_3.dtd '' > < web-app > < display-name > Archetype Created Web Application < /display-name > < /web-app > import javax.jws.WebMethod ; import javax.jws.WebService ; import javax.servlet.http.Ht... | GlassFish Server deployment |
Java | My application structure is likeI created an annotation as below : -Then created a Sample Interceptor : Then I created a GuiceModule as below : - } Class in which I am using the above annotation is I have a RestModule using which I am binding SampleClassForInterceptor as followsNow I have a bootsrap class in which I am... | @ Retention ( RetentionPolicy.RUNTIME ) @ Target ( ElementType.METHOD ) public @ interface SampleAnnotation { } public class SampleInterceptor implements MethodInterceptor { private static final Logger logger = LoggerFactory.getLogger ( SampleInterceptor.class ) ; @ Inject SampleService sampleService ; // this is not w... | Not able to inject java object while writing Annotation based Method Interceptor using Guice framework |
Java | Im trying to do - What I expect to happen is to now have 2 separate readers on the file pointing at different places . However , the buffReader returns null on the readLine , while the scanner seems to work fine . Is it possible for me to have 2 readers like I want ? | BufferedReader br = new BuffereReader ( file ) ; Scanner s = new Scanner ( br ) ; sys.out ( s.next ( ) ) ; sys.out ( buffReader.readLine ( ) ) ; | Scanner constructor causes bufferedReader to return null |
Java | I 'm trying to hide an implementation of a class I do not own . I 'm wanting to do this my extending the class and implementing an interface of my own . Here is how an instance of the class I need is created : QueueInfo is the class I do not own . To get an instance of this object , I have to use an admin object to get... | QueueInfo info = admin.getQueue ( queueName ) ; public class EMSQueueInfo extends QueueInfo implements IQueueInfo { // ... } QueueInfo info = new QueueInfo ( queueName ) ; public class EMSQueueInfo extends QueueInfo implements IQueueInfo { public EMSQueueInfo ( String queueName ) { super ( queueName ) ; } } public clas... | Java OO : Is this even possible ? |
Java | I am using the below code . The first line is giving java.lang.NumberFormatException , and the second is giving java.lang.NullPointerException . I 'm unable to figure out why . | int intValue =Integer.parseInt ( null ) ; Double double1 = Double.parseDouble ( null ) ; | Why do different Exceptions occur ? |
Java | I 'm attempting to count the number of times an Int is seen in a field within a List of Objects.This is the code I haveyet it is n't ideal , if more ratings are added ( say 20+ ) then you 'd have a bunch of doubles being created , and it 's not maintainable.I know I could do something with a Stream if I had a list of i... | TreeMap < Integer , Double > ratings = new TreeMap ( ) ; ArrayList < Establishment > establishments = new ArrayList < > ( ) ; double one = 0 ; double two = 0 ; double three = 0 ; double five = 0 ; for ( Establishment e : establishments ) { if ( e.getRating ( ) == 1 ) { one++ ; } if ( e.getRating ( ) == 2 ) { two++ ; } ... | How could I improve this List iteration with a Stream ? |
Java | Reading the JAVA 13 SE specification , I found in chapter 5 , section 5.1.7 . Boxing Conversion the following guarantee : If the value p being boxed is the result of evaluating a constant expression ( §15.28 ) of type boolean , char , short , int , or long , and the result is true , false , a character in the range '\u... | Byte b1= ( byte ) 4 ; Byte b2= ( byte ) 4 ; System.out.println ( b1==b2 ) ; Byte b1=4 ; | Is caching of boxed Byte objects not required by Java 13 SE spec ? |
Java | I tried something in my code and it didn´t work ( the error when compiling was `` The local variable fundo is never read '' ) . I´ve made some changes and it worked , but I would like to know why it didn´t work in the first place.I have a class called Setor , in my code I´m trying to create an object from that class in... | class Vendedor { void abreTeatro ( int codigoCamarote , int capacidadeCamarote , int precoCamarote , int codigoFrente , int capacidadeFrente , int precoFrente , int codigoMeio , int capacidadeMeio , int precoMeio , int codigoFundo , int capacidadeFundo , int precoFundo ) { Setor camarote = new Setor ( codigoCamarote , ... | Why can´t I create a class object within a method from a different class in Java ? |
Java | ( I 'm using Eclipse Luna 4.4.0 , JDK 1.8.0_05 ) I 'm making a game , and the topology of the game world can be roughly broken down into World - > Level - > Tile , where a Tile is a a small unit of terrain . I have three projects set up , one which holds some base classes for those structures , and the other two are se... | public class BaseWorld { /* ... code ... */ } public class BaseLevel { /* ... code ... */ } public class BaseTile { /* ... code ... */ } public class World extends BaseWorld { /* ... extended code ... */ } public class Level extends BaseLevel { /* ... extended code ... */ } public class Tile extends BaseTile { /* ... e... | This convoluted generics pattern crashes Eclipse - can I make it work ? |
Java | When I use this code at my home PC , it gives the output as `` output1 '' , Butwhen i use the same code at my office PC gives a different output as `` output2 '' .code : Output 1 : C : \Users\admin\AppData\Local\Temp\Output 2 : C : \Users\admin\AppData\Local\TempWhy there is a difference in output ? | System.out.println ( System.getProperty ( `` java.io.tmpdir '' ) ) ; | Different Results on Different System |
Java | This is my second programming class and I am new to Java . I have been working on my first assignment and it involves classes and methods . I know very little about these topics and find myself lost . My assignment asks me to create a RPN calculator that asks the user for two numbers and an operator . The calculator pe... | import java.util.Scanner ; public class RPNCalc { public static void main ( String [ ] args ) { Scanner keyboard = new Scanner ( System.in ) ; double v1 , v2 ; String operator = keyboard.nextLine ( ) ; char symbol = operator.charAt ( 0 ) ; System.out.print ( `` Enter a value v1 : `` ) ; v1 = keyboard.nextDouble ( ) ; S... | RPNCalculator Code Confusion |
Java | I am new in Java8 , and I created this piece of code that is working finebut under my understandings this piece of code should also work fine , but is not the case and I am wondering why | userService.getClient ( ) .findUsersByMarkets ( marketIds ) .stream ( ) .filter ( us - > ! alreadyNotifiedUserIds.contains ( us.getId ( ) ) ) .forEach ( usersToBeNotified : :add ) ; userService.getClient ( ) .findUsersByMarkets ( marketIds ) .stream ( ) .filter ( us - > ! alreadyNotifiedUserIds.contains ( User : :getId... | Java8 .getMethod ( ) vs : :getMethod |
Java | I am facing some problems with garbage collection while generating an application in java , where I use Stream.map to trim all the elements in the list . The instances of anonymous lambda class exist in the heap dump even though the instance of the enclosing class is 0 as shown in the snap of visual VM.The LambdaTestin... | class LambdaTesting { protected List < String > values ; protected LambdaTesting ( List < String > values ) { this.values = values ; } public List < String > modify ( ) { return this.values.stream ( ) .map ( x - > x.trim ( ) ) .collect ( Collectors.toList ( ) ) ; } public List < String > modifyLocal ( ) { List < String... | Java lambdas heap dump - Instance of lambda not getting garbage collected |
Java | I 'm working through myself Oracle 's JavaFX tutorials . After doing Swing for many years ( a long time ago ) I 'm fascinated by the new smart features , incl . properties . I was surprised to see that these examples ( e.g : https : //docs.oracle.com/javafx/2/ui_controls/table-view.htm ) do n't use them in a way what I... | public static class Person { private final SimpleStringProperty firstName ; ... public String getFirstName ( ) { return firstName.get ( ) ; } emailCol.setCellValueFactory ( new PropertyValueFactory < Person , String > ( `` firstName '' ) ) ; firstNameCol.setCellValueFactory ( celldata - > celldata.getValue ( ) .firstNa... | JavaFX Displaying properties in controls |
Java | This happens in both C # and Java so I think it 's not a bug , just wonder why.According to this page , the lower case of `` '' is `` '' , they should be the equal when comparing with IgnoreCase option . Why they are not equal ? | var s = `` '' ; var lower = s.ToLower ( ) ; var upper = s.ToUpper ( ) ; if ( ! lower.Equals ( upper , StringComparison.OrdinalIgnoreCase ) ) { //How can this happen ? } | Case-insenstive string comparison strange behavior |
Java | I have 2 Lists : Does anyone know how can I merge those 2 Lists to one List containing all the employees from both lists grouped by `` PersonalNumber '' and keeping the order of the elemets in newList ? newList comes from the Database with a predefined sorting , and I need to keep it that way , so I ca n't sort it agai... | // old listList < Employee > oldList = new ArrayList < > ( ) ; Employee emp1 = new Employee ( ) ; emp1.setPersonalNumber ( `` 123 '' ) ; emp1.setName ( `` old_name1 '' ) ; emp1.setStatus ( Status.OLD ) ; Employee emp2 = new Employee ( ) ; emp2.setPersonalNumber ( `` 456 '' ) ; emp2.setName ( `` old_name2 '' ) ; emp2.se... | Java 8 : merging two Lists containing objects by Id |
Java | The standard method of implementing singleton design pattern is this : I was wondering if you could also implement it like this : and if yes which version is better ? | public class Singleton { private static Singleton instance = new Singleton ( ) ; public static Singleton getInstance ( ) { return instance ; } private Singleton ( ) { } } public class Singleton { private Singleton ( ) { } public final static Singleton INSTANCE = new Singleton ( ) ; } | Implementing Singleton Alternatively |
Java | I am comfortable with functional languages and closures and was surprised by the following error : `` Can not refer to the non-final local variable invite defined in an enclosing scope '' .Here is my code : As I understand it , referencing invite in the TimeTask instance is an error because that variable is not guarant... | Session dbSession = HibernateUtil.getSessionFactory ( ) .openSession ( ) ; Transaction dbTransaction = dbSession.beginTransaction ( ) ; Criteria criteria = dbSession.createCriteria ( Invite.class ) .add ( Restrictions.eq ( `` uuid '' , path ) .ignoreCase ( ) ) ; Invite invite = ( Invite ) criteria.uniqueResult ( ) ; if... | What 's the Java way of handling closures ? |
Java | Please what memory tuning advise would you suggest given the GC log below with a system currently running on these params , taking into consideration the Machine recieves high frequency data that takes a about 6ms to process.Thanks in Advance.GC Logs | java -Xms4144m -Xmx4144m -XX : +UseParNewGC -XX : +CMSClassUnloadingEnabled -XX : CMSFullGCsBeforeCompaction=1 -XX : +PrintGCDetails -Xloggc : gc.log -verbose : gc -XX : SurvivorRatio=4 -XX : +UseCompressedOop 198.341 : [ GC 198.341 : [ ParNew : 1178752K- > 235712K ( 1178752K ) , 0.7930435 secs ] 2653227K- > 1913561K (... | JVM Memory Tuning Advice |
Java | I 'm trying to parse a json file that looks like thisThe code I have is currently this : I am getting an error : Is there something special I need to do in order to read `` < `` as String ? I 'm reading the file into a BufferReader with StandardCharsets.UTF_8 like this : Edit : I actually do need defaultTyping for an A... | { `` foo '' : `` v2 '' , `` bar '' : [ `` abc/bcf < object @ twenty > .xyz '' , `` abc/fgh < object @ thirtu > .xyz '' ] } Config.javaprivate static final ObjectMapper OBJECT_MAPPER ; static { OBJECT_MAPPER = new ObjectMapper ( ) ; OBJECT_MAPPER.configure ( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES , false ) ; ... | Deserializing JSON with special characters into a string |
Java | I want to dynamically set an integer variable using a hexadecimal value , but when I use Integer.parse ( hexValue , 16 ) it gets a different value from setting as int a = 0x04A7D488For example : Why do I get different values ? How can I dynamically set variable a with value 0x04A7D3B8 ? Note : I 've discovered that thi... | int a = 0x04A7D3B8 ; System.out.println ( `` a = `` + a ) ; // prints 78107576int b = Integer.parseInt ( `` 04A7D3B8 '' , 16 ) ; System.out.println ( `` b = `` + b ) ; // prints 78107784 | Why does this hexadecimal value gets different decimal value ? |
Java | I have written : And sonar says : New : Squid : S2183 Severity : CRITICAL , Message : Remove this useless shift Could anybody tell me why ? Is that only the fact that there should be no calculations on literals , even if it adds to readability ? | public static final int MY_GREAT_COLOR = ( 91 < < 16 ) + ( 155 < < 8 ) + 213 + ( 255 < < 32 ) ; | SonarQube Java Analyser , rule S2183 , why should I remove this useless shift ? |
Java | java.util.concurrent.TimeUnit has this source : Why is n't this an abstract method like | public long convert ( long sourceDuration , TimeUnit sourceUnit ) { throw new AbstractMethodError ( ) ; } abstract int excessNanos ( long d , long m ) ; | Why does java.util.concurrent.TimeUnit.convert throw an AbstractMethodError instead of being abstract |
Java | I am a complete newbie at Big O and I am a bit stumped by this . I have : In my mind this would equate to Am I right or can it be simplified to N as you are doubling the inputs with n*n and halving it with i *= 2 ? | for ( int i = 1 ; i < n*n ; i *= 2 ) | Big O N^2 ( Log N ) |
Java | Q : Is it possible to create Stream implementation that counts their elements in a single operation rather than counting each and every element in the stream ? I came to this though when i tried to compare two methods on a list : size ( ) count ( ) Stream : :count terminal operation counts the number of elements in a S... | List < Integer > list = IntStream.range ( 0 , 100 ) .boxed ( ) .collect ( toList ( ) ) ; System.out.println ( list.size ( ) ) ; System.out.println ( list.stream ( ) .count ( ) ) ; | Is it possible to create Stream implementation that counts their elements in a single operation |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.