lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I wrote this class : javac ListArg.java // compiled classI compiled above class and run like : java ListArg *But ListArg is displaying current directory contents on console and not `` * '' . | public class ListArg { public static void main ( String args [ ] ) { for ( int i=0 ; i < args.length ; i++ ) { System.out.println ( args [ i ] ) ; } } } | Strange Behavior of Java Argument * |
Java | I was learning to write some lambda representation as FunctionalInterface.So , to add two integers I used : Gives me the output 70 . But if I write it as this I get an error saying Wrong number of type arguments : 3 ; required : 1Is n't BinaryOperator a child of BinaryFunction ? How do I improve it ? | BiFunction < Integer , Integer , Integer > biFunction = ( a , b ) - > a + b ; System.out.println ( biFunction.apply ( 10 , 60 ) ) ; BinaryOperator < Integer , Integer , Integer > binaryOperator = ( a , b ) - > a + b ; | Which FunctionalInterface should I use ? |
Java | I 've tried searching for it , but I do n't really now how to formulate the question correctly ... I have an if-statement with many logical operators . How do I do this easier ? I 'm thinking in pseudo-code I want something like this : As you understand , I 'm a beginner and I have problems formulating what I need . | If ( n == 1 ||n == 2 ||n == 3 ||n == 5 ||n == 9 ||n == 8 ||n == 7 ||n == 551 ||n == 17 ||n == 81 || etc etc ) { //Stuff } List list = { 1 , 3 , 5 , 7 , 9 , 12 , 14 , 16 , 18 , 19 , 21 , 23 , 25 , 27 , 30 , 32 , 34 , or 36 } if n is in list , then { } | I need help making an if statement with many logical operators easier |
Java | I decided to an solid rpg-like game structure with Java to practice design patterns.Basically there are different types of characters in my game , which are all considered to be `` game objects '' , having some common features : Status here is an enumeration : I would like to make my code flexible , easy-to-modify , an... | public abstract class Character extends GameObject { Status status ; //fields , methods , etc . } public abstract class Monster extends Character { //fields , methods , etc } public class Hero extends Character { //fields , methods , etc } public enum Status { NORMAL , BURNT , POISONED , HEALED , FROZEN } public class ... | Design pattern to customize possible statuses of a Character in a game |
Java | I have added this gradle task and then I get this error : what is wrong with my syntax ? I saw this tutorial : | FAILURE : Build failed with an exception . * Where : Build file '/Users/eladb/WorkspaceQa/java/UsersServer/build.gradle ' line : 98* What went wrong : A problem occurred evaluating root project 'UsersServer'. > No signature of method : org.gradle.api.tasks.testing.junit.JUnitOptions.includeGroups ( ) is applicable for ... | org.gradle.api.tasks.testing.junit.JUnitOptions.includeGroups ( ) is applicable for argument types : ( java.lang.String ) values : [ NoDbTests ] |
Java | I am designing an application that has two widgets : -A list that contains arbitrary objects-A table that displays specific properties of the currently selected objectThe goal is to be able to pick an object from the list , look at the properties , and modify them as necessary . The list can hold objects of various typ... | public class Person { public String name ; public Integer age ; } public class Vehicle { public String make ; public String model ; } public String [ ] getFields ( ) { return new String [ ] { `` name '' , `` age '' } ; } | Displaying various objects ' instance variables in a JTable and modifying them |
Java | I have the pattern `` ddMMyy '' in my code I have specified it using the appendValue methods : However this produces `` 0099 '' for year : 0099-01-10If I change that to using the appendPattern like that : I have the correct result for year `` 2099 '' with century in it . 2099-01-10The code seems equivalent for me why i... | DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder ( ) .appendValue ( ChronoField.DAY_OF_MONTH , 2 ) .appendValue ( ChronoField.MONTH_OF_YEAR , 2 ) .appendValue ( ChronoField.YEAR_OF_ERA , 2 ) .toFormatter ( ) ; System.out.println ( LocalDate.parse ( `` 100199 '' , dateTimeFormatter ) ) ; DateTimeFormat... | Java8 appendPattern vs pattern defined by appendValue methods produces different result |
Java | I have a WebDriver based Java testsuite , which I try to execute with Jenkins.Project is imported and build was successful.During execution of test I get following : Running TestRunner Configuring TestNG with : org.apache.maven.surefire.testng.conf.TestNG652Configurator @ 2437c6dc org.openqa.selenium.firefox.NotConnect... | Xvfb :19 -screen 0 1024x768x16 & export DISPLAY=:19firefox & Ubuntu 16.04.3Selenium 2.53.1Firefox 55.0Jenkins 2.60.3 | Firefox WebDriver : Failed to connect to binary |
Java | Given a function Function < T , T > f and a Stream < T > ts what is a good ( nice readability , good performance ) way of creating a new Stream < T > which first contains the original elements and then the elements converted by f.One might think this would work : But this does n't work and results in an exception inste... | Stream.concat ( ts , ts.map ( f ) ) ; java.lang.IllegalStateException : stream has already been operated upon or closed | Adding an element to the end of a stream for each element already in the stream |
Java | I found this on github occasionally.Could this happen in common use ? | md5 ( text ) .equals ( text ) | Could md5 algrithom generate the same string with the original string ? |
Java | Some byte arrays using new String ( byte [ ] , '' UTF-8 '' ) return different results in jdk 1.7 and 1.8bytes2 use new String ( byte [ ] , '' UTF-8 '' ) , the result ( str2 ) is not the same in jdk7 and jdk8 , but byte1 is same . What is special about bytes2 ? Test the `` ISO-8859-1 '' code , the result of bytes2 is th... | byte [ ] bytes1 = { 55 , 93 , 97 , -13 , 4 , 8 , 29 , 26 , -68 , -4 , -26 , -94 , -37 , 32 , -41 , 88 } ; String str1 = new String ( bytes1 , '' UTF-8 '' ) ; System.out.println ( str1.length ( ) ) ; byte [ ] out1 = str1.getBytes ( `` UTF-8 '' ) ; System.out.println ( out1.length ) ; System.out.println ( Arrays.toString... | new String ( byte [ ] ) results differ in JDK 7 and 8 |
Java | I 'm working on code that calculates entries in the StackFrameMap ( SFM ) . The goal is to be able to generate ( SFM ) entries that make the Java 7 bytecode verifier happy . Following a TDD methodology , I started by creating bogus SMF entries for the verifier to complain about ; I would the replace these with my prope... | public int stackFrameTest ( int x ) { if ( x > 0 ) { System.out.println ( `` positive x '' ) ; } return -x ; } public int stackFrameTest ( int ) ; flags : ACC_PUBLIC Code : stack=2 , locals=2 , args_size=2 0 : iload_1 1 : ifle 12 4 : getstatic # 47 // Field java/lang/System.out : Ljava/io/PrintStream ; 7 : ldc # 85 // ... | Why does n't the Java 7 byteode verifier choke on this ? |
Java | I know there are many topics and resources about this , but I 'm wondering about a very specific question ( and it might take a very long time to check all sources for a definite answer ) . I know that JVM/Dalvik guarantees that by the time you access a static field of a class ( except for final static primitive values... | public class Boo { public static int [ ] anything = new int [ ] { 2,3,4 } ; private static int [ ] something = new int [ ] { 5,6,7 } ; // this may be much bigger as well public static final int [ ] getAndClear ( ) { int [ ] st = something ; something = null ; return st ; } } | Is static init guaranteed NOT to run if class is not accessed ? |
Java | This creates literal `` abc '' in string pool . No new literal is created . b is pointed to the existing `` abc '' .Now the object is created in heap and c is pointed to the heap . The literal is also created in the string pool.But , what happens if the pool already has the literal `` abc '' ? Will there be duplicate l... | String a = `` abc '' ; String b = `` abc '' ; String c = new String ( `` abc '' ) ; | How strings are handled in java |
Java | I have a command line program to validate an XML against an XSD file . One of the command line options for this program is the namespace to use , which is stored in String namespace . I get a different validation result depending on whether I pass the parsed option as namespace or pass the call to namespace.intern ( ) ... | public static void validateAgainstXSD ( File file , File schemaFile , String namespace ) { try { SchemaFactory factory = SchemaFactory.newInstance ( `` http : //www.w3.org/2001/XMLSchema '' ) ; Schema xsdScheme = factory.newSchema ( schemaFile ) ; Validator validator = xsdScheme.newValidator ( ) ; ErrorHandler eh = new... | Why do I get different results with String.intern ( ) vs. passing String object in Java ? |
Java | I 've a question on how to apply Java 8 group by . The group by solution in books and other questions / forums illustrates applying on a object property , like a getter method , but my case is bit different . I 've a DB query result set which is a List inside List . The inner list is sometimes a List < Long > or List <... | List < List > resultSet = new ArrayList < > ( ) ; // did n't declare List < List < Long > > to keep it generic for both Long , and String.List < Long > tmp = new ArrayList < > ( ) ; tmp.add ( 1L ) ; tmp.add ( 20L ) ; resultSet.add ( tmp ) ; tmp = new ArrayList < > ( ) ; tmp.add ( 1L ) ; tmp.add ( 30L ) ; resultSet.add ... | How to use Group by on a result set response |
Java | I 've been trying to switch from the Oracle OCI driver to the thin driver , I got the thin driver to pickup my tnsnames.ora by adding -Doracle.net.tns_admin=/path to the command line.However , our tnsnames.ora contains lines where multiple services are defined at once . They look like this : The OCI driver seems happy ... | NEWS2 , NEWS , NEWSFX = ( DESCRIPTION_LIST= ... ) | Declaring multiple identical service in tnsnames.ora supported by oracle thin driver |
Java | I 'm new to programming , I 'm sorry if this is a silly mistake , but I keep getting this error `` CompanyAddress.java:11 : error : can not find symbol System.out.println ( testObject.getName ( CompanyName ) ) ; '' I do n't know what I 'm doing wrong.The main.my test.java | import java.util.Scanner ; public class CompanyAddress { public static void main ( String [ ] args ) { Scanner scan = new Scanner ( System.in ) ; test testObject = new test ( ) ; System.out.println ( `` Enter name : `` ) ; String input = scan.nextLine ( ) ; testObject.getName ( input ) ; System.out.println ( testObject... | I ca n't get this to work , methods & instance variables |
Java | I have a class representing DB-Entries with a unique Id attribute.Is is OK to implement the equals ( ) and hashcode ( ) methods only based on this attribute | @ Override public int hashCode ( ) { return id ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) return true ; if ( obj == null ) return false ; if ( getClass ( ) ! = obj.getClass ( ) ) return false ; Task other = ( Task ) obj ; if ( id ! = other.id ) return false ; return true ; } | Is this naive equals , hashcode OK ? |
Java | Probably I am missing something and maybe my assumptions were wrong , but I thought that when I declare parametrized method with type T then no matter how much variables there are with that type it is still the same type . But I see that this compiles and it oposses my view.So if my method is parametrized with one type... | static < T > void f ( T a , T b ) { } public static void main ( String [ ] args ) { f ( Integer.MIN_VALUE , `` ... '' ) ; } | Method parametrized with one type accepts two types |
Java | I need to check if a returned list was created once or if it 's a copy of an object . Is it possible to find out it 's address ? How could getAddress ( list ) look like ? The problem is that hashCode ( ) which normally returns an address is overridden in AbstractList , so it would return a valid hash code instead of an... | // thread 1List < Object > list = supplier.get ( ) ; System.out.print ( `` list : `` + list + `` @ '' + getAddress ( list ) ) ; // thread 2List < Object > list = supplier.get ( ) ; System.out.print ( `` list : `` + list + `` @ '' + getAddress ( list ) ) ; | How can I get an address of a List ? |
Java | While solving a challenge online , I observed the following behavior of java which I found a little weird . I started off by compiling a program along the following outline : Notice that in the above program , there are two errors : I have not handled exceptions which might be thrown by BufferedReader.I have not import... | import java.io . * ; class WeirdJava { public static void main ( String [ ] args ) { BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; String input = br.readLine ( ) ; HashMap < Integer , Integer > map = new HashMap < Integer , Integer > ( ) ; System.out.println ( `` Weird Java '' ) ; } }... | Unexpected order of errors in java compilation |
Java | I have a generic interface interface ListList < E > extends List < List < E > > . For some reasons , I ca n't cast ListList < ? super T > to List < List < ? super T > > . Is there any way of doing it and why it does n't work ? By this moment I 've already tried the following : Simple assignment , this way I 've managed... | ListList < ? super T > var = new ArrayListList < > ( ) ; List < ? extends List < ? super T > > work = var ; // ( 1 ) List < List < ? super T > > notWork = var ; // ( 1.1 ) List < List < ? super T > > explicit = ( List < List < ? super T > > ) var ; // ( 2 ) List < List < ? super T > > raw = ( ListList ) var ; // ( 3 ) ... | Why ListList < ? super E > is List < ? extends List < ? super E > > but not List < List < ? super E > > |
Java | I have built a User management service in which I 'm using MongoDb ( spring data ) . I have two models User and Role.Role model -and Role enumerator-In User there is a role attribute which I have @ Dbref to role collection . My problem is that I want to have a option of using PostgreSql and MongoDb in the same applicat... | package com.userservice.usermanagement.models ; import java.util.HashSet ; import java.util.Set ; import org.springframework.data.annotation.Id ; import org.springframework.data.mongodb.core.mapping.DBRef ; import org.springframework.data.mongodb.core.mapping.Document ; @ Document ( collection = `` user_data '' ) publi... | Is it possible to use MongoDb and PostgreSql for same model in Spring boot ? |
Java | Why does the below snippet compile ? OtherInterface does not extends Concrete so I would have bet a kidney that this would n't compile . But it does.On the other hand , the next snippet does not compile , which is what I expect . | public class Test { public static interface SomeInterface { } public static interface OtherInterface { } public static class Concrete implements SomeInterface { public < T extends Concrete > T getConcrete ( ) { return null ; } } public static void doStuff ( ) { Concrete c = new Concrete ( ) ; OtherInterface iCompile = ... | Apparent type violation , but compiles |
Java | I am trying to improve the performance of some code . It looks something like this : What I noticed is that many of the Patterns seem to be simple string literals with no regular expression constructs . So I want to simply store these in a separate list ( importantList ) and do an equality test instead of performing a ... | public boolean isImportant ( String token ) { for ( Pattern pattern : patterns ) { return pattern.matches ( token ) .find ( ) ; } } public boolean isImportant ( String token ) { if ( importantList.contains ( token ) ) return true ; for ( Pattern pattern : patterns ) { return pattern.matches ( token ) .find ( ) ; } } | How do I determine if a string is not a regular expression ? |
Java | Looking java 's hashmap implementation , not able to understand the reason behind some lines . In below code copied from here , in line 365-367 , I am not able to understand why have they done the assignment of e.key to k first and then compared == with key [ ( k = e.key ) == key ] . Why not directly do ( e.key == key ... | 359 360 final Entry < K , V > getEntry ( Object key ) { 361 int hash = ( key == null ) ? 0 : hash ( key.hashCode ( ) ) ; 362 for ( Entry < K , V > e = table [ indexFor ( hash , table.length ) ] ; 363 e ! = null ; 364 e = e.next ) { 365 Object k ; 366 if ( e.hash == hash & & 367 ( ( k = e.key ) == key || ( key ! = null ... | in java hashmap implementation key is first assigned to object and then compared |
Java | I have a Many-to-Many relationship between the class Foo and Bar . Because I want to have additional information on the helper table , I had to make a helper class FooBar as explained here : The best way to map a many-to-many association with extra columns when using JPA and HibernateI created a Foo , and created some ... | foo.addBar ( bar ) ; // adds it bidirectionallybarRepository.save ( bar ) ; // JpaRepository foo.removeBar ( bar ) ; // removes it bidirectionallybarRepository.save ( bar ) ; // JpaRepository public class Foo { private Collection < FooBar > fooBars = new HashSet < > ( ) ; // constructor omitted for brevity @ OneToMany ... | Hibernate Many-to-Many with join-class Cascading issue |
Java | As discussed in this question , the equals method of java.awt.geom.Area is defined as public boolean equals ( Area other ) instead of overriding the equals method from Object . That question covers the `` why '' , and I 'm interested in `` how can I force Java to use the most appropriate equals method '' .Consider this... | public static void main ( String [ ] args ) { Class < ? > cls = Area.class ; Area a1 = new Area ( new Rectangle2D.Double ( 1 , 2 , 3 , 4 ) ) ; Area a2 = new Area ( new Rectangle2D.Double ( 1 , 2 , 3 , 4 ) ) ; System.out.println ( `` Areas equal : `` + a1.equals ( a2 ) ) ; // true Object o1 = ( Object ) a1 ; Object o2 =... | Java reflection to call overloaded method Area.equals ( Area ) |
Java | If a class A makes public Object 's clone ( ) method : What will be the instanceof ( or getClass ( ) ) of an instance of A created using clone ( ) ? What about instances of class B extends A created using the clone ( ) method ? EDITClarification : I ask this because even before compiling , Eclipse java editor requires ... | @ Overridepublic Object clone ( ) { return super.clone ( ) ; } A original = new A ( ) ; A cloned1 = original.clone ( ) ; // Eclipse marks this as errorA cloned2 = ( A ) original.clone ( ) ; // This is OK | What is instanceof of a cloned object ? |
Java | Why does this code totally destroy the output ? Sample output I get : Boo.Boo.Boo.Boo.Boo.Boo.Boo.Boo.Boo . | public class Main { public static void main ( String [ ] args ) { System.out.println ( ) ; rec ( ) ; } private static int rec ( ) { try { return rec ( ) ; } catch ( StackOverflowError e ) { System.out.println ( `` Boo . `` ) ; return 0 ; } } } | Odd Java StackOverflowError ? |
Java | I 've typed up a bunch of String [ ] arrays in an interface . I want IntelliJ-IDEA to order the elements alphabetically . I 'm not talking about ordering during run-time or compile-time . I want the actual java/text-file to be modified.How can I get IntelliJ-IDEA to sort String [ ] array elements alphabetically and in ... | String [ ] RACES = { `` human '' , `` elf '' , `` small folk '' , `` orc '' , `` goblin '' , `` aasimar '' , `` tiefling '' } ; String [ ] RACES = { `` aasimar '' , `` elf '' , `` goblin '' , `` human '' , `` orc '' , `` small folk '' , `` tiefling '' } ; | How to order pre-written String [ ] array elements alphabetically pre-run-time in IntelliJ-IDEA ? |
Java | BackgroundI would like to understand why a snippet of code does not throw a NullPointerException.Source CodeConsider the following code : The deliver method is called repeatedly , whilst the following code runs in a separate thread : There is only a single agent instance.ProblemA NullPointerException is never thrown.Ho... | public class Agent { public List files = new ArrayList ( ) ; public void deliver ( ) { if ( files ! = null & & files.iterator ( ) .hasNext ( ) ) { File file = ( File ) files.iterator ( ) .next ( ) ; } files = new ArrayList ( ) ; } } public void run ( ) { agent.files = null ; } public void deliver ( ) { if ( files ! = n... | Why does this code not throw a NullPointerException ? |
Java | According to Android documentation , in above code , zero is slower . But I do n't understand why ? well I have n't learn that much deep but as I know length is a field not method . So when loop retrieves its value , how its different from retrieving from local variable ? and array length is always fixed once initializ... | public void zero ( ) { int sum = 0 ; for ( int i = 0 ; i < mArray.length ; ++i ) { sum += mArray [ i ] .mSplat ; } } public void one ( ) { int sum = 0 ; Foo [ ] localArray = mArray ; int len = localArray.length ; for ( int i = 0 ; i < len ; ++i ) { sum += localArray [ i ] .mSplat ; } } | Performance tips questions |
Java | I have the following Java class with multiple level of inheritance with certain type parameters . I want to use the type parameter T in class B . However , he following does n't compile : Although I can define the variable t in class C , but it is not a good coding practice . How can I define the following ( This does ... | class B extends C { } class C < T extends D > { } class D { } class B extends C { T t ; } class C < T extends D > { } class D { } class B extends C < T extends D > { } | Multiple Level of Inheritance |
Java | Following is the simplest example of static inner class in Java . Let 's look at it.Within the Outer class , there is a static class named Inner and a static object with the same name Inner of type Extra . The program displays Whilte on the console , a string in the Extra class through Outer.Inner.s in main ( ) which i... | package staticclass ; final class Outer { final public static class Inner { static String s = `` Black '' ; } static Extra Inner = new Extra ( ) ; //The inner class name and the object name of the class Extra are same and it is responsible for shadowing/hiding Inner.s } final class Extra { String s = `` White '' ; } fi... | Static classes in Java -- something is being shadowed |
Java | There is a method in hamcrest library : In my code , I call this method with first being Matcher < Object > and second being Matcher < SomeException > .And now : When I compile it with Eclipse with 1.6 target , it makes < T > Matcher < SomeException > .When I compile it with javac 1.7 with 1.6 target , it makes < T > M... | package org.hamcrest.core ... public static < T > Matcher < T > allOf ( Matcher < ? super T > first , Matcher < ? super T > second ) { List < Matcher < ? super T > > matchers = new ArrayList < Matcher < ? super T > > ( 2 ) ; matchers.add ( first ) ; matchers.add ( second ) ; return allOf ( matchers ) ; } | For method of type T , what should be its 'inferred ' type when it takes two < ? super T > arguments ? |
Java | The title may be misleading but as a non-native i could n't figure out a better one.Say i have two classes , Dog and Fox : And i create some instances as well call some methodsFor the 1 . Ouput I expected `` RingdingRingding '' because hybrid actually is a reference to an instance of the Dog , even if the reference has... | public class Dog { public String bark ( ) { return `` Wuff '' ; } public String play ( Dog d ) { return `` Wuff '' + d.bark ( ) ; } } public class Fox extends Dog { public String bark ( ) { return `` Ringding '' ; } public String play ( Fox f ) { return `` Ringding '' + f.bark ( ) ; } } Fox foxi = new Fox ( ) ; Dog hyb... | Class type of reference and the actual class type , which decides which method to call ? |
Java | When redeclaring Integer ' a ' in line 33 , why does jshell show the reference variable as an instance of Integer ( refer to lines 38 & 39 ) ? After the redeclaration , line 34 shows that ' a ' is set to null . When ' a ' is declared in line 6 but not given a value , or reset to null in line 22 , ' a ' is not considere... | 01 : java-lava : ~ cafedude $ jshell02 : | Welcome to JShell -- Version 1103 : | For an introduction type : /help intro04 : 05 : jshell > Integer a ; 06 : a == > null07 : | created variable a : Integer08 : 09 : jshell > a instanceof Integer ; 10 : $ 2 == > false11 : | created scratch variable $ 2 : boolean12 : 13 : jsh... | In jshell-11 , why does a redeclared reference variable that resets to null still have a type ? |
Java | I try to use Mockito to mock the getDeclaredMethod ( ) of java.but the parameter of this method is un-certain . how to mock such method ? | public Method getDeclaredMethod ( String name , Class ... parameterTypes ) throws NoSuchMethodException , SecurityException { throw new RuntimeException ( `` Stub ! `` ) ; } | Java Mockito- how to mock uncertain number of parameter method |
Java | I started learning Java and I could n't understand one of examples in `` Thinking in Java '' book.In this example author represent , as he state `` simple use of 'this ' keyword '' : And when above code is working as indeed , I cant understand what increment ( ) method is returning . It 's not variable i , it 's not ob... | //Leaf.java//simple use of the `` this '' keywordpublic class Leaf { int i = 0 ; Leaf increment ( ) { i++ ; return this ; } void print ( ) { System.out.println ( `` i = `` + i ) ; } public static void main ( String [ ] args ) { Leaf x = new Leaf ( ) ; x.increment ( ) .increment ( ) .increment ( ) .print ( ) ; } } | What is returning class when use `` return this '' ? |
Java | What is happening : :At the startdate=2014-12-17T21:37:00+00:00At the endneedbydate= Dec/18/201417 is changed to 18 ... . What wrong am i doing in conversionEDIT : | String date = jsonobject.getString ( `` needbydate '' ) ; DateFormat df = new SimpleDateFormat ( `` MMM/dd/yyyy '' ) ; DateFormat sdf = new SimpleDateFormat ( `` yyyy-MM-dd'T'hh : mm : ssZ '' ) ; Date startDate = sdf.parse ( date ) ; String needbydate = df.format ( startDate ) .toString ( ) + '' '' ; String date=jsonob... | Error in conversion of dates in java |
Java | I have a question about best design practices . I have been attempting to build more immutable components into my project because I read they were easier to maintain in the long run and wanted to test this . When you have a class with immutable data members , say Should the int still be declared as private and given an... | public/private final int importantNumber = 3 ; | Should an immutable class member have an accessor method or allowed to be public ? |
Java | I have following code : mQuestions is empty ArrayList , and I see that count equals 0 on Log always . Also I see 1/111 record on my Log always too . But my activity does n't do a finish method ! makeQuestion is method that need n't work with empty mQuestion ( it throw Exception ) . But If I make a comment for makeQuest... | mQuestions=DictionaryDbWrapper.getInstance ( ) .getQuestionsSequence ( this.getIntent ( ) .getStringExtra ( ApplicationUtilities.TEST_CATEGORY_PARAMETER ) , 50 ) ; mQuestionsCount=mQuestions.size ( ) ; Log.e ( `` count '' , String.valueOf ( mQuestionsCount ) ) ; if ( mQuestionsCount==0 ) { Log.e ( `` 1 '' , `` 111 '' )... | Why does n't this activiy finish ? |
Java | I have two similar pieces of Code : I would like to avoid code duplication and I thought this could be done by using a functional approach.I want to put the loop and the init/shutdown call in seperate functions and then chain their calls ( not the Java 8 Function interface , more pseudocode ) : Then I want to chain the... | void task1 ( ) { init ( ) ; while ( someCondition ) { doSomething ( ) ; } shutdown ( ) ; } void task2 ( ) { while ( someCondition ) { init ( ) ; doSomething ( ) ; shutdown ( ) ; } } Function setup ( Function f ) { init ( ) ; f ( ) ; shutdown ( ) ; } Function loop ( Function f ) { while ( someCondition ) { f ( ) ; } } v... | How can I chain functional calls in Java ? |
Java | I want to write a regular expression in java which will accept the String having alphabets , numbers , - and space any number of times any where.The string should only contain above mentioned and no other special characters . How to code the regular expression in java ? I tried the following , It works when I run it as... | String test1 = null ; Scanner scan = new Scanner ( System.in ) ; test1 = scan.nextLine ( ) ; String alphaExp = `` ^ [ a-zA-Z0-9- ] * $ '' ; Pattern r = Pattern.compile ( alphaExp ) ; Matcher m = r.matcher ( test1 ) ; boolean flag = m.lookingAt ( ) ; System.out.println ( flag ) ; | How to write and use regular expression in java |
Java | In my spring-boot 2.3 application , I have a simple data method using DatabaseClient : With spring-boot 2.4 ( and spring 5.3 and spring-data-r2dbc 1.2 ) , org.springframework.data.r2dbc.core.DatabaseClient from spring-data-r2dbc is deprecated in favor of org.springframework.r2dbc.core.DatabaseClient of spring-r2dbc - w... | fun getCurrentTime ( ) : Mono < LocalDateTime > = databaseClient .execute ( `` SELECT NOW ( ) '' ) .asType < LocalDateTime > ( ) .fetch ( ) .first ( ) } fun getCurrentTime ( ) : Mono < LocalDateTime > = databaseClient .sql ( `` SELECT NOW ( ) '' ) .map { row : Row - > row.get ( 0 , LocalDateTime : :class.java ) ! ! } .... | Spring R2DBC DatabaseClient.as ( … ) |
Java | This code causes a compile error with javac ( but , notably , not with Eclipse 4.2.2 ! ) : The error from javac is this : Changing the cast to ( Bar ) foo ( i.e . using the raw type ) allows the code to compile , as does changing the type of foo to simply Foo < ? extends Iterable < ? > > .EDIT : Hilariously , this simp... | public interface Foo < T > { } class Bar < T > implements Foo < Iterable < T > > { } class Test { void test ( Foo < ? extends Iterable < ? extends String > > foo ) { Bar < ? > bar = ( Bar < ? > ) foo ; } } Foo.java:9 : error : inconvertible types Bar < ? > bar = ( Bar < ? > ) foo ; ^ required : Bar < ? > found : Foo < ... | Why is n't a conversion to `` GenericType < ? > '' allowed here ? |
Java | I need to obtain the underlying OS PID for a Process I start . The solution I 'm using now involves access to a private field through reflection using code like this : It works but there are several problems with this approach , one being that you need to do extra work on Windows because the Windows-specific Process su... | private long getLongField ( Object target , String fieldName ) throws NoSuchFieldException , IllegalAccessException { Field field = target.getClass ( ) .getDeclaredField ( fieldName ) ; field.setAccessible ( true ) ; long value = field.getLong ( target ) ; field.setAccessible ( false ) ; return value ; } | How to obtain pid from Process without illegal access warning with Java 9+ ? |
Java | First variant gives more flexibility , but is that all ? Are there any other reasons to prefer it ? What about performance ? | Collection list = new LinkedList ( ) ; // Good ? LinkedList list = new LinkedList ( ) ; // Bad ? | Is a Collection better than a LinkedList ? |
Java | I 'm trying to apply my knowledge of streams to some leetcode algorithm questions . Here is a general summary of the question : Given a string which contains only lowercase letters , remove duplicateletters so that every letter appears once and only once . You must makesure your result is the smallest in lexicographica... | Input : `` bcabc '' Output : `` abc '' Input : `` cbacdcbc '' Output : `` acdb '' public String removeDuplicateLetters ( String s ) { char [ ] c = s.toCharArray ( ) ; List < Character > list = new ArrayList < > ( ) ; for ( char ch : c ) { list.add ( ch ) ; } List < Character > newVal = list.stream ( ) .distinct ( ) .co... | Java 8 Streams Remove Duplicate Letter |
Java | Are there any conventions as to whether a method called by another method should generally be above or below it ? E.g . say caller ( ) was refactored into two methods - where would be the more standard place out of aboveCaller ( ) or belowCaller ( ) ? Although this is in Java , it is a general programming question and ... | private void aboveCaller ( ) { /* ... here ? ... */ } public void caller ( ) { aboveCaller ( ) ; belowCaller ( ) ; } private void belowCaller ( ) { /* ... or here ? ... */ } | Should a worker method generally be placed above or below the methods that call it ? |
Java | I am trying read the Oracle table information from my application . To get the table description , I execute this query on my application : Here is the code block that executes query : When I run the sql directly on the database I get this result : When I run my application , it returns the result like this : The resul... | SELECT DBMS_METADATA.GET_DDL ( 'TABLE ' , 'CONTRACT_TABLE ' , 'SCHEMA_NAME ' ) FROM DUAL PreparedStatement preparedStatement = null ; ResultSet resultSet = null ; String sql = `` SELECT DBMS_METADATA.GET_DDL ( 'TABLE ' , 'CONTRACT_TABLE ' , 'SCHEMA_NAME ' ) FROM DUAL '' ; preparedStatement = connection.prepareStatement... | Prepared Statement does not retrieve the exact result of the sql |
Java | I have two factory-methods which produce `` consumers '' use different approaches lambda and method references : I found that in first case ( lambdaPrintStringConsumer ( ) ) , method return reference to the same objectbut in the second ( methodRefPrintStringConsumer ( ) ) , objects is differentdirect approach return th... | @ SuppressWarnings ( `` Convert2MethodRef '' ) public Consumer < String > lambdaPrintStringConsumer ( ) { return x - > System.out.println ( x ) ; } public Consumer < String > methodRefPrintStringConsumer ( ) { return System.out : :println ; } @ Testpublic void shouldSameFromFactoryMethod_lambda ( ) { Consumer < String ... | Why Functional interface initialize different when use lambda in factory-method and method reference ( singleton / prototype ) ? |
Java | When I run the following code on Intellij with input 1000000000000 the process holds a moment every 8 million loops.Why is it like this ? Why does n't run in one smoothly flow until the end ? | import java.util . * ; public class Main { public static void main ( String [ ] args ) { Scanner in = new Scanner ( System.in ) ; System.out.println ( `` Please type a number '' ) ; long n = in.nextLong ( ) ; System.out.println ( `` Thanks . `` ) ; long count = 0 ; for ( long i=0 ; i < =n ; i++ ) { if ( ( n+i ) == ( n^... | for loop makes pause every 8 million iterations - why ? |
Java | I have a JSON value as follows in String format . Now if I try to map this as follows , it works and maps fine . But I want to map it to a custom Data class as follows . When I do this , the result of vo is null . Refer to following on how the Data class is structured . Please advice what I am doing wrong . Thanks . | { `` Sample '' : { `` name '' : `` some name '' , `` key '' : `` some key '' } , `` Offering '' : { `` offer '' : `` some offer '' , `` amount '' : 100 } } //mapper is ObjectMapper ; //data is the above json in String formatMap vo = mapper.readValue ( data , Map.class ) ; Data vo = mapper.readValue ( data , Data.class ... | Unable to map String to Object |
Java | I have a small implementation detail question that I fail to understand in ArrayList : :removeIf . I do n't think I can simply put it the way it is without some preconditions first.As such : the implementation is basically a bulk remove , unlike ArrayList : :remove . An example should make things a lot easier to unders... | List < Integer > list = new ArrayList < > ( ) ; // 2 , 4 , 6 , 5 , 5list.add ( 2 ) ; list.add ( 4 ) ; list.add ( 6 ) ; list.add ( 5 ) ; list.add ( 5 ) ; Iterator < Integer > iter = list.iterator ( ) ; while ( iter.hasNext ( ) ) { int elem = iter.next ( ) ; if ( elem % 2 == 0 ) { iter.remove ( ) ; } } list.removeIf ( x ... | removeIf implementation detail |
Java | I want to create a function which returns two counted values . The values are counted by iterating over a for-loop.For example , I have an array of persons ( male , female , adults , children ) and I only want to find the amount of boys ( child + male ) and the amount of women ( adult + female ) .In the last few years ... | function countBoysAndWomen ( ) { var womenCounter = 0 ; var boysCounter = 0 ; for ( var p of persons ) { if ( p.isAdult ( ) & & p.isFemale ( ) ) womenCounter++ ; else if ( p.isChild ( ) & & p.isMale ( ) ) boysCounter++ ; } return { amountOfWomen : womenCounter , amountOfBoys : boysCounter } ; } private Counter countBoy... | Return 2 counted values from one function |
Java | I am using the below code for epoch to time conversion by using java.util.Date class in Java.Below are the outputs while running the same code on two different timezone server : On EDT server-On IST server -Why does this happen ? I am only passing milliseconds . This data is supposed to be treated as 21:15 on all serve... | Long scheduledTime = 1602258300000L ; Date date = new Date ( scheduledTime ) ; System.out.println ( `` Date obj : '' + date ) ; Date obj : Fri Oct 09 11:45:00 EDT 2020 Date obj : Fri Oct 09 21:15:00 IST 2020 | Different time conversion by using java.util.Date in Java |
Java | I have 2 questions about Arrays in Java , hope you can spare your time to help me.Question 1 : But it returns false ? Question 2 : I run this code : and it returns -2 . BUT when I remove duplication : now it returns 2 , which is the right one . I do n't know how binary Search in Array deals with duplication which lead ... | int [ ] intArray1 = { 1 , 4 , 2 , 5 , 6 , 7 , 2 } ; int [ ] intArray2 = { 1 , 4 , 2 , 5 , 6 , 7 , 2 } ; intArray1.equals ( intArray2 ) ; int [ ] intArray1 = { 1 , 4 , 2 , 5 , 6 , 7 , 2 } ; //2 is duplicatedArrays.binarySearch ( intArray1,2 ) ; int [ ] intArray3 = { 1 , 4 , 2 , 5 , 6 , 7 } ; // nothing is duplicatedArra... | Some questions about Arrays |
Java | I know that you can only have an array of a certain type ( e.g . String , int , Student , etc. ) . I was wondering if this held true in the case of inheritance - i.e . whether or not a Bicycle object that extends Vehicle could be placed in a Vehicle array along with something else , like a Bus object.Here 's my code : ... | public class Test { public static void main ( String [ ] args ) { Bus bus1 = new Bus ( ) ; Bicycle bike1 = new Bicycle ( ) ; bike1.changeGear ( true ) ; Bus bus2 = new Bus ( ) ; Vehicle [ ] myFleet = { bus1 , bike1 , bus2 } ; // Note that Vehicle is an abstract class for ( Bus v : myFleet ) { // Trying to access every ... | Can you have an array of different kinds of objects ? |
Java | Consider the following two classes and interface : Why does the second call to mandatory invoke the overloaded method with Class2 , if getInterface1 and Interface1 have no relationship with Class2 ? I understand that Java 8 broke compatibility with Java 7 : And with Java 8 ( also tested with 11 and 13 ) : | public class Class1 { } public class Class2 { } public interface Interface1 { } public class Test { public static void main ( String [ ] args ) { Class1 class1 = getClass1 ( ) ; Interface1 interface1 = getInterface1 ( ) ; mandatory ( getClass1 ( ) ) ; // prints `` T is not class2 '' mandatory ( getInterface1 ( ) ) ; //... | Why does the compiler choose this generic method with a class type parameter when invoked with an unrelated interface type ? |
Java | I have an XML schema , where element Calling1 is defined like this : I have generated Jaxb bindings : I am using JAXB to unmarshal XML documents to Java representation . If my XML cantains element Calling1 , which value is not a correct dateTime , for exampleJAXB does not throw any error , but returns me an java object... | < xsd : element name= '' Calling1 '' type= '' xsd : dateTime '' > < xjc extension= '' true '' schema= '' $ { basedir } /message.xsd '' destdir= '' $ { basedir } /src '' package= '' org.test '' / > < Calling1 > NOT_A_DATETIME < /Calling1 > | JAXB does not throw an Error on wrong dateTime values |
Java | As you all know it is possible to fetch a method with Reflection and invoke it through the returned Method instance.My question is however ; once it is fetched by Reflection and I invoke the Method over and over again will the performance of the method be slower than the normal way of calling a method ? For example : I... | import java.lang.reflect.Method ; public class ReflectionTest { private static Method test ; public ReflectionTest ( ) throws Exception { test = this.getClass ( ) .getMethod ( `` testMethod '' , null ) ; } public void testMethod ( ) { //execute code here } public static void main ( String [ ] args ) throws Exception { ... | Does the execution of a method fetched by Reflection take longer ? |
Java | Let us say I have the following classes : AnimalCatDogCowAnimal is the base class , cat , dog , and cow each subclass it.I now have a Set < Cat > , Set < Dog > and Set < Cow > each of these are used in the same way , so it makes sense to make a generic function to operate on them : This works great , I can freely pass ... | private boolean addObject ( Animal toAdd , Animal defVal , Set < ? extends Animal > vals ) private boolean addObject ( Animal toAdd , Animal defVal , Set < ? super Animal > vals ) private < T > boolean addObject ( T toAdd , T defVal , Set < ? super T > vals ) ( ( Animal ) toAdd ) .getAnimalType ( ) | Adding to a Generic Set passed into a method |
Java | I am bit surprised that the default ( native ) implementation of the hashCode ( ) method appears ~50x slower than a simple override of the method for the following benchmark.Consider a basic Book class that does not override hashCode ( ) : Consider , alternatively , an otherwise identical Book class , BookWithHash , th... | public class Book { private int id ; private String title ; private String author ; private Double price ; public Book ( int id , String title , String author , Double price ) { this.id = id ; this.title = title ; this.author = author ; this.price = price ; } } public class BookWithHash { private int id ; private Strin... | Java hashCode ( ) : Override faster that native implementation ? |
Java | I have this : I want to merge the boolean expressions into one . So I use this : However , I am worry if this is correct . Is this correct ? Could this be simplified/shorten ? With the help of the answer the shorten solution is : | // returns true if both are equal ( independent of scale ) and also checks against nullpublic static boolean isEqual ( BigDecimal val1 , BigDecimal val2 ) { // 1. check : both will be null or both will be non-null . if ( val1 ! = null ^ val2 ! = null ) return false ; // 2. check : if not null , then compare if both are... | negation of boolean expressions with XOR |
Java | Lately , I 'm having a heated discussion regarding this issue . Lets say I created this method in Java : Whenever I see that in a pull request , I shout and try to explain why it is wrong . By doing that , I 'm misguiding the consumers of my method by the promise that they will get a Set . This means they can remove or... | public Set < String > getRich ( ) { return ImmutableSet < String > ... . ; } public ImmutableSet < String > getRich ( ) { return ImmutableSet < String > ... . ; } | A method declaring a mutable data structure as an output and returning an immutable one actually |
Java | I have a function : So , if I were to do something like : this is all good.However , in another function : Gives me an error , because base.getClass ( ) returns ? extends R.Now from what I understand , the function get ( Class < T > x ) returns T , so when called with ? extends R , which let 's say is CAP # 1 , but sin... | < T > T get ( Class < T > fetchType ) { ... } String x = get ( String.class ) ; < R > R otherFunction ( R base ) { return get ( base.getClass ( ) ) ; } reason : no instance ( s ) of type variable ( s ) exist so that capture of ? extends Object conforms to Rinference variable T has incompatible bounds : equality constra... | Why does a wildcard on a generic parameter require an explicit cast ? |
Java | I have a arrayList with values { a , b , a , c , d , b , a } I want to make a comparison of each element in the list and insert the pair of common indexes into a List of array or something using javaexample output : [ [ 0,2,6 ] , [ 1,4 ] ] explanation : a is at indexes 0,2,6 and b is at indexes 1,4So far I have this : ... | HashMap < Integer , Integer > hashMap = new HashMap < Integer , Integer > ( ) ; List < String > name = new ArrayList < String > ( ) ; letter.add ( `` a '' ) ; letter.add ( `` b '' ) ; letter.add ( `` c '' ) ; letter.add ( `` b '' ) ; letter.add ( `` a '' ) ; for ( int i = 0 ; i < letter.size ( ) ; i++ ) { for ( int j =... | How to create a List of arrays using java |
Java | When I generate a stub ( using Eclipse Oxygen , top-down , Axis1 ) , the function are generated like these : Why is TokenRequest class kept intact , while BatchCommand and HttpHeaders are dismantled ? I tried adding more sub-elements under HttpHeaders and BatchCommand , but they just get split up as additional paramete... | public TokenNamespace.ideas.mace.TokenResponse getToken ( TokenNamespace.ideas.mace.TokenRequest tokenRequest ) throws java.rmi.RemoteException { return null ; } public TokenNamespace.ideas.mace.TokenResponse getToken2 ( TokenNamespace.ideas.mace.TokenRequest tokenRequest , boolean stopOnAnyError , TokenNamespace.ideas... | Top-down Web Service Generation using AXIS1 is taking my complexType apart |
Java | I wrote a piece of code and wonder how I can write it more elegant , using streamshere it is : Here - some boolean is returned from a method . If specified date already exists in some task it returns false , otherwise true ( so the return type answers the question raised in method 's name : ) ) I was trying with filter... | public boolean possibleToAddTask ( LocalDate taskDate , final String username ) { List < Task > userTasklist = find ( username ) .getTaskList ( ) ; for ( Task task : userTasklist ) { if ( task.getDate ( ) .equals ( taskDate ) ) { return false ; } } return true ; } public boolean possibleToAddTask ( LocalDate taskDate ,... | How to write it using streams ? Java 8 |
Java | Every now and then I find myself with indexed loops , for which I want to permutate the order to some random order.I usually transition from something liketo This is neither efficient nor elegant . Is it possible to create a Stream ( ideally an IntStream ) in a certain range , but have it return its elements shuffled ?... | for ( int i = 0 ; i < max ; i++ ) { // do stuff with i } List < Integer > indices = IntStream.range ( 0 , max ) .boxed ( ) toCollection ( ( ) - > new ArrayList ( max ) ) ) ; Collections.shuffle ( indices ) ; for ( int i = 0 ; i < max ; i++ ) { int index = indices.get ( i ) ; // do stuff with index } IntStream.range ( 0... | Random permutation of IntStream |
Java | I 'm working with Android Studio and I keep getting a problem I do n't know how to solve . I do n't know whether it 's a problem with Android Studio , with Java or a mistake a make.I have a class whose constructor is the following : I try to create an object of that class with the following lines : ( Of course , class ... | public MakeQuery ( Callable < ArrayList < ? extends A > ) { ... } Callable < ArrayList < B > > callable = new Callable < ArrayList < B > > ( ) { ... } ; MakeQuery makeQuery = new MakeQuery ( callable ) ; | < ? extends A > wo n't accept A 's child classes |
Java | I have a use case where I need to read a file and get the grouping of a sequence and a list of values associated with the sequence . The format of these records in the file are like sequence - val , example I want the output to be a map ( Map < String , List < String > > ) with the sequence as the key and list of value... | 10-A10-B11-C11-A 10 , [ A , B ] 11 , [ C , A ] Map < String , List < String > > seqCpcGroupMap = pendingCpcList.stream ( ) .map ( rec - > { String [ ] cpcRec = rec.split ( `` - '' ) ; return new Tuple2 < > ( cpcRec [ 0 ] , cpcRec [ 1 ] ) } ) .collect ( Collectors.groupingBy ( x- > x . ) ) Map < String , List < String >... | Grouping By without using a POJO in java 8 |
Java | Looking at the java.util.Collections.unmodifiableMap implementation ( OpenJDK 11 ) : My question is why does the implementation not do a check that the map passed might already be an UnmodifiableMap , something like this : Rather this question can be extended to all other un-modifiable collections , a simple check help... | /** * Returns an < a href= '' Collection.html # unmodview '' > unmodifiable view < /a > of the * specified map . Query operations on the returned map `` read through '' * to the specified map , and attempts to modify the returned * map , whether direct or via its collection views , result in an * { @ code UnsupportedOp... | Why does Collections.unmodifiableMap not check if the map passed is already an UnmodifiableMap ? |
Java | I need to get only the procedures using java DatabaseMetaData but this method returns also the functions ' names . | DatabaseMetaData dbmd=con.getMetaData ( ) ; ResultSet result = dbmd.getProcedures ( null , Ousername , null ) ; | Method to get only procedures from an oracle database using Java |
Java | I have two threads both of which accesses an Vector . t1 adds a random number , while t2 removes and prints the first number . Below is the code and the output . t2 seems to execute only once ( before t1 starts ) and terminates forever . Am I missing something here ? ( PS : Tested with ArrayList as well ) } Output : Ma... | import java.util.Random ; import java.util.Vector ; public class Main { public static Vector < Integer > list1 = new Vector < Integer > ( ) ; public static void main ( String [ ] args ) throws InterruptedException { System.out.println ( `` Main started ! `` ) ; Thread t1 = new Thread ( new Runnable ( ) { @ Override pub... | Writing to/Reading from a Vector ( or ArrayList ) with two threads |
Java | I 'm doing a project for a class which focuses on storing a huge matrix with mostly 0 values in memory and performing some matrix math on it . My first thought was to use a HashMap to store the matrix elements , and only store the elements which are non-zero , in order to avoid using huge quantities of memory.I wanted ... | public void Set ( double value , int row , int column ) { //assemble the long key , placing row and column in adjacent sets of bits long key = ( long ) row < < SIZE_BIT_MAX ; // ( SIZE_BIT_MAX is 32 ) key += column ; elements.put ( key , value ) ; } public void Set ( double value , int row , int column ) { //create a d... | Why is it that , the more ' 1 ' bits in my Key , the longer it takes to place in the HashMap ? |
Java | I would like to cater for devices running on jelly bean version and below as well as versions above Jelly Bean.My method is supposed to get app usage/traffic for all applications based on the application ID . Please take noteof this line rx = Long.parseLong ( String.valueOf ( id ) ) ; on the first if clause which cater... | public void recordSnapshot ( Context context ) { TinyDB settings = new TinyDB ( context ) ; int boot_id = settings.getInt ( AppPreferences.BOOT_ID ) ; PackageManager pm = context.getPackageManager ( ) ; for ( ApplicationInfo app : pm.getInstalledApplications ( 0 ) ) { String androidOS = Build.VERSION.RELEASE ; int curr... | Catering for devices running Jelly bean as well as versions later than Jelly bean when obtaining application data usage |
Java | I have two situations drawn up , and the strange differences between them are causing me a bit of grief . I will attempt to detail them below in code.Situation 1 : Situation 2 : Why , in situation one , is the runtime type of the parameter not used , but in situation two it is ? I understand that the examples are actua... | public void doSomething ( Object obj ) { //do something with obj } public void doSomething ( String str ) { //do something similar to str , but apply some custom //processing for String 's } Object o = new String ( `` s '' ) ; doSomething ( o ) ; // this will use the Object version ... class Dog { void makeSound ( ) { ... | Java -- Runtime typing differences |
Java | Can somebody tell me what does this mean ? I 'm going trough Java book and I 've encontered this example : What does Message ( ) { } Mean ? | public class Message { Message ( ) { } public Message ( String text ) { this.text = text ; } | Question about Java class constructor |
Java | I encountered this code wherein a method call , for example ClassA.search ( a , b , flag ) is being used by 3 Controllers . This is a simplified version of the method : Is this a good idea because code is reused ? Or is there a better way to still be able to make code reuse but not introduce this flag for method caller... | public List < Result > search ( Object a , Object b , boolean flag ) { //do some code logic here , common to the 3 controllers //at the middle there is : if ( flag ) { //code that affects 2 Controllers } else { //code affects only 1 } //some more common code //some more code with the flag if else } | Is this a good way to reuse / share a method ? |
Java | Is this a bug or a feature ? The DateTimeFormatter JavaDoc explicitly states that when I use the OOOO pattern in my formatter , the full form of localized timezone should be used ( emphasis mine ) : Four letters outputs the full form , which is localized offset text , such as 'GMT , with 2-digit hour and minute field ,... | DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( `` EEE yyyy.MM.dd HH : mm : ss.SSS OOOO '' ) ; String timestamp = OffsetDateTime.ofInstant ( Instant.now ( ) , ZoneOffset.UTC ) .format ( formatter ) ; System.out.println ( timestamp ) ; Mon 2019.02.25 22:30:00.586 GMT Mon 2019.02.25 22:30:00.586 GMT+00:00 | Why does the timezone pattern `` OOOO '' not show the full GMT+00:00 offset format ? |
Java | Basically question says it all.When I declare a function signature in gen-class , what type do I put for a 2D array of strings ? what do I put for XXXX ? Update : following @ Mark Topolnik 's suggestion , I 'm tryingin my declaration , and I 'm getting back a runtime exception when I try to compile it.Update 2 : Fixed ... | [ myFunc [ XXXX ] ReturnType ] # ^ { : static true } [ myFunc [ ^ '' [ [ Ljava.lang.String ; '' ] clojure.lang.IFn ] java.lang.RuntimeException : Unmatched delimiter : ] | How do I call a Clojure function that takes a two-dimensional array of Strings from Java ? |
Java | For the algorithm below : So for this algorithm , my thought process goes like this : The inner-loop performs n iterations for j when i=0 . However , for every value of i=0,1..n-1 , j will only perform one iteration because the if-statement will evaluate to true and end the inner-loop . Here is my source of confusion :... | int x = 0 ; for ( int i = 0 ; i < n ; i++ ) for ( j = 0 ; j < n ; j++ ) { if ( j < i ) j = j + n ; else x = x + 1 ; } | Misunderstanding small details w/ nested for-loop time complexity analysis ... How to tell O ( n ) and O ( n² ) apart |
Java | I have a list of pencils and a list of erasers . The goal it to check whether or not all the erasers can be put on pencils . An eraser may fit on multiple different pencils . Pencils can have at most 1 eraser . If I just loop through all the erasers and put them on pencils , I end up with erasers that fit no unoccupied... | public class Eraser ( ) { public boolean matches ( Pencil p ) { //unimportant } } public class Pencil ( ) { } public boolean doMatch ( List < Eraser > erasers , List < Pencil > pencils ) { for ( Eraser e : erasers ) { boolean found = false ; Iterator it = pencils.iterator ( ) ; while ( it.hasNext ( ) ) { Pencil p = ( P... | Matching algorithm |
Java | Why do I get an error when But not in this case | int i=123 ; byte b=i ; final int i=123 ; byte b=i ; | Why there is no error when a final int is assigned to a byte |
Java | In Eclipse Neon , if I write this Java code : I get no leak warnings , but if I implement Stream , such asand I write similar codeI get a Resource leak : 'stream ' is never closed warning . This happens only in Eclipse , while compiling with javac does not issue any warning.Note I 'm not looking for an answer on how to... | Stream < Object > stream = Stream.builder ( ) .build ( ) ; public class MyStream < T > implements Stream < T > { // implementation } Stream < Object > stream = new MyStream < > ( ) ; | Why does n't Eclipse show leak warning for streams ? |
Java | I 'm integrating with a payments processor and am trying to deal with the scenario where : user clicks pay and a request is made to our serverour server makes a request to the payment processorthere is a significant delay on the payment processor sideafter a certain threshold e.g . 60 seconds , we alert the user that t... | import javax.ws.rs.client . * ; import java.util.Timer ; import java.util.TimerTask ; ... boolean overThreshold = false ; int timeout = 60 ; // seconds TimerTask task = new TimerTask ( ) { @ Override public void run ( ) { overThreshold = true ; // return a message to user here saying their payment could not be processe... | Interrupt if API call to payment processor takes over 60 seconds |
Java | The requirement is to automate the java webstart process . After clicking the JNLP file , its loading and displaying the below imageThere is no option for trust always here . I am aware of in Java 7 Update 51 , java tighten the security . So I have signed jars with public code signing certificate provided by symantec ,... | Codebase : *Application-Library-Allowable-Codebase : * | Automate the webstart process |
Java | Recently I got a code review comment to use getter method for accessing private instance variable inside methods of same class . Is it really a good practice ? I feel that it is adding unnecessary complication in code . What is the recommended way ? | public class SomeClass { String abc ; public boolean compare ( SomeClass otherClass ) { otherClass.getAbc ( ) .equals ( abc ) ; } } public class SomeClass { String abc ; public boolean compare ( SomeClass otherClass ) { otherClass.getAbc ( ) .equals ( getAbc ( ) ) ; } } | Is it a good coding practice to use getter for accessing private instance variables |
Java | I need to print the number of times the chain method reoccurs . | private static int chain ( int n ) { int count = 0 ; while ( n > 1 ) { if ( n % 2 == 0 ) { count++ ; //the value is not stored return chain ( n/2 ) ; } count++ ; //same thing return chain ( 3*n+1 ) ; } return count ; //prints the initial value ( 0 ) } } | Any idea on how can I count the number of elements that verify an `` if '' condition ? |
Java | I 'll try to illustrate my problem in the following simplified example : Here I want to write generic method firstNotNull that returns DataHolder parametrized by common supertype of type parameter T of the this and other argument , so later I could write e.g . or The problem is that this definition of firstNotNull is r... | public class DataHolder < T > { private final T myValue ; public DataHolder ( T value ) { myValue = value ; } public T get ( ) { return myValue ; } // Wo n't compile public < R > DataHolder < R super T > firstNotNull ( DataHolder < ? extends R > other ) { return new DataHolder < R > ( myValue ! = null ? myValue : other... | How can I use both method and class type parameters in single constraint ? |
Java | I 'm working on a new project , where I want to display some data on the screen . I set myself to using TDD which is new for me , but I love the idea and get along quite OK so far.I set up a JFrame , add a Textarea and put text there , but how can I properly test this ? Or is this wrong thinking in the TDD context on m... | public class MyTextDisplay { public static void main ( String [ ] args ) { JFrame my_frame = new JFrame ( `` DisplaySomeText '' ) ; my_frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE ) ; JTextArea textArea = new JTextArea ( 5 , 20 ) ; textArea.setEditable ( false ) ; my_frame.add ( textArea ) ; my_frame.setVisibl... | How to TDD a JFrame ? |
Java | If i autowire my generic class with different types in different controllers , does spring container create new instance for each ? Assume i have a generic class.In a controller i use and in another controller i use | @ Componentclass MyClass < T , K > { public K doStuff ( T t ) { // some logic here } } @ AutowiredMyClass < Employee , Integer > myClass ; @ AutowiredMyClass < Manager , String > myClass ; | Does spring container create new beans for the objects which belong to same generic class but use different types ? |
Java | So as it goes in the current scenario , we have a set of APIs as listed below : Over these , one of our schedulers performs the tasks e.g.While reviewing this , I thought of moving to a more flexible implementation 1 of performing tasks which would look like : The point that strikes my mind now is that the Javadoc clea... | Consumer < T > start ( ) ; Consumer < T > performDailyAggregates ( ) ; Consumer < T > performLastNDaysAggregates ( ) ; Consumer < T > repopulateScores ( ) ; Consumer < T > updateDataStore ( ) ; private void performAllTasks ( T data ) { start ( ) .andThen ( performDailyAggregates ( ) ) .andThen ( performLastNDaysAggrega... | Order guarantees using streams and reducing chain of consumers |
Java | I have created one service and broadcast receiver to get telephony state . Below is my code : I am facing below two issues1 ) i have printed log in code for different states , but all states are printing multiple times and audio file is also created multiple times for same call.2 ) if once i kill the app and start agai... | @ Override public int onStartCommand ( Intent intent , int flags , int startId ) { final IntentFilter filter = new IntentFilter ( ) ; filter.addAction ( ACTION_OUT ) ; filter.addAction ( ACTION_IN ) ; if ( br_call == null ) { br_call = new CallBr ( ) ; registerReceiver ( br_call , filter ) ; } return super.onStartComma... | Call recording , call multiple ( repetitive ) telephonic stages and creates multiple audio files |
Java | The question is : Why in this case i get compilation error in Java ? But this is legal : I use eclipse , jdk 7.Thank You | byte x = 0 ; x = 128 ; x+= 999l ; | Java operators interesting issue |
Java | I 've recently started benchmarking some Java code in order to get the best performance results for my program and noticed some strange thing . Namely , I 've benchmarked the following methods : and got those results : After searching over SO ( i.e . Is Math.max ( a , b ) or ( a > b ) ? a : b faster in Java ? ) it was ... | private static final int n = 10000 ; public static void test0 ( ) { int m = 0 ; for ( int i = 0 ; i < n ; ++i ) { m = Math.max ( i , m ) ; } } public static void test1 ( ) { int m = 0 ; for ( int i = 0 ; i < n ; ++i ) { m = ( ( i > = m ) ? i : m ) ; } } | Test 0 | Test 1 | -- -- -- -- -- + -- -- -- -- -- -- -- -- -+ --... | Why does inlining Math.max give over 200x slower code ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.