lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I am new to Java and working on a problem where I need to group and aggregate a collection based on the below Matching key , this key is a combination of properties from below mentioned classes.The DailyOCF collection is populated in an ArrayList , sample data provided below.The above list needs to be grouped based on ... | class MyKey { String planYearMonth ; String carSeries ; String weekNo ; String factoryCode ; String lineClass ; String frameSortCode ; String ocfClassificationCode ; String locationIdentificationCode ; String carGroup ; //setters & getters //equals & hashcode } public class OCFIdentificationInfo { private String frameS... | Group and Aggregate by multiple properties based on complex matching key |
Java | I am a bit new to LinkedList and I want to practice by making methods in ExampleLinkedList class . There is a list in test3 . When I call test3 I get Goodbye Thanks Hello . What I want is to add `` AddedItem '' in the end of the list to get AddedItem Goodbye Thanks Hello but I get only AddedItem as a result . How can I... | public class ExampleLinkedList { private String data ; private ExampleLinkedList next ; public ExampleLinkedList ( String data , ExampleLinkedList next ) { this.data = data ; this.next = next ; } public void addToEnd ( String item ) { while ( next ! = null ) { data = item ; next.data = data ; next = next.next ; } } pub... | Adding a Object to End of a Linked List in One Class |
Java | To write a good comparations test test you have to run it several thousands ( millions ) times . It will level ( in most cases ) other programs ' influence . But if a JVM can influence on the results . For example : First solution is : And second is : I do not know which one is better because JVM can influence on the r... | final StringBuilder stringBuilder = new StringBuilder ( ) ; stringBuilder.append ( getStrOne ( ) ) ; stringBuilder.append ( getStrTwo ( ) ) ; final String result1 = stringBuilder.toString ( ) ; final String result2 = getStrOne ( ) + getStrTwo ( ) ; | How do to perform a good performance comparations test ? |
Java | Which Java synchronisation object should I use to ensure an arbitrarily large number of tasks are completed ? The constraints are that : Each task takes a non-trivial amount of time to complete and it is appropriate to perform tasks in parallel.There are too many tasks to fit into memory ( i.e . I can not put a Future ... | let workQueue = dispatch_get_global_queue ( QOS_CLASS_BACKGROUND , 0 ) let latch = dispatch_group_create ( ) let startTime = NSDate ( ) var itemsProcessed = 0let countUpdateQueue = dispatch_queue_create ( `` countUpdateQueue '' , DISPATCH_QUEUE_SERIAL ) for item in fetchItems ( ) // generator returns too many items to ... | Synchronisation object to ensure all tasks are completed |
Java | I 'm not exactly sure why this causes a stack overflow . I know if I call the someMethod method without the instance it works fine , but I 'd like to know why.Thanks | class test { public static void main ( String [ ] args ) { test item = new test ( ) ; item.someOtherMethod ( ) ; } test item2 = new test ( ) ; void someOtherMethod ( ) { item2.someMethod ( ) ; } void someMethod ( ) { System.out.println ( `` print this '' ) ; } } | why does this object cause a stack overflow ? |
Java | I have some output from a ( C++ ) application that stores a tickcount value in a type that wraps to zero at 233 . ( 8,589,934,592 ) ( Do n't have the code ) I need to write my own output in the same way . I retrieve the tickcount from a C lib through JNA , but if I store it in an int it wraps to -231 ( -2,147,483,648 )... | import com.sun.jna . * ; public interface Kernel32 extends Library { Kernel32 INSTANCE = ( Kernel32 ) Native.loadLibrary ( ( Platform.isWindows ( ) ? `` kernel32 '' : `` c '' ) , Kernel32.class ) ; /** * Retrieves the number of milliseconds that have elapsed since the system was started . * * @ return number of millise... | Simulating unsigned number with a certain power of two max in java |
Java | Below is the parent class DblyLinkListBelow is the derived class LockableList , If class LockableNode < T > extends DListNode < T > in the above code , error : The constructor DblyLinkList < T > .DListNode < T > ( T , DblyLinkList < T > .DListNode < T > , DblyLinkList < T > .DListNode < T > ) is undefined occurs at lin... | package JavaCollections.list ; import java.util.Iterator ; import java.util.NoSuchElementException ; public class DblyLinkList < T > implements Iterable < T > { class DListNode < T > { private T item ; private DListNode < T > prev ; private DListNode < T > next ; DListNode ( T item , DListNode < T > p , DListNode < T >... | How to inherit parent 's inner class in this code ? |
Java | The simplest code to demonstrate the issue is this : Main interface in Kotlin : Abstract class implementing it and the method : Java class : It should work , but it does n't . The error is Class 'JavaImpl ' must either be declared abstract or implement abstract method 'go ( T ) ' in 'Base'If the JavaImpl class was in K... | interface Base < T : Any > { fun go ( field : T ) } abstract class Impl : Base < Int > { override fun go ( field : Int ) { } } public class JavaImpl extends Impl { } | Extending Kotlin class by Java requires me to reimplement already implemented method |
Java | there is an error on the last line this looks perfectly fine to me , but maybe i am missing some subtlety on how type wildcards work . Is there a way i can change the type on the last line ? i need this reference because i plan on doing this later : this also has an errorhowever , if i use it without the wildcards and ... | interface A { String n ( ) ; } class B implements A { @ Override public String n ( ) { return `` asdf '' ; } } interface C < T extends A > { T m ( T t ) ; } class D implements C < B > { @ Override public B m ( B b ) { return b ; } } Class < C < ? extends A > > x = D.class ; Type mismatch : can not convert from Class < ... | why doesnt this type wildcard work ? |
Java | I 'm using the following code to convert a hexadecimal String to a floating point String : To test this , I wrote the following JUnit test : However , the 2nd assertion fails . According to various online converters like this one , 50000000 should be converted to 8589934592 but Java returns 8589934600.Which result is c... | private static String removeScientificNotation ( float value ) { return new BigDecimal ( Float.toString ( value ) ) .toPlainString ( ) ; } /** * Converts a hexadecimal value to its single precision floating point representation * * @ param hexadecimal The < code > hexadecimal < /code > to convert * @ return The convert... | Hexadecimal - > Float Conversion Inaccurate |
Java | I am trying to track down why a specific behavior is happening with .orElseThrow in a Java Stream . This code block results in this error : unreported exception X ; must be caught or declared to be thrownI do n't want to report the exception because that would cause me to add that to every other method who interacts wi... | private SomeContainer getSomeContainerFromList ( SomeContainerList containerList , String containerId ) { return containerList.stream ( ) .filter ( specificContainer - > specificContainer.getId ( ) .equals ( containerId ) ) .findAny ( ) .orElseThrow ( ( ) - > { String message = `` some special failure message '' ; log.... | Java8 Stream .orElseThrow unreported exception error |
Java | I have a list of `` Item '' objects list like : Is there a way to `` unpack '' those object using streams to have a list of items eventually repeated if qty is greater than 1 so at the end I 'll have objects with qty equals to 1 ? | public class Item { private String name ; private int qty ; public Item ( ) { } public Item ( String name , int qty ) { this.name = name ; this.qty = qty ; } public List < Item > unpack ( ) { List < Item > items = new ArrayList < > ( ) ; items.add ( new Item ( `` foo '' , 2 ) ) ; items.add ( new Item ( `` bar '' , 3 ) ... | Java stream how to unpack a object with quantity to list of single object |
Java | I 'm writing a java program that print seconds elapsed , and every 5th second it will print a message . This is a sample output : How can I remove the boolean variable printMsg ? Is there a better thread design that allow this ? For now , without printMsg the program will print multiple `` hello '' during the 1/10 seco... | 0 1 2 3 4 hello 5 6 7 8 9 hello 10 11 12 13 14 hello 15 16 17 18 19 hello class Timer { private int count = 0 ; private int N ; private String msg ; private boolean printMsg = false ; public Timer ( String s , int N ) { msg = s ; this.N = N ; } public synchronized void printMsg ( ) throws InterruptedException { while (... | Multiple threads with notifyAll ( ) |
Java | Given this code ... Imagine that instead of this while ( true ) you have something that does not throw interrupted execution ( for example , a recursive function that actually calculates something ) .How do you kill this thing ? And why is it not dying ? Note if I do n't put Exception type there and use InterruptedExce... | public class SimpleTest { @ Test public void testCompletableFuture ( ) throws Exception { Thread thread = new Thread ( SimpleTest : :longOperation ) ; thread.start ( ) ; bearSleep ( 1 ) ; thread.interrupt ( ) ; bearSleep ( 5 ) ; } public static void longOperation ( ) { System.out.println ( `` started '' ) ; try { boole... | Impossible to interrupt thread if its actually computing ? |
Java | This is from Thinking in JavaHere is my Java enviroment : java version `` 1.8.0_60 '' Java ( TM ) SE Runtime Environment ( build 1.8.0_60-b27 ) Java HotSpot ( TM ) 64-Bit Server VM ( build 25.60-b23 , mixed mode ) | class Snow { } class Powder extends Snow { } class Light extends Powder { } class Heavy extends Powder { } class Crusty extends Snow { } class Slush extends Snow { } public class AsListInference { public static void main ( String [ ] args ) { //The book says it wo n't compile , but actually it does . List < Snow > snow... | Why is there no type conversion exception in this code ? |
Java | Java is smart enough to determine whether an integer is small enough to be converted to a character . Why is it not able to convert very small floating point literals to a float ? . For example : char c = some integer literal might compile but float f = some floating point literal will never compile . Why ? PS : I know... | char c1 = 123 ; //Compiles finechar c2 = 123456 ; //Error : can not convert from int to char float f1 = 0.3 ; //Error : can not convert from double to floatfloat f2 = 0.3f ; //Compiles fine | char c = some integer literal might compile but float f = some floating point literal will never compile . Why ? |
Java | I have following code : Eclipse gives a `` dead code '' warning on the return null ; . Removing the test for keyValue == null also removes the warning but I do n't see how that extra test makes the return statement dead code . Clearly if the map contains no entry for some non-null keyValue , then rowIndex can still be ... | public String myMethod ( String keyValue ) { Map < String , Integer > keyValueToRowIndex = ... Integer rowIndex = ( keyValue == null ) ? 0 : keyValueToRowIndex.get ( keyValue ) ; if ( rowIndex == null ) return null ; ... } | Eclipse gives dead code warning for reachable code ( variant ) |
Java | I am looking to select a design pattern for a project I am working on and was wondering if I can get some input . BackgroundAn interface called Ranker is defined as follows . Each implementation of Ranker can have multiple Rankers as member variables and each of the member Rankers can have multiple Rankers as their mem... | interface Ranker < T > { public void rank ( List < T > item ) ; } RankerForTypeA RaknerForTypeB RankerForTypeC RankerForTypeD RankerForTypeE RankerForTypeF RankerForTypeG RankerForTypeH RankerForTypeI RankerForTypeJ RankerForTypeK ... interface RankerFactory { Ranker < A > getRankerForA ( paramsForA ) ; Ranker < B > ge... | Dilemma while selecting a design pattern |
Java | In my study book , there 's this example : I find it strange that it compiles , since there is no definition of Class < T > . What is the story about this ? It says in my book that T is for the type parameter but how do I know when to use it ? | import java.util . * ; public class RentalGeneric < T > { private List < T > rentalPool ; private int maxNum ; public RentalGeneric ( int maxNum , List < T > rentalPool ) { this.maxNum = maxNum ; this.rentalPool = rentalPool ; } public T getRental ( ) { return rentalPool.get ( 0 ) ; } public void returnRental ( T retur... | How to understand this use of Java generics |
Java | I am making a program in which a pool of x number of threads interacts with a shared inventory . In this case I use an ArrayList as the shared inventory . In my program the threads are representations of jobs that a creature has . Creatures belong to a party and share a pool of Artifacts used to perform jobs . only one... | boolean ready = target.hasReqArtifacts ( reqStones , reqPotions , reqWands , reqWeapons ) ; //checks to see if creature already has correct amount of each item . //If it does it should skip pool interaction until it dumps its used items //back into the pool . System.out.println ( `` Ready : `` + ready ) ; while ( ! rea... | Threads not communicating |
Java | I have the following class.What is the -keep option that will ensure the constructor wo n't be removed by Proguard ? The following will keep the constructor ; however , I do n't want to have to specify every single class or package . | public class StatusCategory { @ JsonProperty ( `` key '' ) private final String m_key = null ; public String getKey ( ) { return ( m_key ) ; } } -keep class oracle.psr.ndr.jira.api.StatusCategory { < init > ; } | Keep constructor if field annotated |
Java | I have two corresponding lists : The goal is to sum discounts , which means adding discountRate from actualPromotions to discountRate value from the booksToReturn list . The objects from both lists can be matched by idOfBook.This is how I solved it I 'm just exploring streams and I think my solution is clumpy . How wou... | public class BookOverallData { private Long idOfBook ; private String title ; private String authour ; private BigDecimal basePrice ; private Integer discountRate ; } public class TimeDiscount { private Long idOfBook ; private Integer discountRate ; } Set < BookOverallData > booksToReturnSet < TimeDiscount > actualProm... | Update objects in one list based on values from second one using streams |
Java | I want to be able to write an aspect to detect when I am casting something in one of my org.mypackage classes.How do you write a pointcut to express the casting operation , not just for Foo class , but for any class in org.mypackage ? Background : So Hibernate 5 + Spring Data JPA requires casting entities with inherita... | package org.mypackage ; class Foo { public static void main ( String [ ] args ) { Bar casted = ( Bar ) args [ 0 ] ; // want to detect this casting action ! } } if ( isInstanceOfMyEntity ( someEntity ) ) { // formerly , this was sufficient : // MyEntity myEntity = ( MyEntity ) someEntity ; // now , this is required *eve... | AOP To Detect All Class Casts For Hibernate.unproxy ( ) |
Java | It says I 'm supposed to write : On the settings.gradle file according to : https : //docs.gradle.com/enterprise/gradle-plugin/But then I get an error saying:2 : Only Project build scripts can contain plugins { } blocks | plugins { id `` com.gradle.enterprise '' version `` 3.5 '' } gradleEnterprise { server = `` https : //gradle-enterprise.mycompany.com '' } | I ca n't apply the gradle 6.x plugin |
Java | Here , my main goal is setting the value safely , without having a performance ( speed , memory , cpu etc ) impact.I have a silly option ( in a bad style ) also mentioned below . So , what is the best way to do this ? option 1 ? option 2 ? or another one ? Option 1 : Option 2 : Note : this piece of code is in a loop ha... | if ( animalData ! =null & & animalData.getBreedData ( ) ! =null & & dogx.getBreed ( ) ! = null & & dogx.getBreed ( ) .getBreedCode ( ) ! = null & & animalData.getBreedData ( ) .get ( dogx.getBreed ( ) .getBreedCode ( ) ) ! = null ) { dogx.getBreed ( ) .setBreedId ( animalData.getBreedData ( ) .get ( dogx.getBreed ( ) .... | Using try-catch over if conditions to safely set values with minimum performance impact in java |
Java | ProblemI am writing automated tests for my company 's website using Java and Selenium . Right now I am writing tests that involve clicking on links , and verifying that the link leads to the correct place . We have a newsletter popup ( from BounceExchange ) that appears at very unpredictable times , and it 's causing E... | public void click ( By elementBy ) { By bounceExchange = By.className ( `` bx-slab '' ) ; By bounceExchangeClose = By.className ( `` bx-close '' ) ; //close bouncex if its open if ( elementExists ( bounceExchange ) ) { WebElement bounceX = driver.findElement ( bounceExchange ) ; if ( bounceX.isDisplayed ( ) ) { System.... | How do I stop email newsletter popup from intercepting clicks ? |
Java | I 'm writing a library method that will be used in several places . One of the method 's parameters is a collection of objects , and the method does not mutate this collection . Should the method signature specify a mutable or immutable collection ? Option 1 : mutable collection as parameterPros : Clients can pass in w... | public static void foo ( List < Bar > list ) { // ... } public static void foo ( ImmutableList < Bar > list ) { // ... } | Preferring mutable or immutable collections as method parameters |
Java | I am getting the below error : Monitor.javaWebScoutCallable.javaContainsMonitor.javaI 'll freely admit that I 'm new to generics and still quite new to Java itself . I find the error message confusing as it looks like it should work ( method declaration expects a Monitor or subclass , I 'm passing in a subclass ) . Any... | 'call ( ContainsMonitor ) ' can not invoke 'call ( ? extends webscout.Monitor ) ' in 'WebScoutCallable ' WebScoutCallable < ? extends Monitor > handler ; public setCallable ( WebScoutCallable < ? extends Monitor > callable ) { this.handler = callable ; } public interface WebScoutCallable < T extends Monitor > { public ... | Why does this method call fail ? ( Generics & wildcards ) |
Java | My code is : The output is I really have no idea why only c [ 0 ] has changed . | public class MyProgram { public void start ( ) { int a = 1 ; int [ ] b = { 1 , 2 , 3 } ; int [ ] c = { 1 , 2 , 3 } ; method1 ( a , b [ 0 ] , c ) ; System.out.println ( `` a = `` + a ) ; System.out.println ( `` b [ 0 ] = `` + b [ 0 ] ) ; System.out.println ( `` c [ 0 ] = `` + c [ 0 ] ) ; } private void method1 ( int x ,... | I cant figure out how this void method works |
Java | Let 's say my original Map contains the following : And I want to create a reversed Map containing the following : I know it can be done in old fashion ( pre-Java 8 ) , but how do I achieve the same using Java Stream API ? There 's similar question posted here , but that only works for single valued Maps . | Map < String , Set < String > > original = Maps.newHashMap ( ) ; original.put ( `` Scott '' , Sets.newHashSet ( `` Apple '' , `` Pear '' , `` Banana '' ) ; original.put ( `` Jack '' , Sets.newHashSet ( `` Banana '' , `` Apple '' , `` Orange '' ) ; `` Apple '' : [ `` Scott '' , `` Jack '' ] `` Pear '' : [ `` Scott '' ] ... | How to create a reverse map when original map contains collection as the value ? |
Java | This is a piece of code in a SCJP practice question : It was partly mentioned here.However , my question is not the prior question . As I run the program on a few machines multiple times , I occasionally get RuntimeException before `` run '' in the output . This does not make sense to me , as these lines of codes execu... | public class Threads2 implements Runnable { public void run ( ) { System.out.println ( `` run . `` ) ; throw new RuntimeException ( `` Problem '' ) ; } public static void main ( String [ ] args ) { Thread t = new Thread ( new Threads2 ( ) ) ; t.start ( ) ; System.out.println ( `` End of method . `` ) ; } } | Codes on the same thread executed in unusual order |
Java | Please look at this code : result:console print: 0 9 I know that subclass will first calls the superclass constructorbut , why is the 0 9 , not 8 9 ? | class Sup { int a = 8 ; public void printA ( ) { System.out.println ( a ) ; } Sup ( ) { printA ( ) ; } } public class Sub extends Sup { int a = 9 ; @ Override public void printA ( ) { System.out.println ( a ) ; } Sub ( ) { printA ( ) ; } public static void main ( String [ ] args ) { Sub sub = new Sub ( ) ; } } | Java - extends why the super variable a is 0 |
Java | Here 's the snippet : As the code above , Even if we put LoggerThread.interrupt ( ) in stop ( ) method , the interruption just be caught by thread and do nothing.So is LoggerThread.interrupt ( ) necessary ? | public class LogService { public void stop ( ) { synchronized ( this ) { isShutdown = true ; } loggerThread.interrupt ( ) ; /* Is it necesarry ? */ } public void log ( String msg ) throws InterruptedException { synchronized ( this ) { if ( isShutdown ) throw new IllegalStateException ( ... ) ; ++reservations ; } queue.... | Is this interrupt ( ) necessary ? |
Java | I 've seen plenty of ways to sort a list of objects that work fine if you know the incoming keys or at least the incoming number of keys.Problem is in my case I do n't know if the user will send in 1 or 10 keys.Currently I have a giant switch statements for each number of keys , but obviously that scales terribly . It ... | https : //host.com/path ? sort= [ { `` attribute1 '' : `` ASC '' } , { `` attribute2 '' : `` DESC '' } ] | Sort a list of objects based on an unknown number of keys |
Java | output : 1121output : 4 4 5 5For above code why both objects are not referring to same memory location . | public static void main ( String [ ] args ) { Integer a = 1 ; Integer b = 0 ; b=a ; System.out.println ( a ) ; System.out.println ( b ) ; ++a ; System.out.println ( a ) ; System.out.println ( b ) ; } public static void main ( String [ ] args ) { ArrayList < Integer > a = new ArrayList < Integer > ( ) ; ArrayList < Inte... | Copying one object to another Object is yielding different results in java |
Java | Need to find out if a given string contains just a particular digit only - e.g . `` 111 '' , `` 2 '' , `` 33 '' should return true . `` 12 '' should return false.Empty string ( `` '' ) should also return true.The string contains only digits and no other characters.Wrote an ugly Java regex that seems to work , but ca n'... | str.matches ( `` 1*|2*|3*|4*|5*|6*|7*|8*|9*|0* '' ) | Check if string contains a particular digit only ( e.g . `` 111 '' ) |
Java | Create a class likeand it compiles in Java 8 ! ( Both in Eclipse 4.5 and JDK1.8_25 ) https : //ideone.com/Q9JLHPIn Eclipse , all the bounds are inferred correctly , but how could outer 's capture Supplier < ? super Integer > ever been satisfied by the argument Supplier < String > ? ? Edit : clarified this is Java 8-spe... | public class Play { public static void main ( String [ ] args ) throws Exception { outer ( Integer.class , inner ( `` abc '' ) ) ; } static < C > void outer ( Class < C > c , List < ? super C > s ) { } static < C > List < C > inner ( C c ) { return null ; } } | Type checking broken on matching capture with upper bound ? |
Java | I have a Java thread with a run method that computes many things . You can think of it as a series of math statements as follows . Note that each computation may utilize other methods that in turn might have additional loops and such.There is a GUI that prints the output of these statements as they produce their result... | public void run ( ) { [ computation 1 goes here here that takes a few seconds ] [ computation 2 goes here that takes a few seconds ] ... . [ computation 30 goes here that takes a few seconds ] } private boolean stop ; public void run ( ) { if ( ! stop ) [ computation 1 goes here here that takes a few seconds ] if ( ! s... | Java - terminating a method within a Thread |
Java | I have an interface A like this : And then I have this class : I have n't use generics before ( only things like List < String > ... ) so I ca n't see why this code does n't compile . To be more precise , I get an error on the line elements.add ( obj ) ; that the method add is not applicable for these parameters.EDIT :... | public interface A { void myFirstMethod ( ) ; void mySecondMethod ( ) ; } public class MyClass { private List < ? extends A > elements ; public MyClass ( ) { A obj = new A ( ) { @ Override public void myFirstMethod ( ) { //SOME CODE } @ Override public void mySecondMethod ( ) { //SOME CODE } } ; elements.add ( obj ) ; ... | Java using Generics |
Java | I 've a query as follows ... That I 've achieved through , Creating a connection , statement & executing the query as followsBut , now I need to find whether the code had performed an INSERT or UPDATE ? Can anyone help me with this ? ? Thanks in advance ... | INSERT INTO MYTABLE ( f1 , f2 , f3 , f4 ) VALUES ( 1,2,3,4 ) ON DUPLICATE KEY UPDATE f4=5 ; statement.execute ( query ) ; | Finding wheather the mysql query performed a update or insert |
Java | Let 's say I 'm using Java 11 javac , but I 'm using the -- source and -- target options set to 1.8 so that my source code will be considered Java 8 and the output .class files will be compatible with Java 8 . My goal is to produce .class files that can run on a Java 8 JVM.And let 's say I have the following Java 8 cod... | import java.nio.ByteBuffer ; …ByteBuffer byteBuffer = … ; //init somehowbyteBuffer.flip ( ) ; //what ends up in the ` .class ` file ? @ Overridepublic ByteBuffer flip ( ) { super.flip ( ) ; return this ; } | How should javac 11 link methods overridden in later versions with a Java 8 target ? |
Java | I have a document that says the average case time-complexity for the given code is O ( nlog2n ) I have computed the best and worst cases as : Best case , k = n leading to time complexity of O ( 1 ) . Worst case , k = 1 leading to time complexity of O ( n ) . How can average case be O ( nlog2n ) , which is higher than t... | Random r = new Random ( ) ; int k = 1 + r.nextInt ( n ) ; for ( int i = 0 ; i < n ; i += k ) ; | time complexity : why O ( nlogn ) ? |
Java | Can you explain me why the result is `` int '' ? I would expect it to be `` long '' provided the variable is a byte . | public class Test { public static void printValue ( int i , int j , int k ) { System.out.println ( `` int '' ) ; } public static void printValue ( byte ... b ) { System.out.println ( `` long '' ) ; } public static void main ( String ... args ) { byte b = 9 ; printValue ( b , b , b ) ; } } | Java Primitive Widening Interview |
Java | In situations such as the one above , I like to put the else in the end so I can be notified if the program runs code it should n't run , meaning something went wrong ( i.e . one of the above conditions should be true , but none are , which means something is wrong ) .What exception should I throw in that final else , ... | if ( stuff ) doThings ( ) ; else if ( something ) doOtherThings ( ) ; else if ( otherStuff ) doStuff ( ) ; else // .. this is n't supposed to be reached | What exception should I throw when code which is n't supposed to run is run ? |
Java | We knows that TPL ( so PLINQ too ) does n't consume all cores if he think that task is easy and executes it on single core . But he does it even for a complicated task ! For example , here is code from article about Java parallelism : and results : you can see that multithreaded version executed ~19 times faster than s... | import org.openjdk.jmh.infra.Blackhole ; import org.openjdk.jmh.annotations . * ; import java.util.concurrent.TimeUnit ; import java.util.stream.IntStream ; import java.math.BigInteger ; @ Warmup ( iterations=5 ) @ Measurement ( iterations=10 ) @ BenchmarkMode ( Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.MICROSECON... | What heuristic uses TPL to determine when to use multiple cores |
Java | I have a rather peculiar problem . I 'm trying to find a pattern like [ some string ] [ word boundary ] . Simplified , my code is : My logic tells me this should always output true , regardless of what someString is . However : if someString ends with a word character ( e.g . `` abc '' ) , true is outputted ; if someSt... | final Pattern pattern = Pattern.compile ( Pattern.quote ( someString ) + `` \\b '' ) ; final String value = someString + `` `` ; System.out.println ( pattern.matcher ( value ) .find ( ) ) ; | \b does n't match when the preceding character is a word boundary |
Java | I would like to know how to shorten my code with the help of Stream Api.Let 's say I have method like this : And I would like to call this method 5 times with the same parameters . For exampleI know I can do something like this : But here I am passing one integer value to method . Anyone can give me some hints or answe... | public static void createFile ( String directoryPath , String fileName ) for ( int i = 0 ; i < 5 ; i++ ) { Utils.createFile ( getDirectoryLocation ( ) , `` test.txt '' ) ; } IntStream.rangeClosed ( 1 , 5 ) .forEach ( Utils : :someMethod ) ; | How to use stream api for repeatable actions |
Java | I realize that the results for string1.compareTo ( string2 ) will be a number -1 or below if string2 comes before string1 alphabetically , and a number 1 or above if different the other direction . I need to return only -1 , 0 , or 1 . I can code it in a seemingly clunky way , but I feel like there must be a more effic... | String s1 = `` aardvark '' ; String s2 = `` zebra '' ; int c = s1.compareTo ( s2 ) ; // -25if ( c > 0 ) { c = 1 ; } else if ( c < 0 ) { c = -1 ; } String s1 = `` '' ; String s2 = `` m '' ; for ( int i = 0 ; i < 100 ; i++ ) { for ( char j = ' a ' ; j < ' z ' ; j++ ) { s2 = ( `` '' + j ) ; solution1 ( s1.compareTo ( s2 )... | How can I best restrict String.compareTo ( ) results to -1 , 0 , and 1 ? |
Java | I have an enum class which has several constants , and I want to add some static value FOCUSED which indicates which of the enum values has focus ... I found a way : However , now I wonder : Did I just mess with the enum class ? Because I do n't want FOCUSED to be selectable when specifying the message type , however a... | package messagesystem ; /** * * @ author Frank */public enum MessageType { ALL , GENERAL , SEND , RECEIVE , LOG , EXCEPTION , DEBUG , PM ; public final static MessageType FOCUSED = GENERAL ; private final String value ; MessageType ( ) { String firstLetter = name ( ) .substring ( 0 , 1 ) ; String otherLetters = name ( ... | Enum : Did I just do something unwanted ? |
Java | I 'm curious if there 's a syntactic way to extend JSONArray such that I can then use it in a for ( : ) loop as I can a List.So , instead of having to do : I would like to doI realize that I need to make sure that in the above example the object in the array is indeed a String , but given that JSONArrays can only handl... | for ( int i = 0 ; i < myJsonArray.length ( ) ; i++ ) { myJsonArray.getString ( i ) ; } for ( String s : myJsonArray ) ; | Is there a way to overload JSONArray to behave like a regular List in a loop ? |
Java | Hey if anyone has an idea I would be really thankfull.I 'm in a Java stream and i would like to sort my list that i 'll be returning.I need to sort the list via TradPrefis ( MyObject : :getTradPrefix ) .But this would be way too easy . Because i want to sort following the number at the end of TradPrefix exampleTradPref... | public LinkedHashSet < WsQuestion > get ( String quizId , String companyId ) { LinkedHashSet < QuizQuestionWithQuestion > toReturn = quizQuestionRepository.findAllQuizQuestionWithQuestionByQuizId ( quizId ) ; return ( toReturn.stream ( ) .map ( this : :createWsQuestion ) .sorted ( comparing ( WsQuestion : :getTradPrefi... | Private Sorting Rule in a Stream Java |
Java | I 'm currently working on my Bachelor Thesis about how to write effective Java code . The following four code snippets are part of a JMH benchmark which will execute every method 1 million times each.The results for this four methods are : primitiveOnly : 1.7 ms/operationprimitiveToWrapper : 2.2 ms/operationwrapperToPr... | public final static int primitiveOnly ( int dummy , int add1 , int add2 ) { for ( int i = 0 ; i < 10 ; i++ ) { dummy += ( add1 + add2 ) ; } return dummy ; } public final static int primitiveToWrapper ( int dummy , int add1 , Integer add2 ) { for ( int i = 0 ; i < 10 ; i++ ) { dummy += ( add1 + add2 ) ; } return dummy ;... | How does Java decide which operator in a math expression has to be ( un ) boxed ? |
Java | I 'm working on a game where you can upgrade your stats in a shop . When you buy something it should refresh the JLabel which shows your CoinsIs there a way to do that without doing a new JFrame ? This is the code of the ActionListener where I want to refresh the JFrame epixHere 's the code of the View | public void actionPerformed ( ActionEvent e ) { user.setCoin ( user.getCoin ( ) - 5 ) ; user.setMaxJump ( 5 ) ; EpixController.getInstance ( ) .coinsUpdate ( user , -5 ) ; SwingUtilities.updateComponentTreeUI ( epix ) ; epix.revalidate ( ) ; epix.repaint ( ) ; } public EpixView ( User user ) { this.setUser ( user ) ; J... | refresh JFrame Java without doing new JFrame |
Java | I have an user story in Rally which has a feature set as parent . I want to update the parent artifact via Java API to another user story . However I am getting a validation error while doing so i.e . I added following property to include in the UpdateRequest : How to override this validation , can anyone please help ? | Validation error : HierarchicalRequirement.parentArtifact should not be set if HierarchicalRequirement.Parent is set and vice versa JsonObject obj = new JsonObject ( ) ; jsonObject.addProperty ( `` Parent '' , `` < Parent User story ref > '' ) ; UpdateRequest updateRequest = new UpdateRequest ( `` < Child User story re... | Unable to update user story in Rally via Java API |
Java | Java 8 's String.replaceAll ( regexStr , replacementStr ) does n't work when the regex given is `` .* '' . The result is double the replacementStr . For example : I know replaceAll ( ) does n't exactly make sense to use when the regex is `` . * '' , but the regex is n't hardcoded and could be other regex strings . Why ... | String regexStr = `` . * '' ; String replacementStr = `` REPLACEMENT '' String initialStr = `` hello '' ; String finalStr = initialStr.replaceAll ( regexStr , replacementStr ) ; // Expected Result : finalStr == `` REPLACEMENT '' // Actual Result : finalStr == `` REPLACEMENTREPLACEMENT '' | Why does String.replaceAll ( `` . * '' , `` REPLACEMENT '' ) give unexpected behavior in Java 8 ? |
Java | I used this Topic I try this code but did not work : PACKAGE_NAME = context.getApplicationContext ( ) .getPackageName ( ) ; But it could not help me . I have the application list , I want to get the permission that used on each of them.How can I handle it ? UPDATE : like the photo , When clicking on `` دسترسی ها '' , I... | try { pi = context.getPackageManager ( ) .getPackageInfo ( PACKAGE_NAME , PackageManager.GET_PERMISSIONS ) ; for ( String perm : pi.requestedPermissions ) { Log.e ( `` Foo '' , perm ) ; } } catch ( Exception e ) { } class AppViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { AppViewHolder ( Vi... | How give the application manifest permissions ? How to do it programmatically on Android ? |
Java | What is wrong ? I assume that if I subtract 1ms from 1 Jan 1980 0:0:0 then I 've got 1979 . But I must subtract about 500+ ms for this . Please , give me a hint.Updated.The solution is | val cal = Calendar.getInstance ( TimeZone.getTimeZone ( `` UTC '' ) ) cal.set ( 1980 , 0 , 1 , 0 , 0 , 0 ) val date = new Datedate.setTime ( cal.getTimeInMillis ( ) ) // < - 1980 Jan 01 0:0:0date.setTime ( cal.getTimeInMillis ( ) - 1 ) // < - 1980 Jan 01 0:0:0 too ! ! ! val cal = Calendar.getInstance ( TimeZone.getTime... | Subtraction of 1ms leads to unexpected behaviour |
Java | I am currently working on a tic tac toe program for an assignment . The issue I am having is when I count my player ( either the ' X ' player or the ' Y ' player ) , it seems to be counting both players as the same . For instance , after the third play , it sees three plays and counts it as a winner , even though only ... | public class TicTacToeApp { public static void main ( String [ ] args ) { TicTacToeView view = new TicTacToeView ( ) ; TicTacToeModel model = new TicTacToeModel ( ) ; TicTacToeViewController controller = new TicTacToeViewController ( view , model ) ; view.setVisible ( true ) ; } } public class TicTacToeModel { double x... | Compiling Issue ? |
Java | It seems I 'm stuck with java generics again . Here is what I have : Couple of classes : class CoolIndex implements EntityIndex < CoolEntity > class CoolEntity extends BaseEntityEnum using classes above : Function I need to call with use of result of getIndexCls ( ) function call : The problem is that compiler complain... | enum Entities { COOL_ENTITY { @ Override public < E extends BaseEntity , I extends EntityIndex < E > > Class < I > getIndexCls ( ) { return CoolIndex.class ; } @ Override public < E extends BaseEntity > Class < E > getEntityCls ( ) { return CoolEntity.class ; } } public abstract < E extends BaseEntity , I extends Entit... | Incompatible classes of java generics |
Java | I would like to be able to compare two versions of a class / library to determine whether there have been any changes that might break code that calls it . For example consider some class Foo that has a method in version a : and in version b the method becomes : or something similar in the case of a field : I would lik... | public String readWidget ( Object widget , Object helper ) ; public String readWidget ( Object widget ) ; //removed unnecessary helper object version a : public static Object sharedFoo ; version b : static Object sharedFoo ; //moved to package private for version b | Tool to look for incompatabilities in method signatures / fields |
Java | I have a simple coding scenario like : My question : Is there any way to handle exception in catch ? if yes , then how ? What if finally block have exception , is there any way to handle them ? Or Is it only bad programming practise to have an exception in catch or finally block ? | class A { public static void main ( String [ ] args ) { try { //some exception } catch ( Exception e ) { //Again some exception } finally { System.out.println ( `` Finally executed '' ) ; } } } | If the catch throws exceptions , how should I handle them ? |
Java | Today I tried to solve a small challenge : You are a big company with 500 offices , you want to compute the global revenue ( sum of revenues of each office ) .Each office exposes a service to get the revenue . The call takes a certain delay ( network , db access , ... ) .Obviously , you want global revenue as fast as p... | import asyncioimport timeDELAYS = ( 475 , 500 , 375 , 100 , 250 , 125 , 150 , 225 , 200 , 425 , 275 , 350 , 450 , 325 , 400 , 300 , 175 ) class Office : def __init__ ( self , delay , name , revenue ) : self.delay = delay self.name = name self.revenue = revenue async def compute ( self ) : await asyncio.sleep ( self.del... | RxJava usage optimization request |
Java | Referencing a previous answer to a question on SO , there is a method used called TestForNull . This was my original code before I was told I could make it more efficient : My original code : In this snippet , I 'm doing three look-ups to the map . I was told that this could be accomplished in just one lookup , so I en... | for ( int i = 0 ; i < temp.length ; i++ ) { if ( map.containsKey ( temp [ i ] ) ) map.put ( temp [ i ] , map.get ( temp [ i ] ) + 1 ) ; else map.put ( temp [ i ] , 1 ) ; for ( int i = 0 ; i < temp.length ; i++ ) { Integer value = map.get ( temp [ i ] ) ; if ( value ! = null ) map.put ( temp [ i ] , value + 1 ) ; else m... | Map Lookup Efficiency of TestForNull |
Java | I have this piece of codebut I have a compilation error | List < BookDto > deskOfficer = delegationExtendedDto .stream ( ) .filter ( Objects : :nonNull ) .filter ( d - > d.getMembers ( ) ! =null & & ! d.getMembers ( ) .isEmpty ( ) ) .map ( d - > d.getMembers ( ) .stream ( ) .filter ( Objects : :nonNull ) .filter ( m - > RolesEnum.RESPONSIBLE_ADMIN.equals ( m.getRole ( ) ) ) )... | Collecting Lists in Java 8 |
Java | I have an String array with multiple items.Now I want to check in if condition likeIs there any method that can check whole array and if list [ i ] present in array then go into the if condition block.Thank you in advance . | String [ ] folder= { `` proc '' , '' root '' , '' sdcard '' , '' cache '' , '' system '' , '' config '' , '' dev '' , '' sys '' , '' acct '' , '' sbin '' , '' etc '' } ; if ( list [ i ] .getName ( ) .equals ( object ) ) | How to get array item without looping in android ? |
Java | How do I read/understand the following statement in Java ? I think I can understand them individually but I do n't know if I get good sense of what it means in its entirety . Individually : Class < ? > means any class and Class < ? extends Payload > means any class that extends the Payload class [ ] seems to refer to a... | Class < ? > [ ] groups ( ) default { } ; Class < ? extends Payload > [ ] payload ( ) default { } ; | What is the syntax for annotation type elements ? |
Java | I 'm trying to use java class BitSet as a field for a customized class . And I want the class to use a default BitSet with all bits set.By default BitSet constructor unsets all bits . So before I send it as an anonymous object , I would like call set ( int , int ) method to set all bits . I know that I could simply ini... | import java.util.BitSet ; public class MyClass { private BitSet mask ; public MyClass ( ) { this ( new BitSet ( 4 ) ) ; // want to set all bits first // something like // this ( new BitSet ( 4 ) .set ( 0,3 ) ) ; } public MyClass ( BitSet mask ) { this.mask = mask ; } } | Can object method call be done simultaneously with object instantiation ? |
Java | Consider 4 input fields A , B , C and D on a web surface . The user can fill any of these arbitrary . There are 16 combinations of how to fill these fields . The ones allowed are : where 1 means not null and 0 means null . I am using the MVC pattern with jsf . I do n't want the logic to be in the view , but rather in t... | A B C D -- -- -- -1 0 0 01 1 0 01 1 1 01 1 1 1 @ Overridepublic boolean isInputInvalid ( Integer a , Integer b , Integer c , Integer d ) { if ( isNotSet ( a ) & & isNotSet ( b ) & & isNotSet ( c ) & & isNotSet ( d ) { return true ; } return ( firstParameterDoesNotExistAndSecondDoesExist ( a , b ) ) || ( firstParameterD... | What is the best way to test this ? Binary digits with 4 positions |
Java | I created a javaFX chooser file in Jython . It was n't easy to port from Java to Jython , but in the end some results came . Now I would like to parameterize the obtained class , taking into account the file filters , so as to be able to use the object for browsing different from the type of filtered files.I tried to i... | import sysfrom javafx.application import Applicationfrom javafx.stage import FileChooser , Stageclass fileBrowser ( Application ) : @ classmethod def main ( cls , args ) : fileBrowser.launch ( cls , args ) def start ( self , primaryStage ) : fc = FileChooser ( ) filter = FileChooser.ExtensionFilter ( `` All Images '' ,... | Add file filters to JavaFx Filechooser in Jython and parametrize them |
Java | I want to set first spinner value as `` select your choice '' then shows the data from serverone solution * creates another array list and in that list contain the value `` select your choice '' and combine these two and set to the spinner .. how can I achieve this please help me ... ( using cursor ? ? ? ? ) method for... | Spinner spinner ; private JSONArray result ; ArrayList < String > allNames = new ArrayList < String > ( ) ; spinner.setPrompt ( `` ... Select the Vehicle Number ... '' ) ; spinner.setOnItemSelectedListener ( new AdapterView.OnItemSelectedListener ( ) { @ Override public void onItemSelected ( AdapterView < ? > parent , ... | Add a first value to spinner when spinner data is came from server |
Java | This is a copy of code that I run on a tomcat server on a scheduler . When I check the status of the server I can see the no of open files increasingThis is the command used to check open files sudo lsof -p $ ( pidof java ) | grep `` DIR '' | wc -lThis is an example of the code wrapped in a unit test.Eventually the res... | import java.io.IOException ; import java.nio.file.Files ; import java.nio.file.Paths ; import java.util.ArrayList ; import java.util.List ; import org.junit.Test ; public class OpenFilesTest { @ Test public void FileRemainOpen ( ) throws IOException { String path = `` /data/cache/hotels/from_ivector '' ; List < String ... | Java 8 reading file list , but files remain open using up resources till server freezes |
Java | I have a data Set like this : Which I 've loaded in ArrayList of String [ ] from Text file like this : I wanted to sort data set in increasing year like this : Problem : The built-in sorting method Collections.sort ( list ) ; of ArrayList only works on single type of data . But , in my case I have string with multi-typ... | 1 , JOHN,19342 , TERENCE,19143 , JOHN,19644 , JOHN,19045 , JOHN,19246 , JOHN,19547 , JOHN,19448 , JOHN,19849 , JOHN,197410 , JOHN,1994 ArrayList < String [ ] > records = new ArrayList < > ( ) ; String fileLocation = System.getProperty ( `` user.dir '' ) ; String dataPath = fileLocation + File.separator + `` boys-names.... | Sorting multi-type string ArrayList in Java based on Integers |
Java | I would like to split a string : '' x= 2-3 y=3 z= this , that '' I would split this up on one or more whitespaces , that are not preceded by a '= ' or a ' , 'meaning group one : `` x= 2-3 '' two : `` y=3 '' three : `` z= this , that '' I have an expression that kinda does it but its only good if = or , has only one whi... | ( ? < ! [ , = ] ) \\s+ | Java regex split on whitespace /not preceded |
Java | Lets suppose I have a ComponentBase class , who is child of ObjectContextDecorator and grandchild of ObjectContext.The set methods on ObjectContextDecorator and ObjectContext are very simillar . Consider this sample code : Both methods ' signatures fit the one being called correctly . I am not able to change the method... | public class ComponentBase extends ObjectContextDecorator { } public class ObjectContextDecorator extends ObjectContext { public void set ( String objectTypePath , String characteristicName , Object value ) { // ... } } public class ObjectContext { public void set ( String characteristicName , Object value , boolean fo... | Overload resolution , which method is called |
Java | Is the class listed below a singleton ? Since the constructor is declared as public , can I infer that the class is a singleton with wrong implementation ? | public class CreateDevice extends Functionality { private static Simulator simulator ; ConnectionDB connect = ConnectionDB.getInstance ( ) ; public CreateDevice ( Simulator simulator ) { this.simulator = simulator ; } private static CreateDevice instance ; synchronized public static CreateDevice getInstance ( ) { if ( ... | Is this class a singleton ? |
Java | How do I get result set as { GERMANY=3 } instead of { GERMANY=3 , POLAND=2 , UK=3 } The outcome as given below I want like below . | public class Student { private final String name ; private final int age ; private final Country country ; private final int score ; // getters and setters ( omitted for brevity ) } public enum Country { POLAND , UK , GERMANY } //Consider below code snippet public static void main ( String [ ] args ) { List < Student >... | How do I get max country for a given arraylist |
Java | I can not compile the following piece of code ( try at onlinegdb ) : incompatible types : can not infer type-variable ( s ) T , U , A , R , capture # 2 of ? , T , T ( argument mismatch ; invalid method referencemethod getDifference in class Container can not be applied to given typesrequired : no argumentsfound : java.... | List < Container < Dto > > list = Arrays.asList ( new Container < > ( new Dto ( `` A '' ) , 10L ) , new Container < > ( new Dto ( `` A '' ) , 30L ) , new Container < > ( new Dto ( `` B '' ) , 30L ) ) ; Map < String , Optional < Long > > mapWrong = list.stream ( ) .collect ( Collectors.groupingBy ( c - > c.getOutput ( )... | Collectors.maxBy ( Comparator.naturalOrder ( ) ) does n't compile although Long is inferred |
Java | I have a string which may have one of two formats : ( someName , true ) ; ( where someName can be any combination of letters and numbers , and after the comma we have either true or false ) ( someName , true ) , ( anything , false ) , ( pepe12 , true ) ; and in this case , we can have as many parenthesis groups as can ... | ( hola , false ) ; comosoy12 , true ) ; caminare ) true , comoestas ( someName , true ) , ( anything , false ) , ( pepe12 , true ) ; ( hola , false ) ; comosoy12 , true ) ; ( batman , true ) , ( kittycat , false ) ; ( batman , true ) ; ( kittycat , false ) ; | Repeating the same pattern on a regex in java ? |
Java | i have a following code : It will return a price like `` 7,49 $ '' . I want to replace this code with java 8 features . I 'm newbie with streams , but tried : But it returns < meta itemprop= '' price '' content= '' 7,49 $ '' > I ca n't filter like this ( missing return statement ) : How to fix it ? | @ Overridepublic String parsePrice ( Document document ) { Elements metaElements = document.getElementsByTag ( `` meta '' ) ; for ( Element tag : metaElements ) { String content = tag.attr ( `` content '' ) ; String item = tag.attr ( `` itemprop '' ) ; if ( `` price '' .equals ( item ) ) { return content.equals ( `` 0 ... | Replace for loop with lambda |
Java | I have recently converted over an android project into androidx and I am having issues with trying to stop views going off of the page . My layout is as follows , a Constraint Layout that contains a Card View and a Text View . Within this Card View I have a Constraint Layout that contains the Text View . Outside of the... | < androidx.constraintlayout.widget.ConstraintLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' xmlns : app= '' http : //schemas.android.com/apk/res-auto '' xmlns : tools= '' http : //schemas.android.com/tools '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent... | How to fix a view from going off of a page when it is constrained to a card view |
Java | A while back , I was working on a programming problem ( CCC ) . I have also come across similar questions in past contests so I decided to ask about this one . The problem is basically this . You are given n people and p pieces of pie.n people are standing in a row.You must distribute p pieces of pie amongst them . You... | import java.io . * ; public class Main { int pieces , people ; int combinations = 0 ; public void calculate ( int person , int piecesLeft , int prev ) { if ( person == people ) { if ( piecesLeft == 0 ) combinations++ ; } else { for ( int x = prev ; ( x * ( people - person ) ) < = piecesLeft ; x++ ) { calculate ( person... | Converting simple recursive method which recurses within a loop into iterative method |
Java | I have the following array of code types : and the following ids : I want to extract the code type from the idsthis is my code snippet : it doesnt work with the 1st id , because it returns `` code '' instead of `` sample_code '' , I want to get the longest code type . | [ `` sample_code '' , '' code '' , '' formal_code '' ] String id= '' 123456789_sample_code_xyz '' ; String id2= '' 91343486_code_zxy '' ; String codeTypes [ ] = { `` sample_code '' , '' code '' , '' formal_code '' } ; String id= `` 123456789_sample_code_xyz '' ; String codeType = Arrays.stream ( codeTypes ) .parallel (... | JAVA return longest value if a string contains any of the items from a List |
Java | Why an actual number string read from a text ca n't be parsed with method Integer.valueOf ( ) in java ? Exception : This is my code | Exception in thread `` main '' java.lang.NumberFormatException : For input string : `` 11127 '' at java.lang.NumberFormatException.forInputString ( NumberFormatException.java:65 ) at java.lang.Integer.parseInt ( Integer.java:580 ) at java.lang.Integer.valueOf ( Integer.java:766 ) at sharingBike.ReadTxt.readRecord ( Rea... | Why an actual number string read from a text ca n't be parsed with method Integer.valueOf ( ) in java ? |
Java | In the project I 'm working on ( not my project , just working on it ) , there are many structures like this : And the Service is called like this : I understand that a factory is used to hide the implementation of MyServiceImpl if the location or content of MyServiceImpl changes . But why is there another factory for ... | project.priv.logic.MyServiceImpl.javaproject.priv.service.MyServiceFactoryImpl.javaproject.pub.logic.MyServiceIF.javaproject.pub.service.MyServiceFactoryIF.javaproject.pub.service.MyServiceFactorySupplier.java MyServiceFactorySupplier.getMyServiceFactory ( ) .getMyService ( ) | Why do I need a FactorySupplier ? |
Java | I have the following scenario : two validation Helpersthe StringValidationHelper ... ... and NumberValidationHelper.The method from is a static factory method that receives a Predicate and a message to eventual validation fails.Thanks to the Validation interface , you can enjoy a wonderfully smooth interfaceSo I can st... | public class StringValidationHelper { public static Validation < String > notNull = SimpleValidation.from ( s - > s ! = null , `` must not be null . `` ) ; public static Validation < String > moreThan ( int size ) { return SimpleValidation.from ( s - > s.length ( ) > = size , String.format ( `` must have more than % s ... | How to generalize a static clousure ? |
Java | I want to create a map of comparators as following , this map will be used to provide the comparator for each kind of class . How can I replace the Generic ? in the declaration of my map to be sure that I have always the same Class type in key and value of my map ( comparators ) ? I want also to reduce the number of wa... | private static final Map < Class < ? > , Comparator < ? > > comparators = new HashMap < > ( ) ; static { comparators.put ( Identifiable.class , new Comparator < Identifiable > ( ) { @ Override public int compare ( Identifiable o1 , Identifiable o2 ) { return o1.getId ( ) .compareTo ( o2.getId ( ) ) ; } } ) ; comparator... | How to Use Generics in a map of Comparator to avoid warnings |
Java | Lets say I have a class C that is doing some job . For that I need a little very simple helper class H ( e.g . representation of a pair or a 3-tuple ) . H is only needed in C.I would put H inside of C.Is putting H inside of C a good idea ? I do it to have it contained and at the place I think it should be and nowhere e... | class C { void foo ( ) { // ... use H to do the job more easy ... } class H { // very simple and contained stuff } } | OOP design of little helper classes |
Java | I have a Spring Boot application , which runs in an Apache Tomcat server . In application.yaml I have , among others , following entries : The application is deployed to Tomcat from within IntelliJ Idea so I can debug it.I start Tomcat using the following command : However , after Istart Tomcat using the above script ,... | mail : pop3Host : $ { MAIL_HOSTNAME } inboxFolder : $ { MAIL_INBOX } hostName : $ { MAIL_HOSTNAME } port : $ { MAIL_PORT } userName : $ { MAIL_USERNAME } password : $ { MAIL_PASSWORD } export JPDA_OPTS= '' -agentlib : jdwp=transport=dt_socket , address=8090 , server=y , suspend=n '' export JAVA_OPTS= '' -DMAIL_HOSTNAME... | How to make sure that environment variable placeholders are substituted in a Spring Boot application running in Apache Tomcat ? |
Java | I browsed some JAVA code made by Google , and I found the ImmutableSet : http : //google-collections.googlecode.com/svn/trunk/javadoc/com/google/common/collect/ImmutableSet.htmlThey implemented the of ( ) method with several other ways : I checked the implementation which is here : https : //code.google.com/p/google-co... | public static < E > ImmutableSet < E > of ( E e1 , E e2 ) ; public static < E > ImmutableSet < E > of ( E e1 , E e2 , E e3 ) ; public static < E > ImmutableSet < E > of ( E e1 , E e2 , E e3 , E e4 ) ; public static < E > ImmutableSet < E > of ( E e1 , E e2 , E e3 , E e4 , E e5 ) ; public static < E > ImmutableSet < E >... | Equivalient method overload why necessary ? |
Java | First time I use Regex statement.I have java regex statement , which split String by pattern with list of some characters.output of above code is like ( 018020000304050.12500 ) Actually I want output like this , ( `` F '' , `` 01 '' , `` T '' , `` 8 '' , `` B '' , `` 02 '' , `` S '' , `` 00003 '' , `` H '' , `` 04 '' ,... | String line = `` F01T8B02S00003H04Z05C0.12500 '' ; Pattern pattern = Pattern.compile ( `` ( [ BCFHSTZ ] ) '' ) ; String [ ] commands = pattern.split ( line ) ; for ( String command : commands ) { System.out.print ( command ) ; } | How to get list of pattern string and matcher string in java regex |
Java | I need some understanding from you expertsThis Program does not go to catch block ( as Heap is full , but I want to understand why ) But the below Program runs good , even after getting OOME : I am bit confused , after seeing different results for the same error OOME . Please guide | public class OOME_NotCatch { static List l = new ArrayList ( ) ; static Long i = new Long ( 1 ) ; public static void main ( String [ ] args ) { try { while ( true ) { l.add ( i ) ; i++ ; } } catch ( OutOfMemoryError e ) { e.printStackTrace ( ) ; System.out.println ( `` Encountered OutOfMemoryError '' ) ; } } } //Consol... | Why different behaviors for OOME while trying to catch it ? |
Java | I 've defined a class like this : This wo n't compile . I 'm not allowed to create the generic type T.How can I solve this ? Is there any good patterns to do this ? Can I solve this by using an abstract class instead of the interface ? Do I have to use reflection ? | public class MyClass < T implements MyInterface > { public T getMy ( ) { return new T ( ) ; } } | How to create generic type ? |
Java | I need help to design java code for generating bit array for any given integer in following manner:23 should produce output as 1101011 ( min length array ) explaination : positions are given as 1 -2 4 -8 16 -32 ... .So 1101011 can be evaluated as : | 1*1 + 1*-2 + 0*4+ 1*-8 + 0*16 +1*-32 + 1*64 = 23 | Forming a pattern of bits from a integer |
Java | I 've failed to google this problem . Why would this line produce a compilation error.I 'm using java 7.The error is : | wrapper.doSmth ( wrapper.getCurrent ( ) ) ; public class App { Wrapper < ? > wrapper ; class Generic < T > { } class Wrapper < T > { Generic < T > current ; public void doSmth ( Generic < T > generic ) { } public Generic < T > getCurrent ( ) { return current ; } } public void operation ( ) { wrapper.doSmth ( wrapper.ge... | Code with generics wo n't compile |
Java | I want to calculate the volume of a sphere using a Java program . So , I used This formula gives the wrong answers it seems.Like Java program opt 4/3 , but if I change it to it gives me the correct answer . Does any one know what is going on ? | double result = 4/3*Math.PI*Math.pow ( r,3 ) ; double result= Math.PI*Math.pow ( r,3 ) *4/3 ; | java 2 different formula problems |
Java | Let 's take an example to make it easier . I build a list which the constructor takes an integer and a List < Integer > . My list will contains all the elements of the given list multiplied by the integer . My list does not store the new elements but compute them on the fly : Then we can call new MyList ( 3 , list ) wi... | class MyList extends AbstractList < Integer > implements RandomAccess { private final int multiplier ; private final List < Integer > list ; public MyList ( int multiplier , List < Integer > list ) { this.multiplier = multiplier ; this.list = list ; } @ Override public Integer get ( int index ) { return list.get ( inde... | How to return an object with multiple types |
Java | I am trying to make a void method that calculates average , but I would like to pass values to the method from the main method . Here is an example of what I am trying to do : The problem I 'm having is getting the values of multiple plants into the method . I 've tried using .get , loops , static , and many other thin... | public class Plant { int leaves ; int age ; int sumLeaves ; double average ; void averageLeaves ( ) { sumLeaves = leaves + leaves ; //here is where I need help average = ( double ) sumLeaves / 2 ; System.out.println ( `` The average number of leaves is : `` + average ) ; } public static void main ( String [ ] args ) { ... | passing object values to methods |
Java | This is the snippet of code in Java language : Why does compiler ca n't see the second if statement considering the last option of the value ? It wo n't compile.Best regards | public void name ( ) { int value = 9 ; int o ; if ( value > 9 ) o = 5 ; if ( value < = 9 ) o = 8 ; System.out.println ( o ) ; } | Branching which ca n't be seen by compiler |
Java | Why in this snippet of code the cast ( MyClass ) o in line number 8 is necessary , despite the fact that the Client invokes a compare method with arguments which are instances of MyClass class ? When I modify the compare method in MyClass class to form like below : Then , the Client will produce the following result : ... | class MyClass { private String str ; public MyClass ( String str ) { this.str = str ; } public int compare ( Object o ) { return str.compareTo ( ( ( MyClass ) o ) .str ) ; //line No.8 } } class Client { public static void main ( String [ ] args ) { MyClass m = new MyClass ( `` abc '' ) ; MyClass n = new MyClass ( `` bc... | Why the cast is necessary in this case ? |
Java | Most questions about wildcards want to know why something sensible is rejected by the compiler . My question is the opposite . Why is the following program accepted by the compiler ? I tried to explain this from the Java Language Specification , but I have not found the answer . I had the impression from various descri... | void test ( List < ? extends Number > g1 , List < ? extends Number > g2 ) { g1 = g2 ; } | Why is this assignment involving wildcards legal in Java ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.