lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
While doing a project I wrote this line , basically it decided whether or not to merge the current node based on how many children there are . The problem is that succNodes will often be significantly larger than bucketingParam . And there 's no point to continue counting if I have already found a large enough sum . Wh...
int succNodes = Arrays.stream ( children ) .mapToInt ( PRQuadNode : :count ) .sum ( ) ; if ( succNodes < = bucketingParam ) { /* do something */ }
Java Stream sum ( ) short circuiting
Java
I have IconText that has image and text views inside it , both class and xml.I then populate the Spinner inside of the MainActivity with these IconTexts , using extended BaseAdapter ( IconTextAdapter ) as adapter.Now , IconText works fine ( shows as it should ) .Spinner however doesn't.When I start the app , it shows t...
< ? xml version= '' 1.0 '' encoding= '' utf-8 '' ? > < LinearLayout xmlns : android= '' http : //schemas.android.com/apk/res/android '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : orientation= '' horizontal '' > < ImageView android : id= '' @ +id/it_image '' android ...
Spinner updating only on user actions
Java
I 'd like to use an infinite loop in Java : for ( ; ; ) and I think it would look amusing if I could replace that ' ; ; ' with the variable 'ever'like this : Is such a thing possible in Java ?
String ever = `` ; ; '' ; for ( ever ) { ... }
How can I use for ( ever ) { } instead of for ( ; ; ) in Java
Java
In C # , I can create an instance of every custom class that I write , and pass values for its members , like this : This way of creating objects is called object creation expressions . Is there a way I can do the same in Java ? I want to pass values for arbitrary public members of a class .
public class MyClass { public int number ; public string text ; } var newInstance = new MyClass { number = 1 , text = `` some text '' } ;
Are there object creation expressions in Java , similar to the ones in C # ?
Java
Consider a method such as ConcurrentHashMap 's compute method : I would like to annotate this for nullability checking with checker framework : but this is n't quite right : I would like to be able to infer that it returns ? extends @ NonNull V in order to avoid a null check in the case where I know the remappingFuncti...
public V compute ( K key , BiFunction < ? super K , ? super V , ? extends V > remappingFunction ) public @ Nullable V compute ( K key , BiFunction < ? super K , ? super @ Nullable V , ? extends @ Nullable V > remappingFunction ) ; @ NonNull V value = map.compute ( key , ( k , v ) - > { if ( v == null ) { return new V (...
`` NonNull if the function returns non-null '' ?
Java
In Java8 I have a stream and I want to apply a stream of mappers.For example : I want to write : But my current best way of solving my task is : How can I solve this problemwithout collecting the mappers into a listwithout using a for loopwithout breaking my fluent code
Stream < String > strings = Stream.of ( `` hello '' , `` world '' ) ; Stream < Function < String , String > > mappers = Stream.of ( t - > t+ '' ? `` , t - > t+ '' ! `` , t - > t+ '' ? `` ) ; strings.map ( mappers ) ; // not working for ( Function < String , String > mapper : mappers.collect ( Collectors.toList ( ) ) ) ...
Apply a stream of mappers to another stream in Java8
Java
How to convert java int [ ] [ ] to Integer [ ] [ ] ? .It seems easy to convert single dimensional primitive array to Object type single dimensional array using java stream.For exampleIs there any way for two dimensional array like above ?
Integer [ ] result = IntStream.of ( intarray ) .boxed ( ) .toArray ( Integer [ ] : :new ) ;
Java 8 way to convert int [ ] [ ] to Integer [ ] [ ]
Java
I wrote a minimal somewhat-lazy ( int ) sequence class , GarbageTest.java , as an experiment , to see if I could process very long , lazy sequences in Java , the way I can in Clojure.Given a naturals ( ) method that returns the lazy , infinite , sequence of natural numbers ; a drop ( n , sequence ) method that drops th...
static int N = ( int ) 1e6 ; // succeeds @ N = ( int ) 1e8 with java -Xmx10m @ Testpublic void dropTest ( ) { assertThat ( drop ( N , naturals ( ) ) .head ( ) , is ( N+1 ) ) ; } // fails with OutOfMemoryError @ N = ( int ) 1e6 with java -Xmx10m @ Testpublic void nthTest ( ) { assertThat ( nth ( N , naturals ( ) ) , is ...
why does this Java method leak—and why does inlining it fix the leak ?
Java
Lets say I have the following code : and Node.getIterable ( ) returns an iterable . Does the getIterable ( ) function get called every time or only when the for loop is started ? Should I change it to :
for ( Object obj : Node.getIterable ( ) ) { //Do something to object here } Iterable < Object > iterable = new Iterable < Object > ( ) ; //populate iterable with objectsfor ( Object obj : iterable ) { //Do something }
Is the `` condition '' of a for loop called each time for Iterables ?
Java
From the Kotlin documentation page : In the code snippet above , I understand everything except that Class < T > thing . I assume it is the C # equivalent of the following : And the client code would say something like : But I ca n't be sure because that whole System.Type parameter seems redundant in the face of the ge...
// public final class Gson { // ... // public < T > T fromJson ( JsonElement json , // Class < T > classOfT ) // throws JsonSyntaxException { // ... public sealed class Gson { public T FromJson < T > ( JsonElement json , System.Type Type ) { } } var gson = new Gson ( ) ; var customer = gson.FromJson < Customer > ( json...
Could you please explain this piece of code in terms of C # code ?
Java
Suppose I have an outer class with an inner class inside . The inner class has four fields with all possible access modifiers . The inner class is private , so I ca n't create instances of it outside the Outer class . Inside the Outer class , if I create an instance of the inner class and try to change the value for ea...
class Outer { private class Inner { public int publicField ; protected int protectedField ; int packagePrivatefield ; private int privateField ; } void doSomethingWithFields ( ) { Inner inner = new Inner ( ) ; inner.publicField = 111 ; inner.protectedField = 111 ; inner.packagePrivatefield = 111 ; inner.privateField = ...
Is there any sense in access modifiers for fields of the private inner class ?
Java
I have two classes : AbstractMailingDirections and DirectionLoad . Both have a copy constructor as follows : and Now when I call the MailingDirections copy constructor ( which is just super ( toCopy ) ) I sometimes do n't get fields of the defaultDirection copied . Or not all of them . And using a Eclipse debugger is e...
public AbstractMailingDirections ( AbstractMailingDirections toCopy ) { this.message = toCopy.message ; this.defaultDirection = new DirectionLoad ( toCopy.defaultDirection ) ; for ( final DirectionLoad dls : toCopy.directionLoads ) { this.directionLoads.add ( new DirectionLoad ( dls ) ) ; } } public DirectionLoad ( Dir...
Weird copy constructor
Java
I have a PersonFactory interface as follows : The Person class : I want to be able to instantiate my Persons like this : Is there a way I could make the Java compiler automatically choose the right constructor by matching the signature of PersonFactory.create ( ) ?
@ FunctionalInterfacepublic interface PersonFactory < P extends Person > { P create ( String firstname , String lastname ) ; // Return a person with no args default P create ( ) { // Is there a way I could make this work ? } } public class Person { public String firstname ; public String lastname ; public Person ( ) { ...
Automatic constructor matching in default method
Java
TL ; DR : After much trial and error , it appears as though the issue is Tomcat related , maybe in regards to the configured java versions , rather than the java language itself . See 'Edit 3 ' below for more details.I have been using Java 8 streams and Comparators for awhile now and have never seen this type of behavi...
public static final Comparator < ServiceRequest > BY_ACTIVITY_DATE_DESC = Comparator.comparing ( ServiceRequest : :getActivityDate , Comparator.nullsLast ( Comparator.reverseOrder ( ) ) ) ; @ Testpublic void testComparator_BY_ACTIVITY_DATE_DESC ( ) { ServiceRequest olderRequest = new ServiceRequest ( ) ; olderRequest.s...
Why is the same Comparator acting differently in unit tests vs. when run as a web app ?
Java
I have a .jrxml file and I would like to pass some params from the code to it . I have an Order class that has fields like double price , int quantity and Product product . The situation is simple , when i need to pass price or quantity , I just do something like this : The problem appears when I try to pass product.ge...
< textFieldExpression class = `` java.lang.Integer '' > < ! [ CDATA [ $ F { quantity } ] ] > < /textFieldExpression > < textFieldExpression class = `` java.lang.String '' > < ! [ CDATA [ $ F { product } .getName ( ) ] ] > < /textFieldExpression >
How to get the value of complex JavaBean
Java
My task is to filter an array , change the remaining elements and return the array with both the changed and unchanged values . My code : How can I return an array of the changed and unchanged values ?
return Arrays.stream ( sentence.split ( `` `` ) ) .filter ( /* do some filter to each value */ ) .map ( /* map this value*/ ) .collect ( Collectors.joining ( ) ) ;
Access all elements after stream filter
Java
Is there a library ( e.g . Apache , Guava ) that provides a List < T > with a method that adds the element if it is present , ( and is a no-op if ! element.isPresent ( ) ) ? Obviously easy to implement , but it seems like such an obvious thing it seems someone might have done it already .
void add ( Optional < T > element )
Java List < T > that conditional adds Optional < T >
Java
I see that java-10 adds a constructor for IntSummaryStatistics ( LongSummaryStatistics and DoubleSummaryStatistics ) that takes 4 parameters that are count , min , max and sum.I understand why the no-args constructor exists , so that it would be used in reduction , like : That makes sense , but why is there a need to a...
..stream ( ) .collect ( Collectors.summarizingInt ( Class : :someFunction ) )
XXXSummaryStatistics new constructor in java-10
Java
I am a Java programmer taking baby steps into Scala programming.I have defined a function similar to ( which may be idiomatically wrong , I would n't know ... ) : So the function receives 3 parameters , processes the first two in sequence , takes the results of the processing and passes it along to the someToBeReplaced...
def someGenericAlgorithm ( param1 : String , param1 : String , param3 : String ) = { val triedResult1 = someFunction ( param1 ) triedResult1 match { case Success ( result1 ) = > val triedResult2 = someOtherFunction ( param2 ) triedResult2 match { case Success ( result2 ) = > val triedPolymorphicResult = someToBeReplace...
Scala : how to implement via function object parameters a generic flow where signatures differ ?
Java
I am preparing myself for Java certification test and I have found an interesting question related to the execution of Java static blocks . I have spent a lot of time reading about this topic , but I did n't find the answer I was looking for.I know that static blocks are executed when the class is loaded into JVM or wh...
package oneClassTasks ; class Parent { static int age ; } class Child extends Parent { static { age = 5 ; System.out.println ( `` child 's static block '' ) ; } } public class XXX { public static void main ( String args [ ] ) { System.out.println ( `` Child age is : `` + Child.age ) ; } } Child age is : 0 ... [ Loaded ...
Execution of Java static blocks in subclasses
Java
I have created a List of Contacts that 's working but when I click on any contact I only get contact Number of 1st Item on the android screen from the ListView.I want to get Phone Number of clicked contact of that position.I have searched on web everywhere but did n't get any solution , i am trying to solve this issue ...
li.setOnItemClickListener ( new AdapterView.OnItemClickListener ( ) { @ Overridepublic void onItemClick ( AdapterView < ? > parent , View view , int position , long id ) { TextView txtNummber = li.findViewById ( android.R.id.text2 ) } } ) ;
How to get a phone_Number from contacts ListView on onItemClicklistener
Java
I have two interfaces which is responsible for holding a closureHere is the first one for holding the closure when it comes to a map operation.And the second one for filtering operationsI have a class named CList which is capable of working with closures.Here is my public interface implementing CList with closures.And ...
package com.fs ; /** * This interface is responsible for holding the closures when it comes to map . * It uses two generic types . One for the argument and one for the return type . * @ param < B > Generic type * @ param < A > Generic type */public interface Func < B , A > { /** * Function prototype m takes an argument...
Converting a recursive implementation to a loop based implementation
Java
I 'm new to Spring . Currently starting with xml configuration , so please do n't say to use Annotations.I was reading about autowiring 'byName ' , and i 'm confused on how it works.My Config file -StudentServiceQuery class- } Name of the class for bean name `` StudentRepositor '' is `` StudentRepository '' Autowiring ...
< bean name= '' StudentRepositor '' class= '' com.sample.Repository.StudentRepositoryHibernate '' / > < bean name= '' StudentService '' class= '' com.sample.Service.StudentServiceQuery '' autowire= '' byName '' > < ! -- < property name= '' StudentRepositor '' ref= '' StudentRepositor '' / > -- > < /bean > public class ...
Autowiring in spring 'byName ' not working
Java
No `` if '' statements , please , unless you 're explaining why it 's impossible to do without one.I 'm seeing how far I can go operating on streams only . I have this nuisance : My best idea for how to do this without an `` if '' isIs there a way to do this in one chain only ? A branch basically has to happen in the s...
List < Cube > revised = cubes.filter ( p ) .map ( c - > f ( c ) ) .map ( c - > { if ( c.prop ( ) ) { c.addComment ( comment ) ; } return c ; } ) .collect ( Collectors.toList ( ) ) ; List < Cube > revised = cubes.filter ( p ) .map ( c - > f ( c ) ) ; revised .filter ( Cube : :prop ) .forEach ( c - > c.addComment ( comme...
Java 8 forEach applied to only some ?
Java
If the method call takes more than 10 seconds I want to kill it and move on.Is multi-threading my only option to solve this problem ? If I go with multi-threading which I 'm very new at , my run method would only contain the one method as follows . If myMethod ( ) gets stuck in an infinite loop is there a way to interr...
public void run ( ) { myMethod ( ) ; } while ( true ) { System.out.println ( `` Thinking . `` ) ; for ( int i = 0 ; i < 100000 ; i++ ) { //wasting time } }
I 'm calling a method in java which I have no control of . If I do n't get a response from it , I want to kill it and move on
Java
I 've tried the above for rounding my number to 1 decimal place but in cases where there are no decimal numbers , it seems to round to an integer value ( for example 2.0 would be displayed as 2 ) . I want 2.0 , as well as any other input number to display in 1 decimal place . Also , when DecimalFormat rounds a negative...
double number = Scanner.nextDouble ( ) ; DecimalFormat df = new DecimalFormat ( `` # . # '' ) ; System.out.print ( df.format ( number ) ) ;
Java strange rounding with DecimalFormat
Java
When I first started learning java GUI ( swing ) programming the way I was shown was more of an MVC model which involved using interfaces to call things and pass variables across classes . I recently started programming in a more static way , having a Jframe call its static Jpanel 's and using static methods to change ...
private static Toolbar toolbar = new Toolbar ( ) ; Home.toolbar.setForeground ( Color.green ) ;
Java - Static Programming Style
Java
I am working on Project Euler problem 14 in Clojure . I have what I feel is a good general algorithm , and I am getting the correct result , but I am struggling to understand why my function is so slow compared to ( what I believe to be ) an equivalent function in Java . Here 's my Clojure function to get the length of...
( defn collatz-length [ n ] ( loop [ x n acc 1 ] ( if ( = 1 x ) acc ( recur ( if ( even ? x ) ( / x 2 ) ( inc ( * 3 x ) ) ) ( inc acc ) ) ) ) ) public static int collatzLength ( long x ) { int count = 0 ; while ( x > 1 ) { if ( ( x % 2 ) == 0 ) { x = x / 2 ; } else { x = ( x * 3 ) + 1 ; } count++ ; } return count ; } (...
What 's slowing this Clojure function down ?
Java
While moving from CMS to G1 for some of our applications , I noticed that one of them suffered from a startup time extended by factor 4 . Application stop time due to GC cycles is not the cause . On comparing application behaviour , I disovered that this one carries a whopping 250 million of live objects after startup ...
import java.util.HashMap ; /** * Allocator demonstrates the dependency between number of live objects * and allocation speed , using various GC algorithms . * Call it using , e.g . : * java Allocator -Xmx12g -Xms12g -XX : +PrintGCApplicationStoppedTime -XX : +UseG1GC * java Allocator -Xmx12g -Xms12g -XX : +PrintGCAppli...
Does allocation performance degrade on a large number of live instances when using G1 ?
Java
I have text I 'm trying to extract from LogicalID and SupplyChain fromAt first I used the following regex : This matched as follows : In a fit of desperation , I tried using the asterisk instead of the plus : This matched perfectly . The documentation says * matches zero or more times and + matches one or more times . ...
< LogicalID > SupplyChain < /Logical > .* ( [ A-Za-z ] + ) > ( [ A-Za-z ] + ) < . * [ `` D '' , `` SupplyChain '' ] .* ( [ A-Za-z ] * ) > ( [ A-Za-z ] + ) < . *
Why is the star quantifier greedier than the plus quantifier in Java regular expressions ?
Java
The task is to find lost element in the array . I understand the logic of the solution but I do n't understand how does this formula works ? Here is the solutionBut why we add 1 to total size and multiply it to total size + 2 /2 ? ? In all resources , people just use that formula but nobody explains how that formula wo...
int [ ] array = new int [ ] { 4,1,2,3,5,8,6 } ; int size = array.length ; int result = ( size + 1 ) * ( size + 2 ) /2 ; for ( int i : array ) { result -= i ; }
Meaning of the formula how to find lost element in array ?
Java
I have the following method which is working fine . I am trying to accomplish everything and get the value inside that Optional stream without having to do the additional if check . Is it possible to map and get the Result object at index 0 ? Please advice thanks .
public String getData ( HttpEntity < Request > request , String endPoint ) { ResponseEntity < Reponse > response = template.exchange ( endPoint , HttpMethod.POST , request , Reponse.class ) ; List < Result > results = Optional.ofNullable ( response ) .map ( ResponseEntity : :getBody ) .map ( Response : :getQueryResult ...
How to map value at index 0 for a list in an Optional Stream
Java
I am trying to build a Java Spring Boot application that would post & get the messages from Confluent Cloud Kafka.I followed the article for publishing a Kafka message into Confluent Cloud and it works.Below is the implementationKafkaController.javaProduct.javaProducer.javaConfluentBootApplication.javaapplication.prope...
package com.seroter.confluentboot.controller ; import org.springframework.beans.factory.annotation.Autowired ; import org.springframework.http.HttpStatus ; import org.springframework.http.ResponseEntity ; import org.springframework.web.bind.annotation.PostMapping ; import org.springframework.web.bind.annotation.Request...
Confluent Cloud - Spring Boot Consumer REST Endpoint ?
Java
FindBugs complains about Possible null pointer dereference of str1 on branch that might be infeasible in Comparator.compareStrings ( String , String ) in this method : In Eclipse , I also see a warning on the last line ( str1 may be null ) .Under what circumstances can str1 be null in return str1.equals ( str2 ) ? COMP...
private static int compareStrings ( final String str1 , final String str2 ) { if ( ( str1 == null ) & & ( str2 == null ) ) { return COMPARE_ABSENT ; } if ( ( str1 == null ) & & ( str2 ! = null ) ) { return COMPARE_DIFFERS ; } if ( ( str1 ! = null ) & & ( str2 == null ) ) { return COMPARE_DIFFERS ; } return str1.equals ...
How can a variable be null in this piece of code ?
Java
I was referring to the java language specification to understand the use of super . While I understand the first use case i.e . The form super.Identifier refers to the field named Identifier of the current object , but with the current object viewed as an instance of the superclass of the current class.I ca n't seem to...
class S { int x=0 ; } class T extends S { int x=1 ; class C { int x=2 ; void print ( ) { System.out.println ( this.x ) ; System.out.println ( T.this.x ) ; System.out.println ( T.super.x ) ; } } public static void main ( String args [ ] ) { T t=new T ( ) ; C c=t.new C ( ) ; c.print ( ) ; } }
Understanding the use of Super to access Superclass members
Java
I have a collection like : List < List < Object > > firstListI want to group together a similar list of pattern : List < List < Object > > secondList but grouped by indexes.say I want to group this collection as What I have tried so far is But I am not getting what is expected.I am using java 8.EDIT : ALL THE LIST ARE ...
firstList [ 1 ] : 0 = { Object A } '' 1 = { Object B } '' 2 = { Object C } '' firstList [ 2 ] : 0 = { Object A } '' 1 = { Object B } '' 2 = { Object C } '' secondList [ 1 ] : 0 = { Object A } '' 1 = { Object A } '' secondList [ 2 ] : 0 = { Object B } '' 1 = { Object B } '' secondList [ 3 ] : 0 = { Object C } '' 1 = { O...
Collecting a collection of list based on similar index
Java
A Stream is an AutoCloseable and if I/O-based , should be used in a try-with-resource block . What about intermediate I/O-based streams which are inserted via flatMap ( ) ? Example : vs.The flatMap ( ) documentation says : Each mapped stream is closed after its contents have been placed into this stream.Well , that 's ...
try ( var foos = foos ( ) ) { return foos.flatMap ( Foo : :bars ) .toArray ( Bar [ ] : :new ) ; } try ( var foos = foos ( ) ) { return foos.flatMap ( foo - > { try ( var bars = foo.bars ( ) ) { return bars ; } } ) .toArray ( Bar [ ] : :new ) ; }
Should I use try-with-resource in flatMap for an I/O-based stream ?
Java
I do n't understand why this confuses the compiler . I 'm using the generic type T to hold an object that 's not related to the put and get methods . I always thought GenericClass and GenericClass < Object > were functionally identical , but I must be mistaken . When compiling the DoesntWork class I get incompatible ty...
public class GenericClass < T > { public < V > void put ( Class < V > key , V value ) { // put into map } public < V > V get ( Class < V > key ) { // get from map return null ; } public static class DoesntWork { public DoesntWork ( ) { GenericClass genericClass = new GenericClass ( ) ; String s = genericClass.get ( Str...
Why does this class behave differently when I do n't supply a generic type ?
Java
I got the following exception while executing my software : It surprises me that there is a sleeping time limit and that the standard library exception message has bad grammar/a typo ( to 0 to ? ) . After checking the source code of the delay ( ) method , I noticed that it restricts the waiting time as the exception st...
Exception in thread `` main '' java.lang.IllegalArgumentException : Delay must be to 0 to 60,000ms at java.awt.Robot.checkDelayArgument ( Robot.java:544 ) at java.awt.Robot.delay ( Robot.java:534 ) at com.company.Main.main ( Main.java:10 ) /** * Sleeps for the specified time . * To catch any < code > InterruptedExcepti...
Why is Robot.delay ( int ms ) limited to 1 minute ?
Java
I have a collection which has a field of type Set with some values . I need to create a new set collecting all these values.I am wondering if this is possible using lambda expressions.Below is the code line : The problem is post map operation , it contains a collection of set of strings . So collect operation returns a...
Set < String > teacherId = batches.stream ( ) .filter ( b - > ! CollectionUtils.isEmpty ( b.getTeacherIds ( ) ) ) .map ( b - > b.getTeacherIds ( ) ) .collect ( Collectors.toSet ( ) ) ;
Collect all values of a Set field
Java
New to java 8 , I would like to optimise my code bellow : I have a lot of methods using this same way to catch exceptions and do the same finally , is that possible to replace the bellow common code by a method in java 8 ? So that I could optimise all my methods who use this common code .
public Response create ( ) { try { ... } catch ( Exception e ) { codeA ; } finally { codeB ; } } public Response update ( ) { try { ... } catch ( Exception e ) { codeA ; } finally { codeB ; } } } catch ( Exception e ) { codeA ; } finally { codeB ; }
How to regroup catch finally into one method in java 8 ?
Java
I 'm a web dev ( game dev as a hobby ) , and I 've seen myself use the following paradigm several times . ( Both in developing server architecture and with video game dev work . ) It seems really ugly , but I do n't know a work around . I 'll give an example in game dev , because it 's where I recently noticed it . Thi...
public class Combatant { ArtificialIntelligence ai = null ; public Combatant ( ) { // Set other fields here . this.ai = new ArtificialIntelligence ( this ) ; } }
Weird reference passing in class construction
Java
I wrote a simple class that uses AbstractQueuedSynchronizer . I wrote a class that represents a `` Gate '' , that can be passed if open , or is blocking if closed . Here is the code : Unfortunately , if a thread blocks on pass method because gate is closed and some other thread opens the gate in meantime , the blocked ...
public class GateBlocking { final class Sync extends AbstractQueuedSynchronizer { public Sync ( ) { setState ( 0 ) ; } @ Override protected int tryAcquireShared ( int ignored ) { return getState ( ) == 1 ? 1 : -1 ; } public void reset ( int newState ) { setState ( newState ) ; } } ; private Sync sync = new Sync ( ) ; p...
AbstractQueuedSynchronizer.acquireShared waits infinitely even that waiting condition has changed
Java
I am trying to recursively find all inner exceptions ( getCause 's ) from a top level exception ... of a specific instance type.Here is what I 've tried : and my early `` find '' method : It is not working . : ( I 've tried several other things ( not shown yet ) ... I 'll post them as `` appends '' to this question if ...
public class MyCustomRunTimeException extends RuntimeException { public MyCustomRunTimeException ( ) { } public MyCustomRunTimeException ( Exception innerException ) { super ( innerException ) ; } } private void findAllSpecificTypeOfInnerExceptions ( Exception ex ) { Collection < MyCustomRunTimeException > MyCustomRunT...
Finding specific type of custom exception on all inner exceptions
Java
While investigating Why ThreadPoolExecutor behaves differently when running Java program in Eclipse and from command line ? I wrote a test that throws a very strange OutOfMemoryError ( max mem = 256 Mb ) comment out int i = 1 and the test works . As far as I understand when finalize is empty HotSpot simply ignores it ....
class A { byte [ ] buf = new byte [ 150_000_000 ] ; protected void finalize ( ) { int i = 1 ; } } A a1 = new A ( ) ; a1 = null ; A a2 = new A ( ) ;
How can one ` finalize ` invocation break GC / JVM ?
Java
Let 's say we have a few test interfaces/classes like this : You can see Animal.eat is a generic method with constraints . Now I have my Human class like this : which compiles fine . You can see Human.eat is less constrained than Animal.eat because the Eatable interface is lost.Q1 : Why does n't the compiler complain a...
abstract class Plant { public abstract String getName ( ) ; } interface Eatable { } class Apple extends Plant implements Eatable { @ Override public String getName ( ) { return `` Apple '' ; } } class Rose extends Plant { @ Override public String getName ( ) { return `` Rose '' ; } } interface Animal { < T extends Plan...
Why a generic method of an interface can be implemented as non-generic in Java ?
Java
I am fully aware this question was asked many times , but I can not find an answer to it . : /I have one parametrized class : And several static objects of this class : The problem is that I have to omit diamond operator and stick to unchecked cast of MessageType to MessageType < List < String > > in the last line.I wo...
public class MessageType < T > { private final Class < T > clazz ; public MessageType ( final Class < T > clazz ) { this.clazz = clazz ; } public Class < T > getClazz ( ) { return clazz ; } } static final MessageType < String > TYPE_A = new MessageType < > ( String.class ) ; static final MessageType < Double > TYPE_B =...
How to extract class from Java generic class to satisfy compiler ?
Java
I have a simple problem : I iterate a large and deeply nested directory structure using Files.walkFileTree like this : My goal is to add all files under a specific directory target that I know is at most CUTOFF levels under codeRoot.I 'm looking for a more efficient way to do this in terms of necessary stat ( ) calls o...
final int CUTOFF = 5 ; final List < Path > foundList = new ArrayList < > ( ) ; Files.walkFileTree ( codeRoot , new SimpleFileVisitor < Path > ( ) { @ Override public FileVisitResult preVisitDirectory ( Path dir , BasicFileAttributes attrs ) throws IOException { String rPath = codeRoot.relativize ( dir ) .toString ( ) ;...
Efficently find files in specific directories
Java
Usually we implement Comparable with a type-parameter of B . But java allows using a super class , as well . Is there a scenario where I really need to do something like this ?
class A { ... } class B extends A implements Comparable < A > { int compareTo ( A aobject ) { ... } }
When to implement Comparable < super class of X > instead of Comparable < X > ?
Java
I 'm working on a problem that I 'm a little confused on . The question says imagine you 're a general of the British Air Force during WW2 . You have 100 planes left to defend the United Kingdom . With each mission you fly each plane has a 50 % chance of getting shot down by the German anti aircraft guns so every missi...
import acm.program . * ; import acm.util . * ; public class MissionPlanes extends ConsoleProgram { public void run ( ) { int planes = 100 ; /* total number of planes */ int suvPlanes = 0 ; /* surviving planes */ int mission = 0 ; /* total number of missions */ int planeCounter = 0 ; /* keeps track of the planes flying ...
RandomGenerator - Losing 50 % of planes simulation
Java
Suppose I have a blocking method called check as follows : which will do some check against the input and return the decision.Now I want to run this check against a list of inputs asynchronously , and I want to return to the main thread right after one of the inputs passing the check , so I do n't have to wait for all ...
boolean check ( String input ) { }
Java asynchronously call a method for target output
Java
I have been working on requirement and I need to create a regex on following string : There can be many variations of this string as follows : startDate in above expression is a key name which can be anything like endDate , updateDate etc . which means we cant hardcode that in a expression . The key name can be accepte...
startDate : [ 2016-10-12T12:23:23Z:2016-10-12T12:23:23Z ] startDate : [ * ; 2016-10-12T12:23:23Z ] startDate : [ 2016-10-12T12:23:23Z ; * ] startDate : [ * ; * ] Pattern.compile ( `` ( [ [ a-zA-Z_0-9 ] * ) : ( \\ [ [ [ \\* ] | [ 0-9 ] { 4 } - [ 0-9 ] { 2 } - [ 0-9 ] { 2 } T [ 0-9 ] { 2 } : [ 0-9 ] { 2 } : [ 0-9 ] { 2 }...
Regex not capturing matching in expected groups
Java
I have a Validator interface which provides a isValid ( Thing ) method , returning a ValidationResult which contains a boolean and a reason message.I want to create a ValidatorAggregator implementation of this interface which performs an OR across multiple Validators ( if any Validator returns a positive result , then ...
public ValidationResult isValid ( final Thing thing ) { return validators.stream ( ) .map ( v - > validator.isValid ( thing ) ) .filter ( ValidationResult : :isValid ) .findFirst ( ) .orElseGet ( ( ) - > new ValidationResult ( false , `` All validators failed ' ) ) ; } public ValidationResult isValid ( final Thing thin...
Return first result matching predicate in a Java stream or all non-matching results
Java
Okay , I was trying to do some conditional checks and noticed this returned false ... . Something I 'm missing ?
int test = 1 ; int [ ] testing= { 1,3 } ; System.out.println ( Arrays.asList ( testing ) .contains ( test ) ) ; //false ? ? ?
Java list.contains returning false , should be true
Java
I made this snippet to show my problem : date1 and date2 are expressed in seconds , so I 'm expecting two different dates in output , but the dates are printed the same . I checked inside this online tool , and as you can see the dates are related to two different days.How can I solve this ?
import java.text.SimpleDateFormat ; public class Foo { public static void main ( String [ ] args ) { SimpleDateFormat formatter = new SimpleDateFormat ( `` mm hh dd MM yyyy '' ) ; String date1 = `` 1412293500 '' ; String date2 = `` 1412336700 '' ; String dateString1 = formatter.format ( Long.parseLong ( date1 + `` 000 ...
Retrieve two equal dates from SimpleDateFormat in java
Java
I am using wikidata api to fetch a entity using its english title , Earlier , with an older version of wikidata-api , I was able to run it smoothly.After updating to version 5.0.0 , I always get the following error , How to fix this ?
wdf = WikibaseDataFetcher.getWikidataDataFetcher ( ) ; eid = wdf.getEntityDocumentsByTitle ( `` enwiki '' , entitle ) ; Exception in thread `` main '' java.lang.NullPointerException at org.wikidata.wdtk.wikibaseapi.ApiConnection.fillCookies ( ApiConnection.java:544 ) at org.wikidata.wdtk.wikibaseapi.ApiConnection.sendR...
Wikidata API always returns a Null Pointer Exception
Java
In the new date package in Java 8 , we changed from using `` new Date ( ) '' to `` LocalDate.of ( ) '' .When you want a new object you usually use the new keyword . This is an intuitive way to create a new object.Sometimes , when you need a singleton with delayed initialization you can use a static method to get the in...
Date d = new Date ( year , month , dayOfMonth ) ; //Old wayLocalDate d2 = LocalDate.of ( year , month , dayOfMonth ) ; //new way
Why does java.time use 'of ' instead of 'new ' for dates ?
Java
I 'm making a text editor which finds a string in the first line of a text and highlights it and its occurrences throughout the text . The problem is that it also highlights the occurrences located in the comment lines ( started with `` # '' ) . This is my code so far : How can I edit this code to avoid highlighting of...
import javax.swing . * ; import javax.swing.event.DocumentEvent ; import javax.swing.event.DocumentListener ; import javax.swing.text.BadLocationException ; import javax.swing.text.DefaultHighlighter ; import javax.swing.text.Highlighter ; import java.awt . * ; import java.util.logging.Level ; import java.util.logging....
How to avoid text highlighting of a string in a line starting with a specific symbol [ java ]
Java
Answering a question here at SO , I came up to a solution which would be nice if it would be possible extend the Class class : This solution consisted on trying to decorate the Class class in order to allow only certain values to be contained , in this case , classes extending a concrete class C. I know this code does ...
public class CextenderClass extends Class { public CextenderClass ( Class c ) throws Exception { if ( ! C.class.isAssignableFrom ( c ) ) //Check whether is ` C ` sub-class throw new Exception ( `` The given class is not extending C '' ) ; value = c ; } private Class value ; ... Here , methods delegation ... } public cl...
Why is ` Class ` class final ?
Java
I am having one of those weird moments . Output : Every time I run this , the new object always gives the same Hex String ( Java doc Integer.toHexString ( hashCode ( ) ) ) , why is this ? Why does n't this produce a different String each time ? Or is it reusing the same object because it can ? EDIT : I tried executing ...
ArrayList < Object > a = new ArrayList < Object > ( ) ; a.add ( new Socket ( ) ) ; a.add ( new Thread ( ) ) ; a.add ( `` three '' ) ; a.add ( a ) ; a.add ( new Object ( ) ) ; for ( Object output : a ) { System.out.println ( output ) ; } Socket [ unconnected ] Thread [ Thread-0,5 , main ] three [ Socket [ unconnected ] ...
` new Object ( ) ' does not seem to create a new object , why ?
Java
The api for Stream.max requires an argument of type Comparator < ? super T > , and for Comparator , the only abstract method is but Double : :compareTo , the compareTo api iswhy just provide one argument , so why can Double : :compareTo use as argument of Stream
int compare ( T o1 , T o2 ) public int compareTo ( Double anotherDouble ) Optional < T > max ( Comparator < ? super T > comparator )
Why Double : :compareTo can be used as an argument of Stream.max ( Comparator < ? super T > comparator )
Java
I 'm studying generics in this period and today I 've found this mystery for me.Let 's consider the following dummy class : Because of erasure , at runtime , the T [ ] return type of the getArray ( ) method is turned into a Object [ ] , which is completely reasonable to me.If we access that method as it is ( c.getArray...
public class Main { public static void main ( String [ ] args ) { Container < Integer > c = new Container < Integer > ( ) ; c.getArray ( ) ; //No Exception //c.getArray ( ) .getClass ( ) ; //Exception //int a = c.getArray ( ) .length ; //Exception } } class Container < T > { T [ ] array ; @ SuppressWarnings ( `` unchec...
How is the Java erasure affecting the generic arrays ?
Java
Ran into an interesting issue ; the following class compiles : but this one fails : with this error : I 'd have thought that due to type erasure that these would be essentially identical . Any one know what 's going on here ?
public class Test { public static void main ( String [ ] args ) throws Exception { A a = new A ( ) ; B b = new B ( ) ; foo ( a ) ; foo ( b ) ; } private static void foo ( A a ) { System.out.println ( `` In A '' ) ; } private static void foo ( B b ) { System.out.println ( `` In B '' ) ; } private static class A { } priv...
Generics in overridden methods
Java
Imagine you have a list of people , Roberts , Pauls , Richards , etc , these are people grouped by name into Map < String , List < Person > > . You want to find the oldest Paul , Robert , etc ... You can do it like so : Say , I want to get a mapping in the form of Map < String , Integer > instead of Map < String , Pers...
public static void main ( String ... args ) { List < Person > people = Arrays.asList ( new Person ( 23 , `` Paul '' ) , new Person ( 24 , `` Robert '' ) , new Person ( 32 , `` Paul '' ) , new Person ( 10 , `` Robert '' ) , new Person ( 4 , `` Richard '' ) , new Person ( 60 , `` Richard '' ) , new Person ( 9 , `` Robert...
How do you convert Map < String , Person > to Map < String , Integer > in java streams inside collect ?
Java
Scenario : I 'm receiving a huge xml file via extreme slow network so I want so start the excessive processing as early as possible . Because of that I decided to use SAXParser.I expected that after a tag is finished I will get an event.The following test shows what I mean : I wrapped the input stream to see what is re...
@ Testpublic void sax_parser_read_much_things_before_returning_events ( ) throws Exception { String xml = `` < a > '' + `` < b > .. < /b > '' + `` < c > .. < /c > '' // much more ... + `` < /a > '' ; // wrapper to show what is read InputStream is = new InputStream ( ) { InputStream is = new ByteArrayInputStream ( xml.g...
Why does SAXParser read so much before throwing events ?
Java
I have interface : and class that implement this : everything works fine . so far . Now I want to create GenericDAO , why I can not create this ? : I can only declare my GenericDAO as this : And complete class : But i think it 's useless , because I repeat information . I already declared , that Cat implements Identifa...
interface Identifable < T extends Serializable > { T getID ( ) ; } public class Cat implements Identifable < Long > { public Long getID ( ) { ... } ; } public abstract GenericDAO < T extends Identifable < S > > { T getByID ( S id ) ; } public abstract GenericDAO < T extends Identifable , S > { T getById ( S id ) ; } pu...
Java Generic of Another generic
Java
I was exploring the Streamable Interface and the first method that I came across was the empty ( ) method that has the following definition.Collections : :emptyIterator returns the Iterator < T > but the return type of this method is Streamable < T > . Streamble extends Iterable and Supplier and not Iterator interface....
@ FunctionalInterfacepublic interface Streamable < T > extends Iterable < T > , Supplier < Stream < T > > static < T > Streamable < T > empty ( ) { return Collections : :emptyIterator ; }
Streamable Interface : How empty ( ) method returns Iterable ?
Java
The following program : prints the incremented value of counter every time I access the url of this servlet . I read that the server creates an instance of this servlet and whenever there is a request for this servlet a new thread maps this request to the special instance created by the server . When does the instance ...
public class SimpleCounter extends HttpServlet { int counter=0 ; @ Override protected void doGet ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { response.setContentType ( `` text/plain '' ) ; PrintWriter writer = response.getWriter ( ) ; counter++ ; writer.println (...
When does the instance created by the server die ?
Java
I am solving a problem in java in which i have to find the maximum pair-wise product of the 2 integer arrays.Example : My currrent code also produces this output.My Solutionsort both arrays and then multiply numbers at same indexes from both arrays and sum the product of each pair . ProblemMy solution is tested using t...
array 1 - > [ 1 , 3 , -5 ] array 2 - > [ -2 , 4 , 1 ] output : 23 // ( 3 * 4 ) + ( 1 * 1 ) + ( -5 * -2 ) private static long maxSum ( int [ ] a , int [ ] b ) { long result = 0 ; Arrays.sort ( a ) ; Arrays.sort ( b ) ; for ( int i = a.length - 1 ; i > = 0 ; i -- ) { result += a [ i ] * b [ i ] ; } return result ; }
finding the max sum of pair-wise products
Java
I 'm trying to serialize some objects of custom classes and I got the following exception : I have an ArrayList : The storage is serializable and all contents in it are as well.But I still got this error and I do n't know why.There is only one key and value in the property map.The key is a string and the value is a lon...
com.esotericsoftware.kryo.KryoException : com.sleepycat.je.EnvironmentFailureException : ( JE 5.0.73 ) IdentityHashMap.entrySet ( ) should not be used . See [ # 18167 ] . UNEXPECTED_STATE : Unexpected internal state , may have side effects.Serialization trace : highestFlushLevels ( com.sleepycat.je.recovery.DirtyINMap ...
Kryo crash EnvironmentFailureException
Java
I have this : It gives : Question : I understand why I am getting this exception . It is because the ArrayList class from inside Arrays.java is being used which does not have a remove ( ) method . My question is how can someone ( any user , like me ) know before using that the List they received that it does not contai...
import java.util.Arrays ; import java.util.List ; import java.util.ArrayList ; public class ListTest { public static void main ( String [ ] args ) { String [ ] values = { `` yes '' , `` no '' } ; List < String > aa = Arrays.asList ( values ) ; System.out.println ( aa.getClass ( ) .getName ( ) ) ; aa.remove ( 0 ) ; } } ...
How to know if List.remove ( ) is `` Unsupported '' ?
Java
Edited : My purpose is to check whether someTime is in the same day or in the previous day without doing too much heavyweight stuff . Does this account for day light savings and why ? If not , what 's the simplest logic ?
// someTime is epoch in millis ( UTC ) final long timeNow = new Date ( ) .getTime ( ) ; final long midnight = timeNow - timeNow % ( 3600 * 24 * 1000L ) ; final long yesterdayMidnight = midnight - ( 3600 * 24 * 1000L ) ; // check if same day.if ( someTime > = midnight ) // do something// check if yesterdayif ( someTime ...
Does this account for daylight savings ?
Java
I recently argued with a friend on a code like this : I argued that it 's possible that value can be seen as 0 in Y , because there 's no guarantee that the assignment value = initializeValue ( ) is visible in the executor 's threads . I said he would need to make value a volatile field . He contradicted me , and said ...
import java.util.concurrent.ExecutorService ; import java.util.concurrent.Executors ; /** * See memory consistency effects in a Java Executor . */public class PrivateFieldInEnclosing { private long value ; PrivateFieldInEnclosing ( ) { } void execute ( ) { value = initializeValue ( ) ; ExecutorService executor = Execut...
Visibility of assignment to variable in Java
Java
I 'm not quite sure I understand g.drawString . I have a program that writes to a preprinted form . The users claim that the printing is irregular ... ie , text on the form is higher/lower than the previous print . Personally , I think they 're misloading the form , but since they pay me to write code , I 'm measuring ...
public int print ( Graphics g , PageFormat pf , int page , Check c ) { final double MILLIMETER_IN_PIXELS = 3.779527559 ; DecimalFormat df = new DecimalFormat ( `` $ # .00 '' ) ; if ( page > 0 ) { return NO_SUCH_PAGE ; } Graphics2D g2d = ( Graphics2D ) g ; int x = ( int ) pf.getImageableX ( ) ; int y = ( int ) pf.getIma...
Printing to a physical form -- need basic understanding
Java
I 'm trying to make a UI tool to start/stop a webapp ( war ) on a Jboss EAP 5.1 via JMX , but I have a issue with securityArgs : localhost:1099 , jboss.web.deployment : war=/QueueManager , start , admin , adminand that 's the exception : Can you help me toubleshooting this issue ?
public class jmx_console { // private static final Logger log = Logger.getLogger ( jmx_console.class ) ; // public static String startAndStopQueueManager ( String jnpUrl , String qmUrl , String action , String username , String password ) throws NamingException , MalformedObjectNameException , InstanceNotFoundException...
start /stop war via JMX w/ JBoss EAP 5.1
Java
I followed this answer https : //stackoverflow.com/a/19418847/1665592 but it does n't help me to compile single java files using Gradle . It says Task : compileMessageKeys NO-SOURCE Why ? I just have only one Java File CreateMessageKeysTask.java which is dependent on `` apache-ant-1.7.0/ant.jar '' jarMy ant script is a...
task compileMessageKeys ( type : JavaCompile ) { doFirst { println `` $ projectDir/precompile '' new File ( `` $ projectDir/precompile '' ) .mkdirs ( ) } source = sourceSets.main.java.srcDirs include 'mypackage.build.CreateMessageKeysTask.java ' classpath = sourceSets.main.compileClasspath destinationDir = sourceSets.m...
Gradle Compile & Execute the Single Java Class with third-party jar dependencies using Gradle ` buildscript `
Java
In Android I subclassed ParseObject with two local variables that are not in Parse class . I just needed to set those variables locally and had no need to save them on server . They are String 's named helper1 and helper2 with getters and setters as well.It works all fine on Android - I can use setHelper1 ( `` whatever...
q1.find ( { success : function ( results ) { for ( var x in results ) { x.helper1 = 'foo ' ; } response.success ( results ) ; } , error : function ( error ) { } } ) ;
JavaScript subclassing in Parse.com
Java
I have some complex Observable structures , which may or may not be bad ideas , but which are not the focus of this question.The problem with those structures is that they generate a lot of invalidations of Observable objects being displayed by the UI . As near as I can tell , when the JavaFX UI is displaying something...
package com.myapp.SAM.model.datastructures ; import java.util.concurrent.atomic.AtomicBoolean ; import java.util.logging.Logger ; import javafx.application.Platform ; import javafx.beans.InvalidationListener ; import javafx.beans.binding.Binding ; import javafx.beans.value.ChangeListener ; import javafx.collections.Obs...
Is this a valid way to minimize binding invalidations ?
Java
This is the method i am going to call/invoke.This is the method where i am testing invoking the previous method ( Both are located in the same class named MyClass ) Why does this particular case ( second invoke test ) < Integer , String > doGenericStatic2 ( 100 , `` Text '' ) ; generate a compile time error ?
public static < N , E > void doGenericStatic2 ( N number , E element ) { System.out.println ( number ) ; System.out.println ( element ) ; } public static void testInvokeGenericMethodLocally ( ) { doGenericStatic2 ( 100 , `` Text '' ) ; // < Integer , String > doGenericStatic2 ( 100 , `` Text '' ) ; //Syntax error , ins...
Calling generic static method locally while omitting class name
Java
I am trying to use PageDown on the client side as an editor , and on the server side to then parse that Markdown to HTML.It seems to work fine on the client side , but on the server side , tickmarks are only `` codifying '' the character that follows , not the word that it wraps . So if I do this : test ` test ` testI ...
function getSanitizedHtml ( pagedown ) { var converter = new Markdown.getSanitizingConverter ( ) ; return converter.makeHtml ( pagedown ) ; } < ! DOCTYPE html > < html > < head > < script src= '' pageDown.js '' > < /script > < script > function convert ( ) { var html = getSanitizedHtml ( `` test ` test ` test '' ) ; co...
PageDown through ScriptEngine incorrectly parsing Markdown
Java
This piece of codewill print because the inner append is executed first and modifies the object b1 ; then the outer b1 is evaluated ( it is equal to hello ! now ) and the same string is appended to it . Soinner expression is executedoriginal object gets modifiedouter expression is executed on modified objectBut now , w...
StringBuilder b1=new StringBuilder ( `` hello '' ) ; b1.append ( b1.append ( `` ! `` ) ) ; System.out.println ( `` b1 = `` +b1 ) ; b1 = hello ! hello ! StringBuilder s1=null ; StringBuilder s2=new StringBuilder ( `` world '' ) ; try { s1.append ( s1=s2.append ( `` ! `` ) ) ; } catch ( Exception e ) { System.out.println...
Clarification on StringBuilder reference and methods execution order
Java
I 've got a java.util.stream.Stream containing key value pairs like : Now I would like to merge all entries , which have got the same key : The data is already sorted , so only consecutive datasets have to be merged.Now I 'm searching for a way to transform the the content of the stream like above , without loading all...
< 1,3 > < 1,5 > < 3,1 > < 4,2 > < 4,7 > < 4,8 > < 1 , [ 3,5 ] > < 3 , [ 1 ] > < 4 , [ 2,7,8 ] >
Java 8 : Executing reduce operation on Stream
Java
What is the effect of not catching the value of the method that returns a value ? Does it develop complications like memory issues if the return value was not caught.Example code snippets :
//reference typespublic Object [ ] thismethodreturnsvalue ( ) { return new Object [ ] { new Object ( ) , new Object ( ) , new Object ( ) } ; } //primitive typespublic int thismethodreturnsint ( ) { return -1 ; } public static void main ( String a [ ] ) { thismethodreturnsvalue ( ) ; thismethodreturnsint ( ) ; }
Java return Issue
Java
I have a function that filtering list of some values and it use instanseof construction : I want to make it more general and set Button as function parameter : But i do n't know how to pass myClass to the function.Please , tell me how i can generalize this function ?
public static List < View > getAllChildren ( View v ) { /* ... */ if ( v instanceof Button ) { resultList.add ( v ) ; } /* ... */ } public static List < View > getAllChildren ( View v , ? myClass ) { /* ... */ if ( v instanceof myClass ) { resultList.add ( v ) ; } /* ... */ }
Class as function argument
Java
I was practicing my Java 8 skills . I came across a strange ( for me ) code . I have my bean class Person with overridden equals method . Then I tried to implement BiPredicate with equals method . It ran successfully . Can anyone explains how 's that possible..because in my opinion equals method takes 1 argument and Bi...
package method_referencing ; import java.util.function.BiPredicate ; import method_referencing.Person ; //1 . static ... .//2 . instance ... //3 . arbitary object //4 . constructorpublic class Method_Ref1 { public static void main ( String [ ] args ) { System.out.println ( checkHere ( Person : :equals ) ) ; } static bo...
confusion in java 8 method referencing for equals method implementation with BiPredicate
Java
Let 's say that I have 2 microservices : Service1 and Service2 . Each one of them has its own database . Service1 has EntityA and Service2 has EntityB I 'm using Spring 's RestTemplate for retrieving and saving data . The problem is : when retrieving EntityA from Service1 's database I do n't have data of EntityB as th...
EntityA { Long id ; //other fields EntityB entity ; } EntityB { //other fields }
Invoking dependent microservice
Java
I have a utility method ( used for unit testing , it so happens ) that executes a Runnable in another thread . It starts the thread running , but does not wait for the Thread to finish , instead relying on a Future . A caller of the method is expected to get ( ) that Future . But is that enough to ensure safe publicati...
private static Future < Void > runInOtherThread ( final CountDownLatch ready , final Runnable operation ) { final CompletableFuture < Void > future = new CompletableFuture < Void > ( ) ; final Thread thread = new Thread ( ( ) - > { try { ready.await ( ) ; operation.run ( ) ; } catch ( Throwable e ) { future.completeExc...
Must you join on a Thread to ensure its computation is complete
Java
I 'm writing a shared library to be loaded into the JVM and the behavior below got me stuck . Here are my Java classes : And the library to be loaded looks like : test_jni.htest_jni.cfs.hfs.cWhen compiling and running this Main class the JVM does not crash . It simply does not enter the function fs.h : :close ( int ) ....
package com.test ; public class UnixUtil { static { System.loadLibrary ( `` myfancylibrary '' ) ; } static native int openReadOnlyFd ( String path ) ; static native int closeFd ( int fd ) ; } public class Main { public static void main ( String [ ] args ) { int fd = UnixUtil.openReadOnlyFd ( `` /tmp/testc '' ) ; UnixUt...
Why does n't the JVM crash when entering infinite recursion ?
Java
I have a RecyclerView and an adapter which has an ArrayList of Person model.When the app starts I type the names in the EditText and press the button:1 ) 2 ) 3 ) 4 ) But when I log personList data in the activity , the result is : First item is removed and last item is repeated in the first one . ( My adapter is more c...
personList : Item 0 -- -- - > AlirezapersonList : Item 1 -- -- - > TohidpersonList : Item 2 -- -- - > Alireza < ? 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= '' wra...
RecyclerView set the last ArrayList item data to the first item
Java
Since Java 11 , a PREVIEW-MODE on the Java Compiler and Runtime can be enabled . It allows to preview new features . ( JEP 12 ) How can I detect from within Java whether the JVM has been started with preview-mode enabled ? The intention is to describe the running container on an in-application status page/json - for de...
java -- enable-preview
Programmatically detect -- preview Mode in JRE
Java
I am trying to learn Java Generics , and found the following code.Which works with no problem.However when I change print method to the following , it gives me compiling errors.Error : Can anyone help me understand the errors ?
public static < T > void print ( T a , T b ) { System.out.println ( a ) ; System.out.println ( b ) ; } public static void main ( String [ ] args ) { print ( new ArrayList < String > ( ) , 1 ) ; } public static < T > void print ( List < T > a , T b ) { System.out.println ( a ) ; System.out.println ( b ) ; } GenericTest....
Errors occur when calling print ( List < T > a , T b ) with different T class
Java
Arrays are Objects and all the objects come from a class . If I execute the following code : The output is class java.lang.String.But if I execute the following : The output is class [ I.My questions are : What is the class of the arrays ? Why is it the result ? If I would like to use the instanceof operator how should...
public class Test { public static void main ( String [ ] args ) { String str = `` Hello '' ; System.out.println ( str.getClass ( ) ) ; } } public class Test { public static void main ( String [ ] args ) { int arr [ ] = new int [ 10 ] ; System.out.println ( arr.getClass ( ) ) ; } }
What is the class of the Arrays in Java
Java
Sometimes , I came across some class design as follow.I was wondering , what is the purpose of having an abstract_dog class ? Why we `` transform '' the non-abstract speak method into abstract speak again ?
abstract class animal { public abstract void speak ( ) ; } class dog extends animal { @ Override public void speak ( ) { // Do something . } } abstract class abstract_dog extends dog { @ Override public abstract void speak ( ) ; }
Purpose of having abstract child by extending concrete parent
Java
I want to extract the second matcher in a regex pattern between - and _ in this string : I tried this : But I get 123456-124 for the above regex in Java.I need only 124.How can I achieve this ?
VA-123456-124_VRG.tif Pattern mpattern = Pattern.compile ( `` - . * ? _ '' ) ;
How can I get the second matcher in regex in Java ?
Java
When I try to close Ad by clicking the close button in the interstitial ad , that particular ad is closed . But then another one ad is loaded . And the application continues in this way forever . How to avoid another ad to load after manually closing it ? This is my code : and displayInterstitial ( ) method is
static View setupListView ( final Activity activity , View convertView , final ViewGroup parent , MediaBrowserCompat.MediaItem item ) { if ( sColorStateNotPlaying == null || sColorStatePlaying == null ) initializeColorStateLists ( activity ) ; MediaDescriptionCompat description = item.getDescription ( ) ; final MediaIt...
How to avoid interstitial ad to reload after closing it
Java
I have List of TrainingRequest where each and every element has List of Feedback.I need to get all given result of Q1 , Q2 and calculate percentage of each value . To flat all the feedbackTo calculate each value of Q1 and Q2 , I 'm grouping it and getting the count . I need to get the percentage of each Q1 , Q2 value i...
@ Dataclass TrainingRequest { @ Transient List < Feedack > feedback ; } @ Dataclass Feedback { String Q1 ; String Q2 ; } List < TrainingRequest > trainingList = Optional.ofNullable ( trainingRequestList ) .orElseGet ( Collections : :emptyList ) .stream ( ) .map ( m - > { List < Feedback > feedback = findByTrainingReque...
Calculate the percentage of value using Collection framework
Java
This is regarding the difference in the result returned by '+ ' operator . Result varies for String literal and String Object.With the result we can deduce that with literal , already available object from the string pool is returned as in case of line 3 and with string object new object is returned , as in line 5 . Wh...
String str= '' ab '' ; String str1= '' c '' ; String str2 = `` ab '' + '' c '' ; // Line 3String str3 = `` abc '' ; String str4 = str+str1 ; // Line 5System.out.println ( str2==str3 ) ; // TrueSystem.out.println ( str2==str4 ) ; // False
+ Operator in String Class
Java
I found that if I use an annotation , the program will not throw a ClassNotFoundException.Tomcat starts successefully without the javaee-api-7.0.jar which contains the class javax.transaction.TransactionalIt makes me very confused , should n't the JVM throw aClassNotFoundException when it loads the class A ?
class A { @ Transactional public void insert ( ) { //insert something } }
When does the JVM load the annotation class
Java
i use apache-mime4j-0.6.jar and httpmime-4.0.1.jar , in my Logcat Everything is Good except this Log out_write ( ) limiting sleep time 31178 to 23219 with tag audio_hw_primary but I 'm not sure it 's From my App.Problem : in my php File , I can Receive Everything except My posted file ! this is my Code , base on this Q...
package com.negano.Uploader ; import java.io.BufferedReader ; import java.io.File ; import java.io.InputStream ; import java.io.InputStreamReader ; import org.apache.http.HttpResponse ; import org.apache.http.HttpVersion ; import org.apache.http.client.methods.HttpPost ; import org.apache.http.entity.mime.HttpMultipart...
Android app post everyThing except posted file
Java
I have I want to print I am trying Than want to print arrayBut my gg is always 0.am I missing anything.All I need is to remove the number and . and white spacesThe number can be 1 ( or ) 5 digit number
1 . This is a test message This is a test message String delimiter= '' . `` ; String [ ] parts = line.split ( delimiter ) ; int gg=parts.length ; for ( int k ; k < gg ; K++ ) parts [ k ] ;
Splitting a Java String with ' . '