text
stringlengths
46
37.3k
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 ba...
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 . Ho...
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 o...
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 ...
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 <code> class test { public static void main ( String [ ] args ) { test item = new test ( ) ; item.someOtherMethod ( ) ; } test item2 = new test ( )...
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,48...
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...
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 w...
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 wildcar...
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 resu...
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 inter...
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 ? <code> public class Item { private String name ; private int qty ; public Item ( )...
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/...
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 Interrup...
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 ) <code> class Snow { } class Powder extends Snow { } class Light extends Powder { } class Heavy exte...
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 :...
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 st...
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 th...
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 ? <code> import java.util . * ; public class RentalGeneric < T > { priv...
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 . o...
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 . <code> public class StatusCategory { @ JsonProperty ( `` key '' ) private final...
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 . ...
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 i...
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 <code> plugins { id `` com.gradle.enterprise '' version `` 3.5 '' } gradleEnterprise { server...
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 ...
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 ca...
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 pa...
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 ...
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 . <code> 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...
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 . <code...
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 code...
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 ? <code> class Sup { int a = 8 ; public void printA ( ) { System.out.println ( a ) ; } Sup ( ) { printA ( ) ; } } public class Sub extends Sup { int a = 9 ; @ Overri...
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 ? <code> public class LogService { public void stop ( ) { synchronized ( this ) { isShutdown = true ; } logg...
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 terribl...
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 . <code> 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 ) ; } p...
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 , bu...
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 Jav...
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...
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...
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 ... <code> INSERT INTO MYTABLE ( f1 , f2 , f3 , f4 ) VALUES...
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 Jav...
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...
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 . <code> 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 ( `` lo...
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 ...
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...
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...
\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 o...
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 mor...
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 , ho...
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 onl...
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 exampleT...
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/operationwrap...
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 <code> pu...
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...
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 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 `` دسترسی ها...
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 <code> val cal = Calendar.getInstance ( TimeZone.getTimeZone ( `` UTC '' ) ) cal.set ( 1980 , 0 , 1 , 0 , 0 , 0 ) val date = new...
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 thoug...
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 c...
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 wo...
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 ? <code> class A { public static ...
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 fa...
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 , ...
Map Lookup Efficiency of TestForNull
Java : I have this piece of codebut I have a compilation error <code> List < BookDto > deskOfficer = delegationExtendedDto .stream ( ) .filter ( Objects : :nonNull ) .filter ( d - > d.getMembers ( ) ! =null & & ! d.getMembers ( ) .isEmpty ( ) ) .map ( d - > d.getMembers ( ) .stream ( ) .filter ( Objects : :nonNull ) .f...
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 . <code> String [ ] folder= { `` proc '' , '' root '' , '' sdcard '' , '' cache '' , '' sys...
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 ref...
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 sim...
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 rath...
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 tri...
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 ? ? ? ? ) met...
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 ...
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 mu...
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 ...
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...
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 ? <code> public class CreateDevice extends Functionality { private static Simulator simulator ; ConnectionDB connect = ConnectionDB.getInstance ( ) ; public Cr...
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 . <code> public class Student { private final String name ; private final int age ; private final Country country ; private final int score ; // getters and setters ( omitted for brevi...
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 ...
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 ...
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 ? <code> @ Over...
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...
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 the...
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 . <code> [ `` sample_code '' , '' code '' , ''...
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 <code> Exception in thread `` main '' java.lang.NumberFormatException : For input string : `` 11127 '' at java.lang.NumberFormatException.forInputString ( NumberFormatException.java...
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 facto...
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...
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 numbe...
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 no...
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 s...
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/go...
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 '' , `` ...
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 <code> public class OOME_NotCa...
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 ? <code> public class MyClass < T implements MyIn...
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 : <code> 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 : <code> wrapper.doSmth ( wrapper.getCurrent ( ) ) ; public class App { Wrapper < ? > wrapper ; class Generic < T > { } class Wrapper < T > { Generic < T > current ; public void doSmth ( Generic <...
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 ? <code> double result = 4/3*Math.PI*Math.pow ( r,3 ) ; double result= ...
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 , li...
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 oth...
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 <code> 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 re...
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...
Why is this assignment involving wildcards legal in Java ?