lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | 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 that you... | public boolean onMousePressed ( MousePressedEvent e ) { Point p = new Point ( Mouse.getX ( ) , Mouse.getY ( ) ) ; if ( ! this.getBounds ( ) .contains ( p ) ) return false ; boolean left = ( e.getButton ( ) == MouseEvent.BUTTON1 ) ; boolean right = ( e.getButton ( ) == MouseEvent.BUTTON3 ) ; boolean hasItems = ( items.s... | 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 last m... | { token_id : “ tok_afgtryuo ” , ip_address : “ 128.123.45.1 “ , device_fingerprint : “ abcghift ” , card_hash : “ hgtyuigash ” , “ bin_number ” : “ 424242 ” , “ last4 ” : “ 4242 ” , “ name ” : “ Seu Jorge ” } public static void main ( String [ ] args ) throws Exception { StreamExecutionEnvironment env = StreamExecution... | 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 ? | `` 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 invoke the c... | public class Context { private final Class < ? > clazz ; private final String resource ; private final com.thirdparty.Context context ; public Context ( final String resource , final Class < ? > clazz ) { this.clazz = clazz ; this.resource = resource ; this.context = com.thirdparty.Context.newInstance ( this.clazz ) ; ... | 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 364.The a... | public static void main ( String [ ] args ) { List < Integer > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < 10000 ; i++ ) { int count = 0 ; Set < Integer > set = new HashSet < > ( ) ; while ( set.add ( ThreadLocalRandom.current ( ) .nextInt ( 0 , 365 ) ) ) { count++ ; } list.add ( count ) ; } double avg = list.... | 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 numerous ... | @ RunWith ( Suite.class ) @ SuiteClasses ( { com.example.test.MyTestCase.class } ) public class MyTestSuite extends BaseTestSuite { @ ClassRule public static FrameworkResource resource = new FrameworkResource ( ) ; @ BeforeClass public static void setup ( ) { loadProperties ( `` props/suite.properties '' ) } } | 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 ? | post_badge_format = You 've earned the `` { 0 } '' badge for { 1 } . String messageContent = MessageFormat.format ( messageType , paramValues ) ; You 've earned the `` XXX '' badge for XXX . You 've earned the `` { 0 } '' badge for { 1 } . | 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 type varia... | /** * The year being represented . */private final int year ; | 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 on , t... | private static boolean equals ( Object ... objects ) { Object obj = objects [ 0 ] ; boolean flag = false ; for ( Object object : objects ) { if ( object.equals ( obj ) ) { flag = true ; } else { flag = false ; break ; } } return flag ; } | 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 , so it ... | public class Generic { public static void main ( String [ ] args ) { Character [ ] arr3= { ' a ' , ' b ' , ' c ' , 'd ' , ' e ' , ' f ' , ' g ' } ; Integer a=97 ; System.out.println ( Non_genre.genMethod ( a , arr3 ) ) ; } } class Non_genre { static < T > boolean genMethod ( T x , T [ ] y ) { int flag=0 ; for ( T r : y... | 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 ? | public class FooService { private Client client ; public Foo get ( Long id ) { return client.get ( id , Foo.class ) ; } public List < Foo > query ( ) { return Arrays.asList ( client.get ( Foo [ ] .class ) ) ; } } public abstract class BaseService < T , I > { private Client client ; private Class < T > type ; public Bas... | 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 about or... | public abstract class Orbital { Body host ; protected double avgOrbitalRadius ; protected double orbitalPeriod ; public double getOrbitalRadius ( ) { return this.avgOrbitalRadius ; } public double getOrbitalPeriod ( ) { return this.orbitalPeriod ; } } public abstract class Orbitable { List < Body > satellites = new Arr... | 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 can the R... | nCount = 0 , bEnd = false nCount = 100 , bEnd = true main thread done.thread Reader running ... thread Writer running ... SharedData nCount = 0 , bEnd = falsethread Writer bEnd = truethread Reader nCount = 0 , bEnd = truethread Reader nCount = 100 , bEnd = truethread Reader nCount = 100 , bEnd = truethread Reader done ... | 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 , I 've... | The tournament begins ! Write `` jump '' to jump ; otherwise you quit : jumpRound 1//do somethingWrite `` jump '' to jump ; otherwise you quit : jump ( continues ) String command = `` placeholder '' ; while ( ! command.equals ( `` quit '' ) ) { System.out.println ( `` Write \ '' jump\ '' to jump ; otherwise you quit : ... | 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 arrayl... | public static void main ( String [ ] args ) { List < Integer > integers = new ArrayList < Integer > ( ) ; integers.add ( 1 ) ; addToList ( integers ) ; System.out.println ( integers ) ; } public static void addToList ( List list0 ) { list0.add ( `` blabl '' ) ; } | 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 t3 would... | public class Container { int a ; volatile boolean b ; public static void main ( String [ ] args ) { Container container = new Container ( ) ; Thread t1 = new Thread ( ) { @ Override public void run ( ) { for ( ; ; ) { container.a = 409 ; container.b ^= container.b ; } } } ; Thread t2 = new Thread ( ) { @ Override publi... | 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 of when... | public class TestFastThrow { public static void main ( String [ ] args ) { int count = 0 ; int exceptionStackTraceSize = 0 ; Exception exception = null ; do { try { throwsNPE ( 1 ) ; } catch ( Exception e ) { exception = e ; if ( exception.getStackTrace ( ) .length ! = 0 ) { exceptionStackTraceSize = exception.getStack... | 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 aggregation of... | public class Order { private String orderNumber ; private String customerNumber ; private String customerGroup ; private Date deliveryDate ; private double orderValue ; private double orderQty ; } public class OrderTotal { private String customerGroup ; private String customerNumber ; private double totalValue ; privat... | 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 explan... | public class Foo { private int n ; public Foo ( int n ) { this.n = n ; } public void check ( ) { if ( n ! = n ) throw new AssertionError ( `` huh ? `` ) ; } } | 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-8 : Wh... | java -versionPicked up _JAVA_OPTIONS : -Duser.country=US -Duser.language=en -Dfile.encoding=UTF-8openjdk version `` 11 '' 2018-09-25OpenJDK Runtime Environment 18.9 ( build 11+28 ) OpenJDK 64-Bit Server VM 18.9 ( build 11+28 , mixed mode ) public class PromotionTargetFileHandlerMain { public static final String uploadi... | 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 successfully .... | # ! /bin/shrunsql ( ) { i= '' $ 1 '' end= $ ( ( SECONDS+360 ) ) SECONDS=0 while ( ( SECONDS < end ) ) ; do echo `` INSERT into table_ $ i ( col1 ) values ( CURRENT_TIMESTAMP ) ; '' | sqlplus username/password sleep 1 done } for i in $ ( seq 1 10 ) ; do echo `` DROP TABLE table_ $ i ; '' | sqlplus username/password echo... | 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 code r... | System.out.print ( `` hello '' ) ; System.out.print ( name ) ; System.out.print ( `` \n '' ) ; System.out.print ( `` hello '' +name+ '' \n ) ; | 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 ) Now wher... | AssignedSelectMapper ( AssignedOpDtoMapper assignedOpDtoMapper , AssignedOrderDtoMapper assignedOrderDtoMapper// many more constructor parameters ) { this.assignedOptionCodeDtoMapper = assignedOptionCodeDtoMapper ; this.assignedOrderCriteriaDtoMapper = assignedOrderCriteriaDtoMapper ; // all settings } public List < As... | 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 ? | 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 = 6 ; //works A a = new A ( ) ; // a.first = 7 ; does not compile //works just fine , but why ? a.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 I make... | private void deleteFromDir ( String filename ) { String path = `` ./test/pacientes/ '' + filename + `` .tds '' ; File f = new File ( path ) ; System.out.println ( `` Abs path `` + f.getAbsolutePath ( ) ) ; System.out.println ( `` Exist `` + f.exists ( ) ) ; System.out.println ( `` Filename `` + f.getName ( ) ) ; System... | 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 : or : ... | Widget getMatchingWidget ( WidgetCriteria c ) throws Throwable try { Widget w = getMatchingWidget ( criteria ) ; processWidget ( w ) ; } catch ( Throwable t ) { handleError ( t ) ; } CompletableFuture < Widget > getMatchingWidget ( WidgetCriteria c ) CompletableFuture < Widget > f = getMatchingWidget ( criteria ) ; f.t... | 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 trigger... | @ Override public Spliterator < P_OUT > trySplit ( ) { if ( isParallel & & buffer == null & & ! finished ) { init ( ) ; Spliterator < P_IN > split = spliterator.trySplit ( ) ; return ( split == null ) ? null : wrap ( split ) ; } else return null ; } Arrays.asList ( 1,2,3,4,5 ) .stream ( ) .filter ( x - > x ! = 1 ) .spl... | 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 string cont... | test , asd,123 , testtest , test , test public static boolean stringHasOneValue ( String string ) { String value = null ; for ( split : string.split ( `` , '' ) ) { if ( value == null ) { value = split ; } else { if ( ! value.equals ( split ) ) return false ; } } return true ; } | 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 . | Object o =new Object ( ) ; | 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 involved is ... | Files.list ( somePath ) .map ( Path : :toRealPath ) .forEach ( System.out : :println ) R apply ( T t ) ; path - > path.toRealPath ( ) | 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 Bar bar t... | private Foo createAnonymousFoo ( final Bar bar ) { return new Foo ( ) { private Bar bar = SomeUnknownScopeQualifier.bar ; public Bar getBar ( ) { return bar ; } public void doSomethingThatReassignsBar ( ) { bar = bar.createSomeDerivedInstanceOfBar ( ) ; } } ; } | 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 ? | List < String > stringList = new ArrayList < > ( ) ; stringList.add ( `` 2 '' ) ; stringList.add ( `` 4 '' ) ; stringList.add ( `` 6 '' ) ; // String array ( `` 2 '' , '' 4 '' , `` 6 '' averageValue = stringList.stream ( ) .mapToInt ( s - > Integer.valueOf ( s ) ) .average ( ) .getAsDouble ( ) ; List < Integer > Intege... | 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 , what kin... | int x = 1 ; x = 2 ; x = 3 ; | 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 functio... | public interface UserDao { public User getById ( int id ) ; public Collection < User > getAll ( ) ; public boolean delete ( int userId ) ; public boolean update ( User u ) ; } | 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 the code... | @ OpenApi ( summary = `` '' , description = `` Lists all customers '' , path = `` customers '' , queryParams = // ... ... ... .. // ... ... ... .. // etc ) override fun handle ( context : Context ) { // body of the REST handler } @ GetCustomersDocoverride fun handle ( context : Context ) { // body of the REST handler } | 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 ? | The sorted array is [ 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ] import java.util.Scanner ; import java.util.Arrays ; public class SortArray { public static void main ( String [ ] args ) { Scanner kbd = new Scanner ( System.in ) ; int [ ] numbers = new int [ 8 ] ; for ( int i = 0 ; i < numbers.length ; i++ ) { System.out.println ... | 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 applicable f... | Set < Integer > mySet = Arrays.stream ( arr1 ) .map ( ele - > new Integer ( ele - 2 ) ) .collect ( Collectors.toSet ( ) ) ; | 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 . | class A { Date d = new Date ( ) ; public A ( ) { printDate ( ) ; } void printDate ( ) { System.out.println ( `` parent '' ) ; System.out.println ( d ) ; } } class B extends A { Date d = new Date ( ) ; public B ( ) { super ( ) ; } @ Override void printDate ( ) { System.out.println ( `` child '' ) ; System.out.println ( ... | 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 `` 203... | TimeZone.setDefault ( TimeZone.getTimeZone ( `` BET '' ) ) ; Locale.setDefault ( Locale.ENGLISH ) ; SimpleDateFormat sdf1 = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss.SSS '' ) ; SimpleDateFormat sdf2 = new SimpleDateFormat ( `` yyyy-MM-dd HH : mm : ss.SSS zzzz '' ) ; Date d0 = sdf1.parse ( `` 2037-10-17 23:00:00... | 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 ? | 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 the Ex... | public static void main ( String [ ] args ) throws IOException { throw new IOException ( ) ; //OK } | 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 ? | public class WeirdCode { public static int fooField = 42 ; public WeirdCode getFoo ( ) { return null ; } public static void main ( String args [ ] ) { WeirdCode foo = new WeirdCode ( ) ; System.out.println ( foo.getFoo ( ) .fooField ) ; } } | 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 shared c... | private static Object bootstrapDone = new Object ( ) ; public static void signalEsBoostrapCompleted ( ) { synchronized ( bootstrapDone ) { bootstrapDone.notifyAll ( ) ; } } public static void waitEsBoostrapCompleted ( ) throws InterruptedException { synchronized ( bootstrapDone ) { bootstrapDone.wait ( 20000 ) ; } } | 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 of extra... | < activity android : name= '' .ImageEditorActivity '' android : configChanges= '' keyboard|keyboardHidden|screenLayout|screenSize|orientation '' android : label= '' @ string/title_activity_image_editor '' android : parentActivityName= '' .MainActivity '' android : windowSoftInputMode= '' adjustResize|stateHidden '' and... | 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 can get ... | public class MyKeyListenerThread extends Thread implements MyKeyListener { /** * This is the overriden keyPressedEvent method , used * to respond to [ @ link MyKeyPressed ] events and pause or resume * [ @ link Player ] threads according to the source details . * * @ param evt The event the listener will respond to */ ... | 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 via th... | interface Foo { void testFoo ( ) ; } interface Bar { void testBar ( ) ; } interface Car < A > { A testCar ( ) ; } interface FooBar extends Foo , Bar { } interface FooCar < A > extends Foo , Car < A > { } public < T extends Foo & Bar > T implicitFooBar ( ) { return null ; } public < X , T extends Foo & Car < X > > T imp... | 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 . So ever... | public class Block { List < Block > neighBours ; public Block ( List < Block > neighBours ) { this.neighBours = neighBours ; } public Map < Block , Integer > getStepsAway ( ) { Map < Block , Integer > path = new HashMap < Block , Integer > ( ) ; getPaths ( path , 0 , 100 ) ; return path ; } public void getPaths ( Map <... | 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 ? | public class Test { public void method ( String foo ) { // This compiles if the curly braces are uncommented if ( foo instanceof Object ) // { Object bar = ( Object ) foo ; // } } } javac -Xlint : all Test.javaTest.java:5 : error : not a statement Object bar = foo ; ^Test.java:5 : error : ' ; ' expected Object bar = fo... | 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 ? | public class Bar { static void foo ( int ... x ) { System.out.println ( x ) ; } static void foo2 ( float ... x ) { System.out.println ( x ) ; } public static void main ( String args [ ] ) { Bar.foo ( 3,3,3,0 ) ; Bar.foo2 ( 3,3,3,1 ) ; Bar.foo ( 0 ) ; } } [ I @ 7a67f797 [ F @ 3fb01949 [ I @ 424c2849 | 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 appendi... | import java.io . * ; import java.nio.file . * ; public class FilePrepender // class name { public static void main ( String [ ] args ) { // make a giant dump file which we will append all read files into try { new File ( `` Output\\ '' ) .mkdirs ( ) ; File megaDumpFile = new File ( `` Output\\masterDump.txt '' ) ; if (... | 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 , duplicat... | [ { `` USER_1 '' : { `` APP_1 '' : { `` total '' :1 , `` totalGenuine '' :1 , `` totalDevelopment '' :1 } } , `` USER_2 '' : { `` APP_1 '' : { `` total '' :1 , `` totalGenuine '' :1 , `` totalDevelopment '' :1 } , `` APP_2 '' : { `` total '' :2 , `` totalGenuine '' :2 , `` totalDevelopment '' :2 } } } , { `` USER_1 '' ... | 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 ? | public static void add ( List l , Object o ) { l.add ( o ) ; } public static void main ( String [ ] args ) throws Exception { List < Integer > list = new ArrayList < Integer > ( ) ; add ( list , `` 1.23 '' ) ; add ( list , 1.23 ) ; System.out.println ( list ) ; } | 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 still ... | public class Course { private ArrayList < Student > students ; public Course ( ArrayList < Student > students ) { this.students = students ; } } public class Student { private Course course ; public Student ( Course course ) { this.course = course ; } } public class Student { private int courseId ; public Student ( int... | 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 ! | public class TestThread extends Thread { AtomicInteger counter = new AtomicInteger ( 0 ) ; @ Override public void run ( ) { System.out.printf ( `` % d\n '' , counter.addAndGet ( 1 ) ) ; } public static void main ( String [ ] args ) throws InterruptedException { ExecutorService es = Executors.newCachedThreadPool ( ) ; T... | 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 . | public class B { public B ( ) { } private void m0 ( ) { System.out.println ( `` BO '' ) ; } public void m1 ( ) { System.out.println ( `` B1 '' ) ; } public void test ( ) { this.m0 ( ) ; this.m1 ( ) ; } } public class D extends B { /** * */ public D ( ) { } public void m0 ( ) { System.out.println ( `` DO '' ) ; } public... | 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 storing the ... | BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; | 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 ? | package strings ; import java.util.Scanner ; public class P58Targil7 { public static Scanner in = new Scanner ( System.in ) ; public static void main ( String [ ] args ) { // TODO Auto-generated method stub String st2 = in.next ( ) ; check ( st2 ) ; } public static void check ( String st1 ) { char sec , fir ; for ( int... | 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 returns 1... | public class TestBigIntArraySize { public static int arraySize = 1000_000_000 ; public static int [ ] firstArray = new int [ arraySize ] ; public static int [ ] secondArray = new int [ arraySize ] ; public static void main ( String [ ] args ) { System.out.println ( 1000_000_000 * Integer.SIZE ) ; } } | 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 ! | int batchAmount = 10 ; for ( int i = 0 ; i < fullList.size ( ) ; i += batchAmount ) { List < List < object > > batchList = new ArrayList ( ) ; batchList.add ( fullList.subList ( i , Math.min ( i + batchAmount , fullList.size ( ) ) ) ; // Here I can do another for loop in batchList and do operations on each item } | 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 static final... | public class VisibilityTest { @ interface A { int f ( ) ; } @ A ( f = VisibilityTest.v ) //fails private static class C { int c = VisibilityTest.v ; //works } @ A ( f = v ) //works private static class D { int d = VisibilityTest.v ; //works } private final static int v = 5 ; } | 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/shortest/most... | Locale locale = Locale.CANADA_FRENCH ; DayOfWeek firstDayOfWeek = WeekFields.of ( locale ) .getFirstDayOfWeek ( ) ; List < DayOfWeek > dows = new ArrayList < > ( 7 ) ; // Set initial capacity to 7 , for the seven days of the week.dows.add ( firstDayOfWeek ) ; | 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 have s... | public static boolean execute ( String filename ) { // Perform some side effects ( e.g . write on DB ) return true ; // or false according to some criteria ; } public class Entrypoint { public static boolean myFunction ( String input ) { System.out.println ( `` executed ... '' + input ) ; return ! input.equals ( `` B '... | 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 : | List < Employe > listEmploye = new ArrayList < > ( ) ; for ( int i=0 ; i < ids.size ( ) ; i++ ) { Long idLong = Long.valueOf ( ids.get ( i ) ) ; BigDecimal idBig= BigDecimal.valueOf ( idLong ) ; listEmploye.add ( findByIdPointage ( idBig ) ) ; } | 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 method in A... | //javapublic class A { public void f ( ) { System.out.println ( `` A - > f ( ) '' ) ; x = x + 4 ; if ( x < 15 ) this.f ( ) ; //the f-call } public int x = 5 ; } public class B extends A { @ Override public void f ( ) { System.out.println ( `` B - > f ( ) '' ) ; x = x + 3 ; super.f ( ) ; } } public class Main { public s... | 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 time zo... | Instant time = Instant.now ( ) ; OffsetDateTime utc = time.atOffset ( ZoneOffset.UTC ) ; int utcTime = ( int ) utc.toEpochSecond ( ) ; int localTime = ( int ) time.getEpochSecond ( ) ; System.out.println ( `` utc `` + utcTime + `` local `` + localTime ) ; utc 1593762925local 1593762925 OffsetDateTime utc = time.atOffse... | 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 method . H... | package com.acme ; public class InheritableFoo extends Foo { public InheritableFoo ( ) { super ( ) ; } } | 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 string fo... | public static Boolean enumContains ( Enum en , String valueString ) { return toStringList ( en.values ( ) ) .contains ( valueString.toUpperCase ( ) ) ; } | 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 : | .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 work out.I... | private List < Entity > getPlanets ( ) { return entities.values ( ) .stream ( ) .filter ( x - > x instanceof Planet ) .collect ( Collectors.toList ( ) ) ; } | 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 connects c... | @ Overridepublic void run ( ) { try ( BufferedReader in = new BufferedReader ( new InputStreamReader ( client.getInputStream ( ) ) ) ; BufferedWriter out = new BufferedWriter ( new OutputStreamWriter ( client.getOutputStream ( ) ) ) ) { String input ; while ( true ) { input = readLine ( ) ; if ( input == null ) break ;... | 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 webserver ... | 1 ) In database2 ) On Webserver as different files for each user . We can encrypt data in those files using some key . 1 ) Where can we store those files on webserver2 ) How can we restrict access to those files ? 3 ) Is there something available in spring to achieve this ? 4 ) What kind of encryption library I can use... | 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 : | `` m1 , m2 , m3 '' `` m1/build , m2/build , m3/build '' System.out.println ( `` m1 , m2 , m3 '' .replaceAll ( `` ( [ ^ , ] * ) '' , `` $ 1/build '' ) ) ; > > > m1/build/build , m2/build/build , m3/build/build echo 'm1 , m2 , m3 ' | sed -e 's % \ ( [ ^ , ] *\ ) % \1/build % g ' > > > m1/build , m2/build , m3/build | 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 getDeclaredMetho... | public interface Foo < X extends TypeA > { public X hello ( ) ; } public class Bar implements Foo < TypeB > { @ Override public TypeB hello ( ) { ... } } Method method = Bar.class.getDeclaredMethod ( `` hello '' ) ; Class returnType = method.getReturnType ( ) ; Method [ ] methods = Bar.class.getDeclaredMethods ( ) ; | 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 object... | public class Test { /** * @ param args */ public static void main ( String [ ] args ) { String s1 = new String ( `` myTestString '' ) ; String s3 = s1.intern ( ) ; System.out.println ( `` S1 : `` + System.identityHashCode ( s1 ) + `` S3 : '' + System.identityHashCode ( s3 ) ) ; } } public class Test { /** * @ param arg... | 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 & `` @ +id/tx... | Here is my layout code < ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' android : paddingBottom= '' 5dp '' a... | 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 code such... | List < Host > hosts = LoadBalancer.getHostList ( ) ; ExecutorService executor = Executors.newFixedThreadPool ( hosts.size ( ) ) ; executor.submit ( ( ) - > { for ( Host host : hosts ) { try { connect ( host , '' message '' ,1 ) ; } catch ( Exception e ) { e.printStackTrace ( ) ; } } } ) ; public class Host { private St... | 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 from java.lang.String class public boolean regionMatches ( boolean paramBoolean , int paramInt1 , String paramString , int paramInt2 , int paramInt3 ) { char [ ] arrayOfChar1 = this.value ; int i = paramInt1 ; char [ ] arrayOfChar2 = paramString.value ; int j = paramInt2 ; if ( paramInt2 < 0 || paramInt1 < 0 ||... | 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 '' ? | public class Solution { private String name ; Solution ( String name ) { this.name = name ; } private String getName ( ) { return name ; } private void sout ( ) { new Solution ( `` sout '' ) { void printName ( ) { System.out.println ( getName ( ) ) ; } } .printName ( ) ; } public static void main ( String [ ] args ) { ... | 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 , I do ... | interface I { void add ( I foo ) ; } C c = new C ( ) ; c.add ( new C ( ) ) ; c.add ( new D ( ) ) ; class C implements I { public void add ( I foo ) { if ( foo instanceof C ) { System.out.println ( `` instance of C '' ) ; } else { System.out.println ( `` another instance '' ) ; } } } | 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 ? | 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 to chec... | public int [ ] union ( int [ ] array1 , int [ ] array2 ) { int count = 0 ; if ( isSet ( array1 ) & & isSet ( array2 ) ) { for ( int i = 0 ; i < array1.length ; i++ ) { for ( int j = 0 ; j < array2.length ; j++ ) { if ( array1 [ i ] == array2 [ j ] ) { System.out.println ( array2 [ j ] ) ; count ++ ; } } } } int [ ] arr... | 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 importan... | class SOSModule { private Camera camera ; private Camera.Parameters params ; private boolean isFlashOn ; void blink ( final int delay , final int times ) { Thread t = new Thread ( ) { public void run ( ) { try { for ( int i=0 ; i < times*2 ; i++ ) { if ( isFlashOn ) { turnOffFlash ( ) ; } else { Camera.open ( ) ; turnO... | 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 elements in... | double totalPrice = stream.mapToDouble ( product - > product.price ) .sum ( ) ; List < Product > products = stream.map ( this : :convert ) .collect ( Collectors.toList ( ) ) ; | 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 one is... | @ Overridepublic void actionPerformed ( ActionEvent e ) { if ( e.getActionCommand ( ) .equals ( `` Button1Text '' ) { /* do stuff */ } else if ( e.getActionCommand ( ) .equals ( `` Button2Text '' ) { /* do stuff */ } else if ( e.getActionCommand ( ) .equals ( `` Button3Text '' ) { /* do stuff */ } else if ( e.getAction... | 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 only stat... | public static void mystery ( int n ) { System.out.println ( `` mystery called with n = `` + n ) ; if ( n == 0 ) { System.out.println ( `` n is zero so no more recursive calls ! '' ) ; return ; } mystery ( n - 1 ) ; System.out.println ( `` We did it again with n = `` + n ) ; } public static void main ( String [ ] args )... | 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 following :... | ClassLoader c = new ClassLoader ( ) { @ Override public Class < ? > findClass ( String name ) { return Object.class ; } } ; Class < ? > cc = c.loadClass ( Object [ ] [ ] .class.getName ( ) ) ; System.out.println ( cc.getName ( ) ) ; | 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 createAnimator m... | public interface Animates < S extends Animator > { S createAnimator ( long animationTime ) ; } public interface AnimatesPaint extends Animates < PaintAnimator > { PaintAnimator createPaintAnimator ( long animationTime ) ; default PaintAnimator createAnimator ( long animationTime ) { return createPaintAnimator ( animati... | 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 ( Meth... | @ Retention ( RetentionPolicy.RUNTIME ) public @ interface Initialize { int priority ( ) ; } public static void initMethods ( Initializable clazz ) { TreeMap < Integer , Method > methods = prioritizedMethods ( clazz.getClass ( ) .getDeclaredMethods ( ) ) ; methods.forEach ( ( priority , method ) - > { try { method.setA... | 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 . | 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 = begin ; i < = end ; i += step ) { if ( func.function ( i ) < = min ) min = func.function ( i ) ; } return min ; } } | 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 if some ... | class Car { String name ; List < String > manufactures ; } object sedan - > { ford , gm , tesla } object sports - > { ferrari , tesla , bmw } object suv - > { ford , bmw , toyota } carList.stream ( ) .map ( c - > c.getManufacturers ( ) ) .collect ( Collectors.toSet ( ) ) ; | 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 charges an... | import javax.swing.JOptionPane ; public class Pingo { public static void main ( String [ ] args ) { final int MAXROOMS=50 ; int [ ] roomNumbers = new int [ MAXROOMS ] ; int [ ] patientQuantity = new int [ roomNumbers.length ] ; int numPatients=getNumberOfPatients ( roomNumbers , patientQuantity ) ; } public static int ... | 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 | [ [ 765 , servus , burdnare ] , [ 764 , asinj , ferrantis ] , [ 764 , asinj , ferrantis ] , [ 764 , asinj , ferrantis ] , [ 762 , asinj , ferrantis ] , [ 756 , peciam terre , cisterne ] , [ 756 , peciam terre , cortile ] , [ 756 , peciam terre , domo ] , [ 756 , asinj , ferrantis ] ] 765 - [ servus ] 764 - [ asinj ] 76... | 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 with an... | public class A { public void testArgs ( A a ) { System.out.println ( `` A '' ) ; } public void test ( ) { System.out.println ( `` A '' ) ; } } public class B extends A { public void testArgs ( B a ) { System.out.println ( `` B '' ) ; } public void test ( ) { System.out.println ( `` B '' ) ; } } public class Main { publ... | 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 ? | public void downloadUpdate ( final String url ) { try { /* Which of these resources do I need to close ? */ final InputStream inputStream = new URL ( url ) .openStream ( ) ; final ReadableByteChannel readableByteChannel = Channels.newChannel ( inputStream ) ; final FileOutputStream fileOutputStream = new FileOutputStre... | 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 ? | public class MyClass implements java.io.Serializable { private static final long serialVersionUID = 1L ; ArrayList < Admin > admins ; ArrayList < Worker > workers ; ArrayList < Manager > managers ; ArrayList < Secretary > secretaries ; ArrayList < Category > categories ; HashMap < Issue , HashMap < Category , Manager >... | 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 new File... | static String readFirstLineFromFileWithFinallyBlock ( String path ) throws IOException { BufferedReader br = new BufferedReader ( new FileReader ( path ) ) ; try { return br.readLine ( ) ; } finally { if ( br ! = null ) br.close ( ) ; } } static String readFirstLineFromFileWithFinallyBlock ( String path ) throws IOExce... | 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 ? | Set < String > set1 ; Set < String > set2 ; Set < String > s = Stream.of ( set1 , set2 ) .collect ( Collectors.toSet ( ) ) ; | 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/errors bei... | String [ ] data = new String [ 2 ] ; data [ 0 ] = `` OK '' ; data [ 1 ] = `` returning data '' ; data [ 2 ] = `` data out of bounds '' ; | 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 other is ... | import java.util . * ; public class MyClass { public static void main ( String args [ ] ) throws Exception { java.util.Map < String , Integer > oops = new java.util.HashMap < > ( ) ; oops.put ( `` 1 '' , 1 ) ; oops.put ( `` 2 '' , 2 ) ; oops.put ( `` 3 '' , 3 ) ; Runnable read = ( ) - > { System.out.println ( `` Entere... | 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 -- as a ... | interface Restaurant { public void dine ( Object dish ) ; } class ItalianRestaurant implements Restaurant { public void dine ( Object dish ) { // eat with spoon and forks } } class ChineseRestaurant implements Restaurant { public void dine ( Object dish ) { // eat with chopsticks } } | Should the interface define implementation specific enum values ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.