text
stringlengths
46
37.3k
title
stringlengths
12
162
Java : For my game I 've implemented an inventory system . When the screen is clicked , a MousePressedEventis passed through all layers in the game , to all objects that inherit EventListener ( My EventListener ) . The EventListener class works fine and , using it as shown below , I 've managed to get my inventory so t...
Java : Allowing drop action in my inventory ?
Java : I 'm just getting started on stream processing using Apache Flink , the thing is that I 'm receiving a stream of Json that look like this : And was asked if i could fulfill the following business rules : Decline if number of tokens > 5 for this IP in last 10 secondsDecline if number of tokens > 15 for this IP in...
Multiple Apache Flink windows validations
Java : i want to remove anything between `` ? '' and `` / '' my text is `` hi ? 0/hello/hi '' i need to see this out putMy Code Isbut my Output Iswhats wrong ? <code> `` hi ? /hello/hi '' key.replaceAll ( `` \\ ? . */ '' , '' ? / '' ) ; `` hi ? /hi ''
Remove anything between two character
Java : Consider the following code : I am trying to replace it with a generics version of the Context class : Thus I do not pass a .class as a parameter to the constructor , and the unmarshall method automatically casts the return object.I need to know the Class of T to pass to the newInstance ( ) method , and to invok...
How do I retrieve the Class for a Parameterized Class
Java : I'am trying to solve this Homework : Suppose that people enter an empty room until a pair of people share a birthday . On average , how many people will have to enter before there is a match ? Run experiments to estimate the value of this quantity . Assume birthdays to be uniform random integers between 0 and 36...
Birthday problem , Average number of people
Java : Under JUnit4 , I have a test suite which uses a @ classrule annotation to bootstrap a framework . This is needed to be able to construct certain objects during tests . It also loads some arbitrary application properties into a static . These are usually specific to the current test suite and are to be used by nu...
Is there a good way to engage the initialization of a test suite when running an individual test case ?
Java : In my international resources , the code is : In my java code : The expected value of messageContent should like this : But the actual value of messageContent is like this : Why ? <code> post_badge_format = You 've earned the `` { 0 } '' badge for { 1 } . String messageContent = MessageFormat.format ( messageTyp...
International resources
Java : The Java 8 doc page for Java.Time.Year states that the minimum and maximum supported years are -999,999,999 and 999,999,999 , respectively . Field Summary static int MAX_VALUEThe maximum supported year , '+999,999,999 ' . static int MIN_VALUEThe minimum supported year , '-999,999,999'.However , the primitive typ...
Why is Java.Time.Year arbitrarily limited to less than its primitive limits ?
Java : Say if there are two Strings or any Objects and I want to check if both the objects are the same , I would do string1.equals ( string2 ) and thats fine . Now if there are three objects and I want to see if they are all equal I would do string1.equals ( string2 ) & & string2.equals ( string3 ) and say four and so...
Most efficient way to check if all given n objects are the same or distinct ?
Java : Why this code is n't showing any compilation error ? If we write a normal code like this ( shown below ) Then why the above above is running fine , how can T be of Integer class and array of T be of Character class at the same time , and if its running then why its not printing true , ASCII vaue of ' a ' is 97 ,...
How can a parameter in a Generic method be assigned to an Integer and a Character class at the same time ?
Java : I am trying to generify following class : Everything is alright except Foo [ ] .class : How can I solve this issue without passing Foo [ ] .class in the constructor like I have done with Foo.class ? <code> public class FooService { private Client client ; public Foo get ( Long id ) { return client.get ( id , Foo...
Generifying array type such as Object [ ] .class
Java : I ca n't find a solution to this inheritance problem . I 'm working on a program which will store information about celestial bodies . I have an abstract superclass , Body , from which all other celestial bodies should inherit . Now , I want some bodies to have implementation by default for storing information a...
How do I bypass this multiple inheritance problem ?
Java : I hava following code to test volatile . bEnd and nCount are defined volatile . The Writer thread will set The Reader thread read these viriables and print them . Base on the Java Happens-before order , in my opinion , volatile ensures nCount = 100 when bEnd = true . But sometimes the program print this : How ca...
Why the volatile Happens-Before order for Instruction Reordering fails ?
Java : I am learning Java and I am following a project to simulate a ski jump tournament . Basically they want me to replicate this action : My question is solely on the way to loop this . I know I can do this by entering a while ( true ) loop , and break right away if the input by the user equals `` quit '' . However ...
Is there a way to avoid while ( true ) if I need to evaluate the condition at the beginning ?
Java : In this exampleThis compiles and prints a result [ 1 , blabl ] My understanding is : The reference variable 'integers ' has an address ( say 111 ) of the arraylist object which is being passed to the addToList method . So in the addToList method list0 points to the same address which has the object ( which is an...
List of raw type and data integrity
Java : The outline of the program : We have two threads ( t1 and t2 ) that write an integer value , then flush the written value to RAM.Another thread ( t3 ) checks whether the value coincidences with the one written by t1or t2 , and if not , prints it.What I thought would happen : Since a is n't volatile , I thought t...
Multithreading - Why does the following program behave this weirdly ?
Java : The following code , gives the following output after running multiple times , VM detailsWhat was surprising is why does the JIT take much more iterations to optimize if the stack trace is of even length ? I enabled JIT Logs and analysed via jitwatch , but could n't see anything helpful , just that the timeline ...
JIT recompiles to do fast Throw after more iterations if stacktrace is of even length
Java : I 'm trying to recreate a process to create a list of objects that are an aggregation of another list of objects using Java 8 Streams.for example , I have a class , described below , that is provided from a database call or similarElsewhere in my application I have a class OrderTotal which represents and aggrega...
Mapping , aggregating and composing totals using Java 8 Streams
Java : In Java Concurrency in Practice one of the examples that I think surprises people ( at least me ) is something like this : The surprise ( to me at least ) was the claim that this is not thread safe , and not only it 's not safe , but also there is a chance that the check method will throw the assertion error.The...
Making this visibility example fail
Java : I want to createNewFile with a path but I got an IOException . The question is , the detailed message can not be interpreted , I can only see a bunch of question marks.I am with Windows 10 originally in Spanish , but with Chinese language pack installed . The java language already set to en and file encoding UTF...
IOException - detail message all question marks
Java : I am using java to execute a simple bash script on a remote linux machine.The bash script named `` shortoracle.bash '' have this script : Simply speaking : create 10 parallel connection that execute queries for 360 seconds.From my java program i execute the following command : The ssh executes the script success...
Executing bash script via java in background after ssh connection is closed
Java : So I do n't know much about java but I noticed this worked then according to my class notes I should be doing it a different wayHere 's what my notes haveHowever I tried this and it also does the same thing . It 's shorter so is this an acceptable way to do it or will it break down the road ? Also as long as the...
Why does using one `` print '' instead of three work ?
Java : I have a trouble with splitting my class into smaller parts . We have a bad situation where a Dto holds 30 different Dtos . Now we need this selectDto 's mapping which also force us make 30 different mapping class . ( We also use mapstruct in the project , this scenario is different than mapstruct can handle ) N...
Ca n't Split Class into Smaller Ones
Java : Why are n't the same restrictions applied to static fields , what 's the idea behind it ? <code> package one ; public class A { protected int first ; protected static int second ; } package two ; import one.A ; public class B extends A { public void someMethod ( ) { this.first = 5 ; //works as expected B.second ...
Why are protected instance members not visible inside a subclass within a different package , but protected class members are ?
Java : I 'm trying to delete files but it is n't working or I 'm missing something.Here is a little test I 'm doing : And the system prints : Abs path C : \Users\XXXX\Documents\PAI\TSoft.\test\pacientes\John Smith.tds Exist true Filename John Smith.tds Delete false And of course is n't deleting the file , why ? How can...
Deleting specified file
Java : Say I have an API that , based on some query criteria , will find or construct a widget : The ( synchronous ) client code looks like : Now say finding or constructing a widget is unpredictably expensive , and I do n't want clients to block while waiting for it . So I change it to : Clients can then write either ...
Asynchronous , composable return value for vector/stream data in Java 9
Java : While looking into the source code of the WrappingSpliterator : :trySplit , I was very mislead by it 's implementation : And if you are wondering why this matters , is because for example this : is using it . In my understanding the addition of any intermediate operation to a stream , will cause that code to be ...
Stream spliterator implementation detail
Java : I want to find out if a string that is comma separated contains only the same values : Here the 2nd string contains only the word `` test '' . I 'd like to identify these strings.As I want to iterate over 100GB , performance matters a lot.Which might be the fastest way of determining a boolean result if the stri...
How to find duplicates inside a string ?
Java : What would the legitimate use of the following code be ? From what I understand this object has no use and carries no real data ( except for maybe its hash code ) . Why would this be used ? Is it acceptable practice . If I am able to do this could I explicitly extend the object class . <code> Object o =new Objec...
Is there legitimate use for object constructor ?
Java : I am working on this project currently . It works surprisingly well.Yet , after re-reading the README again , I started to wonder about how to document something that is bugging me ... To quote the example , and forgetting for a moment that exceptions can be thrown , it reads : OK. Now , the method of Path invol...
Lambda matches signature of a FunctionalInterface , yet `` does not '' . How do you explain that the argument is passed at all ?
Java : `` Why are you doing this what is wrong with you ? '' notwithstanding , is there any way to accomplish this without changing the final method parameter name ? Obviously without the doSomethingThatReassignsBar call , you would n't need the member Bar and so on . In this case , the simple fix is to change final Ba...
Can final parameters be qualified in some way to resolve naming conflicts with anonymous class members ?
Java : Why can I call average ( ) method on one but not on the other ? Should n't they be equivalent ? example 1 - worksexample 2 - does n't compile ( deleted mapToInt call because already passing Integer stream ) Question , is why do I need to call mapToInt method when Im already passing it a stream of Integers ? <cod...
Java stream question , mapToInt and average method
Java : In this discussion about the performance overhead of using reflection , it is stated : Use of reflection can cause some runtime optimizations to be lost . For example , the following code is highly likely be optimized by a Java virtual machine : Equivalent code using Field.set* ( ) may not.Without reflection , w...
What kind of runtime optimizations are lost if we use reflection
Java : I 'm reading J. Bloch 's effective Java and he said the following : Once an interface is released and widely implemented , it is almost impossible to change.So , now consider the simple interface for DAO-pattern : This is how my Dao interface looked when it was released firstly . By the time , I had to add some ...
Understanding DAO-pattern and interfaces
Java : I have a huge @ OpenApi annotation ( basically it 's documentation of a Javalin/Kotlin endpoint ) which occupies a lot of lines : I have to scroll a lot to see the actual handler.Hence , I 'd like to isolate it somehow like : I 'm OK with other solutions that make the documentation go elsewhere.This would make t...
Isolate the instantiation of an annotation
Java : When I try to sort the array , the result that I get is : The user fills the array with 8 numbers that should be eventually sorted . But what I 'm getting is a bunch of 0s.Why am I getting 0s ? <code> The sorted array is [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] import java.util.Scanner ; import java.util.Arrays ; publi...
Sorting array in an ascending array
Java : I have an array of [ 5 , 6 , 7 , 3 , 9 ] , I would like to change each element from the array substracting by 2 , then store the in a Set , so what I did isbut I am getting two exceptions here asThe method collect ( Supplier < R > , ObjIntConsumer < R > , BiConsumer < R , R > ) in the type IntStream is not appli...
Java stream - map and store array of int into Set
Java : Can anyone explain why this code is giving output as null ? When I try to call new A ( ) instead of new B ( ) , it is printing the current date . <code> class A { Date d = new Date ( ) ; public A ( ) { printDate ( ) ; } void printDate ( ) { System.out.println ( `` parent '' ) ; System.out.println ( d ) ; } } cla...
Java flow-control
Java : the out putThis code print out the the date times around `` 2037-10-18 00:00:000 Brasilia Time '' , the result shows out that `` 2037-10-18 00:00:000 Brasilia Time '' should be `` 2037-10-18 01:00:00.000 Brasilia Summer Time '' that means Brasilia entered the summer time in that moment.My question is why between...
Brasilia Summer Time transition at 2037-10-18
Java : Why does this code compile ? On the left side is one-dimensional array . On the right I thougth that three-dimensional , but it is not ? <code> int [ ] array = new int [ ] [ ] { { 1 } } [ 0 ] ;
One-dimensional array references to multi-dimensional array
Java : If we throw an exception in the method main and do n't handle it it will work fine . ActuallyBut Java requires any checked exception to be handled in the program , therefore the IOException should be handled . Who actually handles the IOException in that case ? Note , that the Java Language Specification defines...
Who actually handles exceptions thrown in the main method ?
Java : I 've stumbled across some pretty weird code that I 'm surprised does n't cause an errorSurprisingly , it prints out 42 ! Can anyone explain ? <code> public class WeirdCode { public static int fooField = 42 ; public WeirdCode getFoo ( ) { return null ; } public static void main ( String args [ ] ) { WeirdCode fo...
Strange Code Output
Java : I have an integration test that launches getty and it in turn launches a web application . The web app will span some asynchronous threads that will run initialization tasks . After that it is ready to be tested . Now because I 've to wait one of those tasks to finish I thought of putting a static monitor in a s...
Does anyone know why I am getting this IllegalMonitorStateException ?
Java : In my Android app I have an Activity where a user can add some text to an image . When the button to initiate this is pressed a TextInput appears at the bottom of the screen with the `` Save '' button overlayed.The relevant config looks like this : The activity xml looks like this - I have trimmed out a couple o...
Place a TextInput above the Android keyboard without it drawing a black rectangle ?
Java : I have a program where players play a game and the user can input p or r to pause and resume the game , using event listeners , and this functionality works in java 6 but not in java 7 , and I do n't understand why not . could someone please help . Event listener threadThe player thread '' event generator '' I c...
pause feature works in java 6 not java 7
Java : Lets start with 3 interfaces . What they do is n't important . Just note that Car is parameterized ( ) , while Foo and Bar are not.I want to 'composite ' these interfaces , and this works just fine if I explicitly create the composites like this : However , I 'd much prefer to implicitly composite the interfaces...
Bound Type Parameters in a Generic Method fail while an equivalent Generic Interface works , why ?
Java : When I say efficient I mean code that is n't cpu intensive.The Problem : I have a field of blocks . Like in the following image : Every single one of these blocks represents an instance of a self-made Block class . This block class has a List < Block > neighBours , where the neighbours of the block are stored . ...
An efficient way to get and store the shortest paths
Java : When trying to compile the followingI get the following errorsWhy does Object bar = ( Object ) foo ; need to be in a block for the code to compile ? <code> public class Test { public void method ( String foo ) { // This compiles if the curly braces are uncommented if ( foo instanceof Object ) // { Object bar = (...
Why do declarations following conditions of control structures need to be in a block ?
Java : I executed the below mentioned code , when I got a strange output . Can anyone please explain why I am getting this output ? Code : OutputWhy are we getting the `` [ I @ '' / '' [ F @ '' prefixes and the 8 alphanumeric characters to follow , are they memory address ? <code> public class Bar { static void foo ( i...
Can anyone explain the output that I am getting while compiling this program ?
Java : Problem and where I 'm at : I ca n't append text into these new files I create with the program . Currently it only copies files but does not append them . See line with comment `` // append file name into the new file `` .Secondly , the final dump file seems to only append the .java file , it 's not reading or ...
Text is not appended in new file in attempt to make a text file manipulator
Java : Could you help me with Java Streams ? As you can see from the title I need to merge List < Map < String , Map < String , Genuineness > > > into Map < String , Map < String , Genuineness > > .The list is represented as List < Map < String , Map < String , Genuineness > > > and looks like : So , as you can see , d...
How to merge List of Maps of Maps into a Map of Maps ?
Java : I use generics in Java but it is n't so good as I thoughtAll this compiles and works . When I get a value from list an exception is thrown.Can it be safer in Java 6 ? <code> public static void add ( List l , Object o ) { l.add ( o ) ; } public static void main ( String [ ] args ) throws Exception { List < Intege...
Collection safer than standard list with generic type ?
Java : Hi I am a new Java programmer and have a small question about class design.I understand that something like this is a cyclic dependency and is probably not a way to structure a project : But what if Student.java is changed to : so that courseId can be used to retrieve the course from a DAO or something . Is this...
Is this considered a cyclic dependency ( is this good practice ) ?
Java : I was wondering why The ExecutorService can actually execute the same Thread multiple times.Because the usual lifecycle of a thread ends on TERMINATED afaik..So , this works where i would actually expect an illegal state exception like in this case : Help much appreciated to unravel the magic behind the execute ...
Restarting a java Thread
Java : My question is why the output is BO , D1 instead of BO , B1 . I am not getting how the super keyword plays the role of calling the methods of the child class instead of the parent class . <code> public class B { public B ( ) { } private void m0 ( ) { System.out.println ( `` BO '' ) ; } public void m1 ( ) { Syste...
How the key word super works in java-Java Puzzle
Java : I just want to know how many characters I can put in when I use the above statement.For example , if I can put in `` aaaaa '' or `` abcde '' into console , that would mean I can put 5 or more characters.Then can I put in `` a '' 2,147,483,647 times ? ( max value of integer ) System.in seems like internally stori...
What is the maximum size of characters when using buffered reader readline ( ) from System.in
Java : I could n't really explain myself in the title , what I meant is - get a String and check every letter and print it if the next char in the String is also the next letter in the ABC order , for example `` almndrefg '' will return `` lmnefg '' , what I did so far is : What should I correct ? <code> package string...
Printing only the letters by ABC order from String
Java : I am writing simple program in java to create 2 int arrays of 1 billion size . I ran this program with -Xms10G , i.e . 10GB of memory still I got OOM error . Below is the snippet . As far as I can think the memory used for 1 billion int array would be System.out.println ( 1000_000_000 * Integer.SIZE ) ; which re...
java OOM on creating 2 arrays of one billion ints
Java : I have an ArrayList that can contain an unlimited amount of objects . I need to pull 10 items at a time and do operations on them.What I can imagine doing is this.Any thoughts ? Thanks ! <code> int batchAmount = 10 ; for ( int i = 0 ; i < fullList.size ( ) ; i += batchAmount ) { List < List < object > > batchLis...
Best way to pull items from an array 10 at a time
Java : I was cleaning up code and changing all access to static member such that they are qualified by the class in which they are defined . This , however , lead to the following problem which is puzzling me . I have a class with a nested class inside . In the annotation on this nested class I refer to a private stati...
Should a private static fields be visible from nested class when qualified by the surrounding one ?
Java : We have the DayOfWeek enum defining the days of the week in standard ISO 8601 order . I want a List of those objects in the order appropriate to a Locale.We can easily determine the first day of the week for locale.Set up the List.➥ To add the other six days of the week to that list , what is the simplest/shorte...
List < DayOfWeek > in localized order
Java : I have the following problem regarding the correct use of streams and map.The problem is the followingI have a method that reads a file from input and inserts record in a database , in a few words it performs some side effectsFurthermore , the same function returns some sort of a state , let 's say a boolean ( I...
Java stream check results of multiple calls using map
Java : I 'm trying to migrate a function from java 7 to java8 but i 'm stucked over getting the value of the indexed element while looping a list . What is the good way to do this ? here is the code that i 'm trying to migrate : <code> List < Employe > listEmploye = new ArrayList < > ( ) ; for ( int i=0 ; i < ids.size ...
How to loop list object and getting it 's element by index ?
Java : As a brain-twister example a professor of mine gave us following exercise , to learn about inheritance . We had to figure out the output.The output is , as I expected , a.f ( ) B - > f ( ) A - > f ( ) B - > f ( ) A - > f ( ) 19However , I was now wondering . Is there a way to make the f-call in A call the f meth...
Calling super method from within super class
Java : I need to get local time and utc time in seconds . I read some posts in StackOverflow and found some solution , which is correct as mentioned : But result is not what I expected . It is utc time . The output : After debugging I found that Instant.now ( ) is already utc . I ca n't find how to get time in current ...
Ca n't get local and utc Instant
Java : I have a question about a sneaky way to gain access to package-access members that occurred to me . Specifically , I want to extend a class - let 's call it com.acme.Foo - to add some functionality . This is pure addition : all current methods of Foo would be supported just by delegating to the superclass 's met...
Gaining access to package-access members by creating the same package name
Java : I want to create universal method , for any enum object , that will check if enum has specified value name , but as Enum type object I am unnable to use method values ( ) ; . Why ? Is there any way to get values from an Enum type object ? I need method like this to check if value from configuration is a valid st...
Why I can not get .values ( ) from Enum object class ?
Java : I am new in Java 8 , and I have this expression : and I would like to know if it could be replaced for something like : <code> .map ( mc - > mc.getName ( ) .getDefaultName ( ) ) .map ( TeleBadalonaCampaignType : :getName : :getDefaultName )
Method reference of a method reference in a Lambda expression
Java : Here 's my scenario : Entity is the super class of Planetentities is a HashMap < Entity > As the method is called `` getPlanets '' I would like it to return a List < Planet > but it appears to me that the stream expression is going to return a List < Entity > I tried some casting expressions but none seem to wor...
Casting a list during a stream operation
Java : I 'm trying to implement a really simple echo-back multi-threaded server.I used the thread pool created with newFixedThreadPool , but it looks like the number of concurrent connections is fixed at nThreads ( passed into newFixedThreadPool ) . For example , if I set nThreads to 3 , then the fourth client that con...
java threads appear not to be released
Java : I have web application implemented using java spring.Basically each user in application can store some critical information . Once user enters that data , it should be persisted .Is there any standard way to store that secure information . I can think of following places to store that informationI prefer for web...
Best place to keep secure information in java spring web application
Java : Is there a way to transform the Stringto the followingonly by using String.replaceAll ( regex , replacement ) method ? So far this is my best attempt : As you can see the output is incorrect . However , using the same regexp in Linux 's sed command gives correct output : <code> `` m1 , m2 , m3 '' `` m1/build , m...
Java regexp groups replacements
Java : java method return type is not the actual type . For example , returnType is TypeA , not TypeB . TypeB is a subclass of TypeA.How to get the actual return type of the method ? It is TypeB , not TypeA . UPDATEI used and then iterate through the methods . The method returns the superclass . Verified that getDeclar...
java method return type is not actual type
Java : I found an interesting case while testing with string creation and checking their hashcode.In first case i created string using copy constructor : Output of above code is : S1 : 816115710 S3:478684581This is expected output as interned string picks the reference from String pool whereas s1 picks reference of new...
Experimenting with String creation
Java : I am developing an android application in that , I have an group chat functionality when i am send a message on group chat i need to display message along with the time ( at the end of the message the time need to display on every chat message ) . `` @ +id/txtInfo '' used for get the current date and time & `` @...
How to display a message along with the time in groupchat ?
Java : I am trying to recognize that hosts are alive or dead with using executor in Java . In my case , I have severeal hosts which kept in a list . My goal is to create threads with the number of hosts and checking them . When thread connect with the host , host doesnt close the connection , and sending a situation co...
Java Executors Check TCP Connection Alive
Java : I was reading java.lang.String equals ignore case implementation and trying figure out why is there a lower case compare after upper case is already compared ? Are there languages where this matters , where upper cases may not match but lower cases may match ? <code> // Code from java.lang.String class public bo...
Java String ignore case implementation
Java : The method of an anonymous class behaves unexpectedly.How to make method sout to print `` sout '' , now it prints `` main '' ? <code> public class Solution { private String name ; Solution ( String name ) { this.name = name ; } private String getName ( ) { return name ; } private void sout ( ) { new Solution ( `...
The method of an anonymous class behaves unexpectedly
Java : Let 's say I have an interface in Java : , and also two classes C and D that implement this interface.Is there any way I can modify the interface such that I could only do : , but not ? I had this question on an exam , but my only idea was to use the instanceof operator in the definition of the method : However ...
Class implementing interface should be able to only add an object of the same class
Java : I 'm trying to initialize two variables with an enhanced switch statement : Is this possible ? <code> int num = //somethingboolean val1 ; String val2 ; val1 , val2 = switch ( num ) { case 0 - > ( true , `` zero ! `` ) ; case 1 - > ( true , `` one ! `` ) ; default - > ( false , `` unknown : / '' ) ; }
Can there be multiple value assignments for the enhanced switch statement ?
Java : I 'm trying to write a method , union ( ) , that will return an int array , and it takes two int array parameters and check if they are sets , or in other words have duplicates between them . I wrote another method , isSet ( ) , it takes one array argument and check if the array is a set . The problem is I want ...
Checking if two int arrays have duplicate elements , and extract one of the duplicate elements from them
Java : I am trying create option like SOS Module in my app , I create code to handle this : } I also add all required permissions in manifest and of course I check uses permission on time.But this no work . I just create other code but working like `` one flash '' without any cycle.Can you guys help me ? Guys this is i...
Option like SOSModule did n't work
Java : A stream should be operated on ( invoking an intermediate or terminal stream operation ) only once.I get the idea , but how come finding the sum of a stream does not consume it ? I can run the code below , without any exceptions.Why sum is not a terminal operator ? How is it different from collecting stream elem...
Consuming stream multiple times with Stream.sum ( )
Java : So , I will do my best to explain this question ... Basically , I have a GUI whose main window has several buttons on it ( probably about 10 ) . I am putting the buttons themselves in an array , but when it comes to handling click events for each button , something different is going to happen depending on which...
Is there a more efficient way to handle button click events than several if statements ?
Java : This is an example program in my AP Computer Science course , and I ca n't understand the flow of control of it.It outputs this : So far , I understand the recursive method and how it recalls itself via : However , I do n't see how it can output those five statements after : Logically , it seems like it would on...
Can someone explain the flow of control of this program ?
Java : When I run the following Java code : I get java.lang.Object in the display terminal , even if I replace Object [ ] [ ] .class.getName ( ) by [ [ Ljava.lang.Object in the code . The problem is that I was expecting the console to show [ [ Ljava.lang.Object.In effect , in the JVM specification , I can read the foll...
The ClassLoader can replace the array by anything
Java : I am creating a game where objects implement interfaces for animations . I have a parent interface for the animations . Here is a shortened version : In addition , I have multiple interfaces that extend this interface . Two examples : andAs you can see , the interfaces that extend Animates override the createAni...
Why ca n't I implement multiple interfaces ?
Java : The question : Is there a way to do code inspection for a method and check if it does n't have a parameter and warn me before compilation , or even give me a warning in my IDE.Let 's say I have an annotation @ InitializeAnd with reflect , I can invoke methods that are annotated with @ InitializeprioritzedMethods...
Check if method requires a parameter using annotation and reflect
Java : I have such for loop and when step is ( 0 ; 1 ) it becomes infinite . If step is [ 1 ; .. ) it works well . <code> public interface FindMinI { double function ( double x ) ; static double findMinOfFuncOnInterval ( int begin , int end , double step , FindMinI func ) { double min = Double.MAX_VALUE ; for ( int i =...
Why this for loop is infinite ?
Java : A Car has multiple manufactures and I want to gather all manufacturers in a Set.For example : Now , I need to create output that contains all manufactures ( without redundancy ) I tried : This gives me a Set of Lists , but I need to get rid of nesting and just create a single Set ( non nested ) . [ EDIT ] What i...
How to condense the following in Java 8
Java : I am a Java beginner and also new to this site . I am learning about arrays and methods and unfortunately I am stuckThe question is : A hospital has space for 150 patients . Each room has a space for 3 patients.The hospital charges a patient $ 150 to stay.If each room is occupied by 3 patients , the hospital cha...
Java College practice
Java : Hi I have a String ArrayList of ArrayList . A sample is shown below : Is it possible to get a list of unique values at index 1 for each value of index 0 ... The result I am expecting is : I was trying a series of if statements however did not work <code> [ [ 765 , servus , burdnare ] , [ 764 , asinj , ferrantis ...
Grouping in arrayList of arrayList
Java : My code looks sort of like this , but this is a simplified version : class A : class B : class Main : Why does a ( new B ( ) ) .testArgs ( new B ( ) ) print A not B ? Is there some sort of way to workaround/fix this ? edit : Clarification : What I really want is the superclass method to be run when it is called ...
Overriding trouble
Java : I 'm trying to download a file from an URL . There are many resources and I dont know which one I need to close or do I simply have to close all of them ? <code> public void downloadUpdate ( final String url ) { try { /* Which of these resources do I need to close ? */ final InputStream inputStream = new URL ( u...
Which resources should be closed ?
Java : I have the following class containing the fields specified below . My question is , must Admin , Worker and all my other self-defined classes implement Serializable for MyClass to be Serializable ? <code> public class MyClass implements java.io.Serializable { private static final long serialVersionUID = 1L ; Arr...
Java Serializable : Must E be serializable in ArrayList < E > ?
Java : First of all , yes , try-with-resource fixes any of these questions ... but I ca n't see how this exactly works without it.Let 's look at this code from the java documentation as an example , which can be found here : Now , the resource is released on br.close ( ) if it was acquired . However , What happens if n...
Does nested resource acquisition require special handling in Java ?
Java : I have two Set like this:And I want to merge it withand Error like this : enter image description hereHow can I convert Set to a serial of String object with flatMap ? Is there any other solution that can accomplish this operation gracefully ? <code> Set < String > set1 ; Set < String > set2 ; Set < String > s =...
How to merge set use java stream with one line of code
Java : Assume this code : For sure will throw an IndexOutOfBounds exception . My question is : There is some reason because Eclipse parser does not complain this issue with a warning or an error ? Analizing the case I find : It 's easy to detect.Will avoid lots of useless launches . There are other similar warnings/err...
Should n't Eclipse parser detect find this kind of IndexOutOfBounds exceptions ?
Java : I have been trying to reproduce ( and solve ) a ConcurrentModificationException when an instance of HashMap is being read and written by multiple Threads.Disclaimer : I know that HashMap is not thread-safe.In the following code : Basically , I make two threads : one keeps putting elements into a HashMap , the ot...
Does Collection.stream ( ) have internal synchronization ?
Java : Consider the following organization of classes : Since both the restaurants serve completely different sets of dishes , what will be the correct way ( design-wise ) to represent the type of dish in the interface ? Will it be a good design decision to define an Enum listing all the dishes -- Italian and Chinese -...
Should the interface define implementation specific enum values ?