lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | In class B , how can I create an object of class A other than the process of object creation ( i.e . without creating an object having null ) ? | class A { public int one ; A ( A a ) { a.one=1 ; } } class B { public static void main ( String ... args ) { //now how to create an object of class A over here . } } | How can I create an object of this class ? |
Java | My question is pretty simple , I would like to launch a .exe in its own directory but with elevation rights/privileges.I know that this question as been raised before but I did n't found the right way for fixing my problem.Indeed , I first tried this : I got the following error : Then I tried this : And it runs but not... | String workingDir = `` C : \\TEST\\ '' ; String cmd = workingDir + `` game.exe '' ; Runtime.getRuntime ( ) .exec ( cmd , null , new File ( workingDir ) ) ; CreateProcess error=740 , The requested operation requires elevation ProcessBuilder builder = new ProcessBuilder ( new String [ ] { `` cmd.exe '' , `` /C '' , '' C ... | Launching .exe in its own directory with elevation priviledges |
Java | How can I make the controllerAdvice class catch the exception that is thrown from completablefutrue . In the code below I have a method checkId that throws a checked exception . I call this method using completablefuture and wrap the checked exception inside CompletionException . Although I have a handler method in con... | package com.example.demo.controller ; @ RestControllerpublic class HomeController { @ GetMapping ( path = `` /check '' ) public CompletableFuture < String > check ( @ RequestParam ( `` id '' ) int id ) { return CompletableFuture.supplyAsync ( ( ) - > { try { return checkId ( id ) ; } catch ( Exception e ) { throw new C... | How to pass checked exception from CompletableFuture to ControllerAdvice |
Java | I want to count the number of occurances for a particular phrase in a document . For example `` stackoverflow forums '' . Suppose D represents the documents set with document containing both terms.Now , suppose I have the following data structure : where numMatchedDocuments is the size of D and numOccurInADocument is t... | A [ numTerms ] [ numMatchedDocuments ] [ numOccurInADocument ] A [ stackoverflow ] [ document1 ] [ occurance1 ] =3 ; boolean docPhrase=true ; int numOfTerms=2 ; // 0 for `` stackoverflow '' and 1 for `` forums '' for ( int d=0 ; d < D.size ( ) ; d++ ) { //D is a set containing the matched documents int minId=getTheLeas... | Fast and efficient computation on arrays |
Java | Is it bad practice to use the instanceof operator in the following context ? There is a lot of myths about the use of that operator and I am not completelysure that what I am doing is not bunk.I have a lot of different writer implementationswhich I want to combine in one interface . The problem is not every DTO is appl... | public interface IWriter { public abstract void write ( Dto dto ) ; } public abstract class Dto { private long id ; public void setId ( long id ) { this.id = id ; } public long getId ( ) { return id ; } } public class DtoA extends Dto { ... } public class DtoB extends Dto { ... } public class MyWriterA implements IWrit... | Is it okay to use the instanceof operator to implement two parallel hierarchies of functions and arguments to those ? |
Java | build.xmlAntTask.javaExecutionQuestionI search the applicable naming rules for elements and attributes and the mapping rules to Java language . | < taskdef onerror = '' ignore '' name = '' monitor-client '' classpath= '' $ { jar-client } '' classname= '' hpms.app.mon.client.AntTask '' / > < target name= '' run-client '' depends= '' compile-sample '' description= '' Launch monitor '' > < monitor-client layout = '' Layout.xml '' gui = '' true '' autostart = '' tru... | How can I define a task named with a hyphen ? |
Java | The following Java code does not invoke the static initializer of class B . Why ? Code : Program output : Tested on JDK 1.8.0_25 | class A { static { System.out.println ( `` A static init '' ) ; } public static void f ( ) { System.out.println ( `` f ( ) called '' ) ; } } class B extends A { static { System.out.println ( `` B static init '' ) ; } } public class App { public static void main ( String [ ] args ) { B.f ( ) ; //invokestatic # 16 // Met... | Static initializer not invoked for a derived class |
Java | I 'm trying to convert this : Which compiles just fine , to the more modern Java 8 streams version : Which produces an error message : I can see why the compiler would have trouble with this -- - not enough type information to figure out the inference . What I ca n't see is how to fix it . Does anyone know ? | static Set < String > methodSet ( Class < ? > type ) { Set < String > result = new TreeSet < > ( ) ; for ( Method m : type.getMethods ( ) ) result.add ( m.getName ( ) ) ; return result ; } static Set < String > methodSet2 ( Class < ? > type ) { return Arrays.stream ( type.getMethods ( ) ) .collect ( Collectors.toCollec... | Java 8 generics and type inference issue |
Java | Here 's the code I 'm using : Compiles perfectly , but nothing happens at runtime . What am I doing wrong ? | public class splitText { public static void main ( String [ ] args ) { String x = `` I lost my Phone . I should n't drive home alone '' ; String [ ] result = x.split ( `` . `` ) ; for ( String i : result ) { System.out.println ( i ) ; } } } | Having trouble with Splitting text |
Java | I was trying some basic Java I/O operations , I try to run the below code : When I run the above I get the following output in the file created : Can anyone explain why the ' f ' is coming in the last line ? | public static void main ( String [ ] args ) { File file = new File ( `` fileWrite2.txt '' ) ; // create a File object try { FileWriter fr = new FileWriter ( file ) ; PrintWriter pw = new PrintWriter ( file ) ; // create a PrintWriter that will send its output to a Writer BufferedWriter br = new BufferedWriter ( fr ) ; ... | Strange behavior in writing to file |
Java | UPDATEWhen new Fish is called , is there a new instance of Fish floating around somewhere without a reference or have I just allocated memory for a new Fish without actually instantiating it ? Can I get the new Fish call to create an actual instance of the Fish with a unique reference name other than iterating through ... | public Fish mate ( Fish other ) { if ( this.health > 0 & & other.health > 0 & & this.closeEnough ( other ) ) { int babySize = ( ( ( this.size + other.size ) /2 ) ) ; int babyHealth = ( ( ( this.health + other.health ) /2 ) ) ; double babyX = ( ( ( this.x + other.x ) /2.0 ) ) ; double babyY = ( ( ( this.y + other.y ) /2... | New instance of class created or just space in memory allocated ? |
Java | Consider the UnaryFunction interface defined in Effective Java generics chapter .and the following code for returning the UnaryFunctionWhy is the cast of IDENTITY_FUNCTION to ( UnaryFunction < T > ) safe ? The book says this about the question I am asking but I ca n't follow the logic here . Where are we invoking the a... | public interface UnaryFunction < T > { T apply ( T arg ) ; } // Generic singleton factory patternprivate static UnaryFunction < Object > IDENTITY_FUNCTION = new UnaryFunction < Object > ( ) { public Object apply ( Object arg ) { return arg ; } } ; // IDENTITY_FUNCTION is stateless and its type parameter is// unbounded ... | Why is it safe to suppress this unchecked warning ? |
Java | I a beginner when it comes to development for Android and I am trying to understand JavaCPP . I want to execute a C++ function from Java inside an Android application . In my example I just use a simple TextView widget that prints what I receive from C++.Following the documentation , inside the app 's build.gradle I ha... | dependencies { implementation 'org.bytedeco : javacpp:1.5.4 ' } package com.example.javacplusplus ; import org.bytedeco.javacpp . * ; import org.bytedeco.javacpp.annotation . * ; @ Platform ( include= '' NativeLibrary.h '' ) @ Namespace ( `` NativeLibrary '' ) public class NativeLibrary { public static class NativeClas... | Run C++ code in Java Android app using JavaCPP |
Java | Consider this method : As you can see , I have to count how many times each number between min and max can be expressed as a sum of two primes.primes is an ArrayList with all primes between 2 and 2000000 . In this case , min is 1000000 and max is 2000000 , that 's why primes goes until 2000000.My method works fine , bu... | public static int [ ] countPairs ( int min , int max ) { int lastIndex = primes.size ( ) - 1 ; int i = 0 ; int howManyPairs [ ] = new int [ ( max-min ) +1 ] ; for ( int outer : primes ) { for ( int inner : primes.subList ( i , lastIndex ) ) { int sum = outer + inner ; if ( sum > max ) break ; if ( sum > = min & & sum <... | Find how many times each number between N and M can be expressed as a sum of a pair of primes |
Java | I have a simple modular javafx application.i compile it usingThis creates mods directoryI then create runtime image using the commandThis creates the runtime image in hellofx directory Now i use the jpackage command to create the windows installer . In the directory i have an icon for the application.This icon was used... | dir /s /b src\*.java > sources.txt & javac -- module-path % PATH_TO_FX % -d mods/hellofx @ sources.txt & del sources.txt jlink -- module-path `` % PATH_TO_FX_MODS % ; mods '' -- add-modules hellofx -- output hellofx jpackage -- runtime-image hellofx -- module hellofx/hellofx.HelloFX -- win-shortcut -- win-menu -- icon ... | is there a way to change icon of the installer file using jpackage ? |
Java | The Java memory model guarantees a happens-before relationship between an object 's construction and finalizer : There is a happens-before edge from the end of a constructor of an object to the start of a finalizer ( §12.6 ) for that object.As well as the constructor and the initialization of final fields : An object i... | public class Foo { public int bar = 0 ; public Foo ( ) { this.bar = 5 ; } ... } Thread t = new Thread ( ( ) - > { if ( myFoo.bar == 5 ) { ... . } } ) ; t.start ( ) ; Foo myFoo = null ; Thread t2 = new Thread ( ( ) - > { for ( ; ; ) { if ( myFoo ! = null & & myFoo.bar == 5 ) { ... } ... } } ) ; t2.start ( ) ; myFoo = ne... | Does object construction guarantee in practice that all threads see non-final fields initialized ? |
Java | I 'm trying to convert this Scala expression to Java : This is what I have in Java : But I get an error on a._2 : .If I go to the `` super '' method , this is what I see : | val corpus : RDD [ String ] = sc.wholeTextFiles ( `` docs/*.md '' ) .map ( _._2 ) RDD < String > corpus = sc.wholeTextFiles ( `` docs/*.md '' ) .map ( a - > a._2 ) ; package org.apache.spark.api.java.function ; import java.io.Serializable ; public interface Function < T1 , R > extends Serializable { R call ( T1 var1 ) ... | Convert Scala expression to Java 1.8 |
Java | I was reading an article on Java Generics when I stumbled on this method signature : The part that I do n't get is why we need to have wouldn'tdo as well ? Could someone please explain why the following signature is not adequate ? Thanks in advance for your replies . This keeps puzzling me for quite some time now.. | static < T extends Object & Comparable < ? super T > > T max ( Collection < ? extends T > coll ) ; Collection < ? extends T > coll Collection < T > coll static < T extends Object & Comparable < ? super T > > T max ( Collection < T > coll ) ; | Explanation of the Collections.max signature |
Java | I was wondering if it is possible to get the return type of a Supplier that was assigned to a constructor.E.g.How do I get `` Foo.class '' from the supplier ? I have been using typetools to solve this problem for other things.This works , for example : But if I assign Supplier like : Supplier < Foo > sFoo = Foo : :new ... | Supplier < Foo > sFoo = Foo : :new ; Supplier < Foo > sFoo = ( ) - > new Foo ( ) ; Class < ? > fooClasss = net.jodah.typetools.TypeResolver.resolveRawArguments ( Supplier.class , sFoo.getClass ( ) ) [ 0 ] ; // fooClass == Foo.class | How to get return type of constructor lambda |
Java | I 'm using the Spark Java Web Framework with Apache 's Velocity Template Engine in order to help design a responsive web application that pulls data from a SQL database . Using SQL2o I 've created some Java objects of custom class types , i.e . user , group , site , etc.I 've checked and the list of objects created is ... | public static void main ( String [ ] args ) { WEB_LOGMGR loggr = new WEB_LOGMGR ( true ) ; WEB_DBMGR dbmgr = new WEB_DBMGR ( true , loggr ) ; Model backend = new ScadaModel ( dbmgr , loggr ) ; System.out.println ( dataToJson ( backend.getUsers ( ) ) ) ; staticFiles.location ( `` / '' ) ; staticFiles.externalLocation ( ... | Java Spark/Velocity Templates/SQL2o |
Java | I have a static method declared in Java : I would love to use this method as extension method for instances of type Y in Kotlin : Is that possible ? I have control over all source code in question , e.g . to add annotations . | class X { public static void foo ( Y y ) { … } } import X.foo…y.foo ( ) | Use Static Method in Java as Extension Method in Kotlin |
Java | I 'm using Scene Builder ( v11.0.0 ) to create FXML files for scenes in JavaFX ( v12 ) but , despite instructing all containers to USE_COMPUTED_SIZE for the preferred widths and heights , the rendered scenes ( as seen in Scene Builder and also when run as a JavaFX application which loads those FXML files ) are being cl... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < ? import javafx.scene.control.Button ? > < ? import javafx.scene.control.TitledPane ? > < ? import javafx.scene.layout.HBox ? > < ? import javafx.scene.layout.VBox ? > < VBox maxHeight= '' -Infinity '' maxWidth= '' -Infinity '' minHeight= '' -Infinity '' minWidth= ... | JavaFX and Scene Builder clip scene edges despite specifying USE_COMPUTED_SIZE |
Java | My Android client get server JSON response as follows : My Android client code parses the JSON response to Java object by using gson.My corresponding Java classes : Everything works fine for me at this point , I can successfully parse JSON data to my Java objects , like following : Then , I would like to modify a bit t... | { `` students '' : [ { `` id '' :1 , '' name '' : '' John '' , '' age '' :12 } , { `` id '' :2 , '' name '' : '' Thmas '' , '' age '' :13 } { `` id '' :3 , '' name '' : '' Merit '' , '' age '' :10 } ... ] } public class StudentList { private List < Student > students ; public List < Student > getStudents ( ) { return s... | Sort my ojects which are parsed from json data |
Java | I was curious to see how Java and Scala implement switches on strings : It seems like Java switches on the hashcode and then does a single string comparison : In contrast , Scala seems to compare against all the cases : Is it possible to convince Scala to employ the hashcode trick ? I would rather prefer an O ( 1 ) sol... | class Java { public static int java ( String s ) { switch ( s ) { case `` foo '' : return 1 ; case `` bar '' : return 2 ; case `` baz '' : return 3 ; default : return 42 ; } } } object Scala { def scala ( s : String ) : Int = { s match { case `` foo '' = > 1 case `` bar '' = > 2 case `` baz '' = > 3 case _ = > 42 } } }... | Switching on Strings |
Java | A static field can not be referenced before it is defined or initialized : However , when it is referenced from an instance initialization block ( in an anonymous inner class ) , not even a warning is generated.See example : The result is : j == null , k == 5 , so clearly we 've made a reference , order matters , and n... | static Integer j = i ; /* compile error */static final Integer i = 5 ; class StaticInitialization { static final Object o = new Object ( ) { { j = i ; } } ; static Integer j , k ; static final Integer i = 5 ; static final Object o2 = new Object ( ) { { k = i ; } } ; } | Java : Why no warning when referencing a field before it is defined ? |
Java | I 'm making a tank game and to avoid redundancy I 'm making classes to extend.My MenuPanel looks like this atm ( I 've only written the code that matters for the question ) ( knop = dutch for button ) because the code to make the buttons is exactly the same ( except for the backgroundPath and the y-coordinate ) I made ... | public class MenuPanel extends JPanel implements ActionListener { private JButton playKnop , highScoreKnop , quitKnop , HTPKnop ; private ImageIcon play , HS , quit , HTP ; private Tanks mainVenster ; public MenuPanel ( Tanks mainVenster ) { this.mainVenster = mainVenster ; this.setLayout ( null ) ; int x = 95 ; int wi... | How to use code from one class in another ? ( Java ) |
Java | I started learning java and I am now at the concurrency chapter . After reading some stuff about concurrency I tried an example of my own.The problem is that i was expecting to see the following output : but after I get this , the program continues printing until I close it.So , my question is what am I doing wrong ? w... | public class Task implements Runnable { public void run ( ) { while ( ! Thread.interrupted ( ) ) { try { System.out.println ( `` task '' ) ; TimeUnit.SECONDS.sleep ( 2 ) ; } catch ( InterruptedException e ) { System.out.println ( `` interrupted '' ) ; } } } } public static void main ( String [ ] args ) throws Exception... | Program continues to run despite InterruptedException |
Java | In this code sample from page 114 of The Well-Grounded Java Developer , the last line : contains the note : Pass zero-sized array , save allocationWhat allocation is this saving , exactly ? The javadoc for List # toArray ( T [ ] a ) mentions : If the list fits in the specified array , it is returned therein . Otherwise... | Update [ ] updates = lu.toArray ( new Update [ 0 ] ) ; List < Update > lu = new ArrayList < Update > ( ) ; String text = `` '' ; final Update.Builder ub = new Update.Builder ( ) ; final Author a = new Author ( `` Tallulah '' ) ; for ( int i=0 ; i < 256 ; i++ ) { text = text + `` X '' ; long now = System.currentTimeMill... | Pass zero-sized array , save allocation ? |
Java | My code currently returns the length of the largest substring : assuming seq is the numbers in the sequence . So if the sequence is : 5 ; 3 ; 4 ; 8 ; 6 ; 7 , it prints out 4 . However , I would like it to also print out 3 ; 4 ; 6 ; 7 which is the longest subsisting in ascending order.I am trying to get the length of th... | for ( int i = 1 ; i < =l-1 ; i++ ) { counter = 1 ; for ( int j = 0 ; j < i ; j++ ) { if ( seq [ j ] < seq [ j+1 ] ) { count [ j ] = counter++ ; } } } for ( int i = 0 ; i < l-1 ; i++ ) { if ( largest < count [ i+1 ] ) { largest = count [ i+1 ] ; } } | Looking for a hint ( not the answer ) on how to return the longest acsending non contiguous substring when I already have the length |
Java | I have an application that starts a few threads , eventually a thread may need to exit the entire application , however other threads may be in the middle of a task so I 'd like to let them continue their current loop before exiting.In the example below Thread2 has no idea when Thread1 is trying to exit , it simply for... | class Scratch { public static void main ( String [ ] args ) { Thread Task1 = new Thread ( new Task1 ( ) ) ; Task1.start ( ) ; Thread Task2 = new Thread ( new Task2 ( ) ) ; Task2.start ( ) ; // ... more threads } public class Task1 implements Runnable { public void run ( ) { while ( true ) { // ... System.exit ( 0 ) ; /... | How to safely close all threads before exit |
Java | Just came across a place where I 'd like to use generics and I 'm not sure how to make it work the way I want.I have a method in my data layer that does a query and returns a list of objects . Here 's the signature.This is what I 'd like the calling code to look like.I 'd like to make it so that I do n't have to cast t... | public List getList ( Class cls , Map query ) List < Whatever > list = getList ( WhateverImpl.class , query ) ; public < T > List < T > getList ( Class < T > cls , Map query ) | Java generics question with wildcards |
Java | This is a plain Java 8+ question , no frameworks used.We are producing an API for a higher layer which deals with the presentation layer among other activities . We have and interface agreed with the invoker , so they are happy to receive some particular exceptions we throw.At the same time , we are also using other AP... | public void method1 ( arguments for method 1 ) { ... } ... public void method300 ( arguments for method 300 ) { ... } public void myExceptionHandler ( Exception e ) { if ( e instanceOf X ) { } else if ... ... throw particularExceptionAccordingTheCase } public class myExceptionHandler implements Thread.UncaughtException... | How to centralize exception handling in multiple methods of an API |
Java | I 'm looking for an explanation for Java 's behavior when handling the following scenarios . I understand that the ASCII table is arranged so that the value of the character 5 is five positions greater than 0 . This allows for calculations to be done on the char without converting to an int as seen in the first example... | int x = ' 5 ' - ' 0 ' ; int x = ' 5 ' int x = ' 0 ' + 1 - ' 5 ' int y = ' 5 ' - ' 0 ' + ' 1 ' int y = ' 5 ' - 0 + ' 1 ' | Java implicit conversion between int and char |
Java | I do some image processing with OpenCV . I want to invert this bitmap ( black to white , white to black ) and i have some problems with it.I got this Bitmap after doing this : This is the result after inverting.This is my code : The white lines from the first image should be inverted to black lines , but it´s not worki... | // to greyImgproc.cvtColor ( mat , mat , Imgproc.COLOR_RGB2GRAY , 4 ) ; Imgproc.adaptiveThreshold ( mat , mat , 255 , Imgproc.ADAPTIVE_THRESH_MEAN_C , Imgproc.THRESH_BINARY_INV , 15 , 4 ) ; Utils.matToBitmap ( mat , bitmapCopy ) ; // to grey Imgproc.cvtColor ( mat , mat , Imgproc.COLOR_RGB2GRAY , 4 ) ; Imgproc.adaptive... | Inverting black and white on a bitmap is not working |
Java | I need to type method signature so it accepts 2 equally typed parameters of different particular concrete subtypes.Is it possible to code something like this with generics ? How would you solve it ? ( The case is absolutely an example ) EDIT : In the end , what I am looking for is a way for the compiler to pass : but n... | public < T extends List < ? > > T < String > sum ( T < Integer > sublistOfInts , T < Boolean > sublistOfBooleans ) { /*fusion both lists*/ return sublistOfStrings ; } ArrayList < String > myList = sum ( new ArrayList < Integer > ( ) , new ArrayList < Boolean > ( ) ) ; ArrayList < String > myList = sum ( new ArrayList <... | Typing a generic type but not its own type in Java Generics |
Java | I recently learned , while converting some Java code to C # , that Java 's increment operator '+= ' implicitly casts to the type of LHS : is equivalent to : ( details here ) thus silently causing the opportunity for loss of magnitude.C # is more conscientious about this at compile-time : Can not convert source type lon... | int i = 5 ; long lng = 0xffffffffffffL ; //larger than Int.MAX_VALUEi += lng ; //allowed by Java ( i==4 ) , rejected by C # int i = 0 ; long lng = 0xffffffffffffL ; i = ( int ) ( i + lng ) ; | Java implicit casts that can lead to precision or magnitude loss ? |
Java | I have a test class with multiple nested test classes inside . The outer test class uses an extension that implements BeforeAllCallback and AfterAllCallback . The methods of these interfaces are called for each nested class when executing the outer test class . Is this expected behaviour ? I could not find any document... | @ ExtendWith ( MyExtension.class ) public class SomeTest { @ BeforeAll static void create ( ) { System.out.println ( `` Call beforeAll of test class '' ) ; } @ AfterAll static void destroy ( ) { System.out.println ( `` Call afterAll of test class '' ) ; } @ Nested class InnerTest1 { @ Test void testingA ( ) { System.ou... | BeforeAll / AfterAll callbacks of junit5 extension are executed for each nested test class . Is this expected ? |
Java | I am using JGit API ( https : //www.eclipse.org/jgit/ ) to access a git repository . In the git repository , I am storing .txt files and other file formats also . I ran into a requirement where I should get the diff of only .txt files . Basically I am trying to achieve the equivalent of How to filter git diff based on ... | git diff master HEAD -- '*.txt ' | jgit - git diff based on file extension |
Java | This is a weird error . After adding the selenium dependencies to the pom of my maven project and upload it to a lambda , it says it is unable to unzip the file . However after removing the dependencies , the lambda is able to unzip the file just fine ( however it comes up with a class not found afterwards ) . I have t... | org/openqa/selenium/WebDriver : java.lang.NoClassDefFoundErrorjava.lang.NoClassDefFoundError : org/openqa/selenium/WebDriver Calling the invoke API action failed with this message : Lambda was not able to unzip the file < dependency > < groupId > org.seleniumhq.webdriver < /groupId > < artifactId > webdriver-common < /... | AWS Lambda Jar unable to zip after adding selenium dependencies in pom |
Java | When I try to write in a file a binary files with value like this : The thing is that when I look at the file generated , it seems that the double is putted in little endian style , and when I switch ByteOrder to little-endian , the double is written in big-endian ... But when I put an int , the endianness is correct.O... | public static main ( String [ ] args ) { ByteBuffer output = ByteBuffer.allocate ( 80 ) ; output.order ( ByteOrder.BIG_ENDIAN ) ; output.putDouble ( 545.5 ) ; appendByteArrayInFile ( `` c : /myPath/ '' , `` test.bin '' , output.array ( ) ) ; } private static void appendByteArrayInFile ( String exportDirectory , String ... | Java ByteBuffer BigEndian Double |
Java | I would like to deploy an artifact together with javadoc and a Maven site . I use ( the split between site and site : deploy is just to avoid the deployment of a site if deploy fails ) . Now the javadoc is created twice - once in javadoc : jar and once in site . Is it possible to create it just once and use it both for... | clean javadoc : jar site deploy site : deploy | How to avoid calling javadoc more than once if creating a site ? |
Java | While going through articles of sequential streams the question came in my mind that are there any performance benefits of using sequential streams over traditional for loops or streams are just sequential syntactic sugar with an additional performance overhead ? Consider Below Example where I can not see any performan... | Stream.of ( `` d2 '' , `` a2 '' , `` b1 '' , `` b3 '' , `` c '' ) .filter ( s - > { System.out.println ( `` filter : `` + s ) ; return s.startsWith ( `` a '' ) ; } ) .forEach ( s - > System.out.println ( `` forEach : `` + s ) ) ; String [ ] strings = { `` d2 '' , `` a2 '' , `` b1 '' , `` b3 '' , `` c '' } ; for ( Strin... | Are there any direct or indirect performance benefits of java 8 sequential streams ? |
Java | I 'm trying to understand how method references work in java.At first sight it is pretty straightforward . But not when it comes to such things : There is a method in Foo class : And in another class Bar there is a method like this : And a method reference is used : It complies and works , but I do n't understand how d... | public class Foo { public Foo merge ( Foo another ) { //some logic } } public class Bar { public void function ( BiFunction < Foo , Foo , Foo > biFunction ) { //some logic } } new Bar ( ) .function ( Foo : :merge ) ; Foo merge ( Foo another ) R apply ( T t , U u ) ; | Java method reference resolving |
Java | I 'm trying Java 8 , I want to iterate over 2 collections and call a parameter function for each pair of values.In abstract , I want to apply a foo ( tuple , i ) function for each iterationNow what I got so far ( java and pseudo code ) | [ v1 , v2 , v3 , v4 , v5 , v6 ] ( first collection ) [ w1 , w2 , w3 , w4 , w5 , w6 ] ( second collection ) -- -- -- -- -- -- -- -- -- -- -- -- -- - foo ( < v1 , w1 > , 0 ) foo ( < v2 , w2 > , 1 ) ... foo ( < v6 , w6 > , 5 ) // Type of f ? private < S , U > void iterateSimultaneously ( Collection < S > c1 , Collection <... | Creating a lambda function to iterate collections simultaneously |
Java | I have been skimming through the news and the source code of Java 16 and I have encountered with new Stream method called mapMulti . The early-access JavaDoc says it is similar to flatMap and has been already approved to the very same Java version.How to perform one to 0..n mapping using this method ? How does the new ... | < R > Stream < R > mapMulti ( BiConsumer < ? super T , ? super Consumer < R > > mapper ) | When and how to perform one to 0..n mapping Stream mapMulti over flatMap as of Java 16 |
Java | Java disallows usage of final variable inside a supplier as it might not be initialized , yet prepending `` ( this ) . '' to variable makes it compile and run fine . Furthermore calling such supplier results in NullPointerException instead of compiler error if called before assigning the variable and runs as expected i... | import java.util.function.Supplier ; class Example { final String str ; Supplier < Integer > test1 = ( ) - > str.length ( ) ; // DOES NOT COMPILE Supplier < Integer > test2 = ( ) - > this.str.length ( ) ; // DOES NOT COMPILE Supplier < Integer > test3 = ( ) - > ( this.str ) .length ( ) ; // DOES NOT COMPILE Supplier < ... | Java 8 supplier behaviour : final variable might not be initialized |
Java | For better debugging , I would often like to have : The debug stack frame as shown above would be dynamically generated , just like a java.lang.reflect.Proxy , except that I 'd like to be in full control of the entire fully qualified method name that ends up on the proxy.At the call site , I would do something silly an... | Exception at com.example.blah.Something.method ( ) at com.example.blah.Xyz.otherMethod ( ) at com.example.hello.World.foo ( ) at com.example.debug.version_3_8_0.debug_info_something.Hah.method ( ) // synthetic method at com.example.x.A.wrappingMethod ( ) public void wrappingMethod ( ) { run ( `` com.example.debug.versi... | How to dynamically generate a stack frame with debug log information |
Java | Joda 's AbstractInstant interface extends the raw type Comparable , instead of Comparable < AbstractInstant > , which seems to violate Java best practices . In particular , it means that I can not use DateTime to parameterize a class like this : It was my understanding this kind of class was perfectly valid ( it certai... | class Foo < T extends Comparable < ? super T > > { public int ct ( T a , T b ) { return a.compareTo ( b ) ; } } @ SuppressWarnings ( `` unchecked '' ) class Foo < T extends Comparable > { public int ct ( T a , T b ) { return a.compareTo ( b ) ; } } | Why do Joda instants extend the raw type Comparable ? |
Java | I am using a large open source library and need to generate personal subclasses of a few of the classes . What are the best strategies ? I would like to keep the original library unaltered and be easily able to reconfigure when it is updated . It is unlikely that my code is worth contributing to the project ( though I ... | public static org.apache.batik.svggen.SVGGraphics2D createSVG ( ) { org.w3c.dom.DOMImplementation domImpl = org.apache.batik.dom.GenericDOMImplementation.getDOMImplementation ( ) ; org.w3c.dom.Document document = domImpl.createDocument ( `` http : //www.w3.org/2000/svg '' , `` svg '' , null ) ; return new org.apache.ba... | subclassing an open-source library |
Java | I have this factory collection : which embeds the Product as products . When I have to add a product to an existing factory : However , the issue is that product is a large object which contains a set of heavy attributes and the factory can have 2000 products . So , the retrieved factory causes large memory consumption... | @ Document ( collection = `` factory '' ) public class Factory { Private List < Product > products ; } @ Autowiredprivate FactoryRepository factoryRepository ; public void addProduct ( Long id , Product product ) { Factory f = factoryRepository.findById ( id ) ; f.addProduct ( product ) ; factoryRepository.save ( f ) ;... | Insert embeded document without reading whole document - spring , mongo |
Java | I do n't know where to seek clarifications and confirmations on Java API documentation and Java code , so I 'm doing it here.In the API documentation for FileChannel , I 'm finding off-by-one errors w.r.t . to file position and file size in more places than one.Here 's just one example . The API documenation for transf... | public long transferFrom ( ReadableByteChannel src , long position , long count ) throws IOException { // ... if ( position > size ( ) ) return 0 ; // ... } | Is this an off-by-one bug in Java 7 ? |
Java | If I execute the JUnit test below WITHOUT the line `` inputStream.close ( ) '' ( see below ) , more than 60000 requests can be processed ( I killed the process then ) . WITH this line , I did not manage making more than 15000 requests , because of : I run it on Windows , before starting the test I wait for the netstat ... | java.net.SocketException : No buffer space available ( maximum connections reached ? ) : connect at java.net.PlainSocketImpl.socketConnect ( Native Method ) at java.net.PlainSocketImpl.doConnect ( PlainSocketImpl.java:351 ) at java.net.PlainSocketImpl.connectToAddress ( PlainSocketImpl.java:213 ) at java.net.PlainSocke... | Client SocketInputStream.close ( ) leads to more resource consumption ? |
Java | I 'm experiencing an unexpected interaction between system events and the window refresh rate in simple Java2D applications on Linux/XWindows . It is best demonstrated with the small example below.This program creates a small window in which a half-circle is displayed at different rotations . The graphics are updated a... | public class Test { // pass the path to 'test.png ' as command line parameter public static void main ( String [ ] args ) throws Exception { BufferedImage image = ImageIO.read ( new File ( args [ 0 ] ) ) ; // create window JFrame frame = new JFrame ( ) ; Canvas canvas = new Canvas ( ) ; canvas.setPreferredSize ( new Di... | Java2D : interaction between XWindows events and frame rate |
Java | program output : Hello world ! .I thought it would throw a NullPointerException . Why is it happenning ? | public class Null { public static void greet ( ) { System.out.println ( `` Hello world ! `` ) ; } public static void main ( String [ ] args ) { ( ( Null ) null ) .greet ( ) ; } } | Why does this not cause a NullPointerException ? |
Java | I tried to implement an Enum styled factory pattern as inner Enum , but it did n't work.Is there any solution without separating inner Enum into a new file ? In other words , is it possible of inner Enum styled factory pattern ? The code is below.The compile error message is below | public class SampleParent { private class InnerChild { } private class InnerChildA extends InnerChild { } private class InnerChildB extends InnerChild { } private class InnerChildC extends InnerChild { } enum InnerChildEnum { CHILD_A { @ Override public InnerChild getInstance ( ) { return new InnerChildA ( ) ; // compi... | Enum styled factory as inner Enum in Java |
Java | I 've made a simple code to get jumping ball positions , but I definitely missed something , because I get this : Here 's the code for getting x and y positions : | public Vector2f [ ] draw ( ) { float x = 0 , y = height ; // height - float value from class constructor ; ArrayList < Vector2f > graphic = new ArrayList < Vector2f > ( ) ; for ( ; ; ) { Vector2f a = new Vector2f ( x , y ) ; graphic.add ( a ) ; ySpeed -= 10 ; y += ySpeed*Math.cos ( angle ) ; x += xSpeed*Math.sin ( angl... | Jumping ball physics in java , gravity |
Java | I compiled a simple Java file to assembly using Java 8 on Mac OS X . This is Test.java : I output the assembly code using : This is the Test.asm output : The question is : why does the generated assembly code have two main methods and how do I make it have only one ? | public class Test { static volatile int a = 1 ; public static void main ( String [ ] args ) { a++ ; } } java -server -Xcomp -XX : +UnlockDiagnosticVMOptions -XX : -Inline -XX : CompileCommand=print , *Test.main Test > Test.asm CompilerOracle : print *Test.mainCompiled method ( c1 ) 1733 1750 3 Test : :main ( 9 bytes ) ... | Why does Java compile to assembly twice ? |
Java | ERROR : Can not make a static reference to the non-static field name | String name = `` Marcus '' ; static String s_name = `` Peter '' ; public static void main ( String [ ] args ) { System.out.println ( name ) ; //ERROR System.out.println ( s_name ) ; //OK } | Why is there a problem with a non-static variable being read from main ? |
Java | let 's say I have this code in javascript : and let the code in the servlet be : Will xhr1 still wait for new changes in readystate ? Or it is closed as soon as it gets the first response ? If it remains open , will it lead to memory leaks/slower browser after a while and accumulating a few of those ? Should I always c... | function doAnAjaxCall ( ) { var xhr1 = new XMLHttpRequest ( ) ; xhr1.open ( 'GET ' , '/mylink ' , true ) ; xhr1.onreadystatechange = function ( ) { if ( this.readyState == 4 & & this.status==200 ) { alert ( `` Hey ! I got a response ! `` ) ; } } ; xhr1.send ( null ) ; } public class RootServlet extends HttpServlet { pu... | What is the life span of an ajax call ? |
Java | I was wondering if there is a Java API that could tell you whether a particular language feature ( e.g . `` diamond '' operator ) is available on the current platform . ( In other words , what I 'm trying to do is analogous to `` browser sniffing '' in JavaScript . ) This would be really handy in meta-programming ( wri... | code.append ( `` Map < Integer , String > map = `` ) ; if ( javax.meta.JavaVersion.getCurrentVersion ( ) .supportsDiamond ( ) ) { code.append ( `` new Map < > ( ) ; '' ) ; } else { code.append ( `` new Map < Integer , String > ( ) ; '' ) ; } | Any way to programmatically determine which Java language features are available on current platform ? |
Java | note : I am new to play frameworkFor my Play ! project , I require some form of asynchronous programming . Simply , I need to display a view , whilst doing processing in the background , followed by a redirect or a new form being rendered.This question has been asked with no response . I have had a look on the Play Doc... | public CompletionStage < Result > message ( ) { return getFutureMessage ( 5 , TimeUnit.SECONDS ) .thenApplyAsync ( s - > ok ( views.html.User.Account.verified.render ( ) ) , exec ) ; } private CompletionStage < String > getFutureMessage ( long time , TimeUnit timeUnit ) { CompletableFuture < String > future = new Compl... | play framework - render view while doing processing/redirect after X seconds |
Java | I have some class which is not thread safe : ( I 've used a long as the field here , but we should think of its field as being some thread-unsafe type ) .I now have a class which looks like thisThat is , the thread unsafe class is a final field of it . Now I 'm going to do this : That is , from thread T ( main ) , I in... | class ThreadUnsafeClass { long i ; long incrementAndGet ( ) { return ++i ; } } class Foo { final ThreadUnsafeClass c ; Foo ( ThreadUnsafeClass c ) { this.c = c ; } } public class JavaMM { public static void main ( String [ ] args ) { final ForkJoinTask < ThreadUnsafeClass > work = ForkJoinTask.adapt ( ( ) - > { ThreadU... | Can a non-thread-safe value be safely ported across thread boundaries using fork/join ? |
Java | I am new in Java Programming language . I am familiar with C and C++ but unable to understand the behaviour of the below program.Correct Output : Output expected : Even changing the line from y = 44 ; to this.y = 44 ; is not giving the expected output . | public class Test { static int x = 11 ; private int y = 33 ; public void method1 ( int x ) { Test t = new Test ( ) ; this.x = 22 ; y = 44 ; System.out.println ( `` Test.x : `` + Test.x ) ; System.out.println ( `` t.x : `` + t.x ) ; System.out.println ( `` t.y : `` + t.y ) ; System.out.println ( `` y : `` + y ) ; } publ... | Behaviour of local and class variables in java |
Java | When using Mockito , I only use it to mock out dependencies , i.e . my workflow looks mostly like this : I have a class with dependencies : In my test class , I mock out those dependencies , and tell them which values to return when some specified methods are called : ( I hope this example is not too simple or too deri... | public class C { public C ( A a , B b ) { this.a = a ; this.b = b ; } public String fooBar ( ) { return a.foo ( ) + b.bar ( ) ; } } public class CSpec { private A a = mock ( A.class ) ; private B b = mock ( B.class ) ; @ Test public itShouldReturnFooBar ( ) { when ( a.foo ( ) ) .thenReturn ( `` foo '' ) ; when ( b.bar ... | Mockito - Feeling that I do n't use its full potential |
Java | So I have a couple futures which I want to run , even if some fail I 'd like all to have a chance to run . So if I do : Will that be the case ? My reasoning is that every future would have its own queed job in its executor and therefore all would run provided the main thread does n't finish first . My issue is that I s... | CompletableFuture.allOf ( futures ) .join ( ) Stream.of ( futures ) .forEach ( future - > { try { future.join ( ) } catch ( Throwable e ) { //dont throw , we want to join the rest } } ) Stream.of ( futures ) .forEach ( future - > { try { future.join ( ) } catch ( Throwable e ) { throw e ; //All other remaining .join ( ... | Will all futures passed to CompletableFuture.allOf ( ) run ? |
Java | Should I use `` _activity = this ; '' ? I 've seen _activity referenced many times in sample code . So , I arbitrarily decided that it looked like a good practice and have been using in all my code for awhile ( over a year ) . But , before I start spreading the word around more I wanted to find some proper documentatio... | public class MainActivity extends Activity { MainActivity _activity ; @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; _activity = this ; // TODO : Find out if this is good practice ? setContentView ( R.layout.activity_main ) ; } public void onClickButton ( View... | Should I use `` _activity = this ; '' ? |
Java | How can the static inner class M and static member M [ of class C ] share the same name ? The following code generates `` White '' as output : how the member object is accessed and not the static class member : W [ `` Black '' ] if i want to access the member within static class M how to do that ? | public class Amazed { public static void main ( String [ ] args ) { System.out.println ( B.M.W ) ; } } class B { public static class M { static String W = `` Black '' ; } static C M = new C ( ) ; } class C { String W = `` White '' ; } | static inner class and static member of a class shares SAME NAME ? |
Java | BackgroundIn Java 101 , we 're taught : A String is immutable.Yes . Good . Thanks.Then we get to Java 102 ( or perhaps Java 201 ) , and we discover : A String is n't really immutable : you can change it using reflection.Ah . Fine . Either quite cute or immeasurably perverse , depending on your perspective.These things ... | String prop = `` java.version '' ; // retrieve a System property as a String String s = System.getProperty ( prop ) ; System.out.println ( s ) ; // now mess with it Field field = String.class.getDeclaredField ( `` value '' ) ; field.setAccessible ( true ) ; char [ ] value = ( char [ ] ) field.get ( s ) ; value [ 0 ] = ... | What are the implications of Java strings not really being immutable ? |
Java | I 'm not habitual to casting a primitive data type to an object . Saw some code like : The instantiation of age1 seemed extraneous , so I tried to write the code as : But that raised a compiler error because p1.getAge ( ) is a primitive data type int and not an Integer , which is an object.Intuitively , I did : and it ... | public static int CompareAges ( Person p1 , Person p2 ) { Integer age1 = p1.getAge ( ) ; return age1.compareTo ( p2.getAge ( ) ) ; } public static int CompareAges ( Person p1 , Person p2 ) { return p1.getAge ( ) .compareTo ( p2.getAge ( ) ) ; } public static int CompareAges ( Person p1 , Person p2 ) { return ( ( Intege... | Casting a primitive vs Creating a object of the primitive |
Java | Gives me this , which is as expected . But when I highlight it and copy paste it , I get `` somewords otherwords '' . The same thing done inside Firefox when copied would paste `` somewords [ fire3 ] otherwords '' ( it substitutes alt text for image ) . Is there any way to replicate this behavior where the alt text is ... | JTextPane text ; text.setText ( `` somewords < img src=\ '' file : ///C : /filepath/fire.png\ '' text=\ '' [ fire1 ] \ '' title=\ '' [ fire2 ] \ '' alt=\ '' [ fire3 ] \ '' style=\ '' width:11px ; height:11px ; \ '' > otherwords '' ) ; // ( should ) allow copying of alt text in place of imagesclass CustomEditorKit exten... | Copying img from HTML in Java Swing |
Java | I 'm developing the server part of a system that has to send messages to a device . This was working fine with the GoogleLogin method , but I want to migrate it to OAuth 2.0 since the other authentication method has been deprecated.In the Google API console I created a project and then I created a key for a service acc... | public boolean authenticateServer ( ) { try { File privateKey = new File ( getClass ( ) .getResource ( `` /something-privatekey.p12 '' ) .toURI ( ) ) ; GoogleCredential cred = new GoogleCredential.Builder ( ) .setTransport ( new NetHttpTransport ( ) ) .setJsonFactory ( new JacksonFactory ( ) ) .setServiceAccountId ( ``... | How can I send a message to a device using C2DM from a server that has been authenticated with OAuth2 ? |
Java | I 'm trying to compile a simple Java Hello World application to native code using the native-image utility provided by GraalVM on Windows but I always run into errors ( see below ) .HelloWorld.java : First , I compile the code to a class file using the following command : Next , I invoke the native-image command from t... | public class HelloWorld { public static void main ( String [ ] args ) { System.out.println ( `` Hello , World ! `` ) ; } } > javac HelloWorld.java > native-image -H : +ReportExceptionStackTraces HelloWorld [ helloworld:20420 ] classlist : 1,249.05 ms [ helloworld:20420 ] ( cap ) : 704.71 ms [ helloworld:20420 ] setup :... | Can not compile simple `` Hello World '' Java application with native-image on Windows |
Java | I 'm trying to play ads on Android using the Google IMA sdk . I used the example app to come to my solution but for some reason I only get the audio of the ad and the overlay ( ad length , read more button etc. ) . The video is not playing , or at least invisible.I build up the video player using the VideoView : Is any... | package eu.myapp.test.views ; import android.media.MediaPlayer ; import android.view.View ; import android.view.ViewGroup ; import android.widget.MediaController ; import android.widget.VideoView ; import android.media.MediaPlayer.OnCompletionListener ; import android.media.MediaPlayer.OnErrorListener ; import android.... | Google Ima SDK , sound playing but no view |
Java | Why does the following happen : By saying < T extends Foo > am I saying that Foo can be overridden with a super type ? Note : My question is not why function2 ( ) throws an error ... but why function1 ( ) does n't throw an error . | public class one { public < T extends Foo > Bar < Foo > function1 ( ) { } public Bar < Foo > function2 ( ) { } } public class two < F extends Foo > extends one { public Bar < F > function1 ( ) { } //Does n't throw an error public Bar < F > function2 ( ) { } //Throws an error } | Java Generics and overridding |
Java | I 'm looking for a standard Javafx or java interface ( if it exists ) that acts like a Callback , except that it does not return a value.The standard Callback from javafx.util package is as follows : This is useful when you need to return the value , but I do n't . I 've looked into Callable < T > : But this does n't a... | public interface Callback < P , R > { public R call ( P param ) ; } public interface Callable < V > { V call ( ) throws Exception ; } public interface Callable < V > { void call ( V value ) throws Exception ; } | Javafx like Callback but without return |
Java | Assuming that I have given a Stream of Futures , which I want to reduce by invoking the Stream # reduce method.But I do n't want to reduce the Futures itself , but the result of the Future ( Future # get ) .The problem is , that the get method may throw an ExecutionException and does not provide a result in this case.T... | Stream < Future < Integer > > stream = ... ; BinaryOperator < Integer > sum = ( i1 , i2 ) - > i1 + i2 ; stream.map ( future - > future.get ( ) ) .reduce ( sum ) ; // does not work , get needs to handle exceptions ! stream.map ( future - > { Integer i = null ; try { i = future.get ( ) ; } catch ( InterruptedException e ... | How to reduce a stream of Futures in Java ? |
Java | E.g. , It should execute only if exactly one of the conditions is met . | if ( bool1 ^ bool2 ^ bool3 ^ bool4 ) { // Do whatever } | Is it possible to use XOR to detect if exactly one of multiple conditions is true ? |
Java | I 'm trying to match the string iso_schematron_skeleton_for_xslt1.xsl against the regexp ( [ a-zA-Z|_ ] ) ? ( \w+|_|\.|- ) + ( @ \d { 4 } -\d { 2 } -\d { 2 } ) ? \.yang.The expected result is false , it should not match.The problem is that the call to matcher.matches ( ) never returns.Is this a bug in the Java regexp i... | import java.util.regex.Matcher ; import java.util.regex.Pattern ; public class HelloWorld { private static final Pattern YANG_MODULE_RE = Pattern .compile ( `` ( [ a-zA-Z|_ ] ) ? ( \\w+|_|\\.|- ) + ( @ \\d { 4 } -\\d { 2 } -\\d { 2 } ) ? \\.yang '' ) ; public static void main ( String [ ] args ) { final Matcher matcher... | Is this a bug in the Java regexp implementation ? |
Java | This question is different from this one Difference between Java8 thenCompose and thenComposeAsync because I want to know what is the writer 's reason for using thenCompose and not thenComposeAsync.I was reading Modern Java in action and I came across this part of code on page 405 : Everything is Ok and I can understan... | public static List < String > findPrices ( String product ) { ExecutorService executor = Executors.newFixedThreadPool ( 10 ) ; List < Shop > shops = Arrays.asList ( new Shop ( ) , new Shop ( ) ) ; List < CompletableFuture < String > > priceFutures = shops.stream ( ) .map ( shop - > CompletableFuture.supplyAsync ( ( ) -... | Is the writer 's reason correct for using thenCompose and not thenComposeAsync |
Java | In the oracle docs , it appears to be For mapper as a Function , it makes the parameter contra-variant but does not make the return type covariant . I wonder if the mapper can ( should ) be or ? | < U > Optional < U > flatMap ( Function < ? super T , Optional < U > > mapper ) Function < ? super T , Optional < ? extends U > > Function < ? super T , ? extends Optional < ? extends U > > | The signature of flatMap in Optional of Java 8 |
Java | I want communicate between java and typescript with encrypted AES-GCM data ( PBKDF2 hash used for password ) .I used random bytes for pbkdf2 : This is my java PBKDF2 Code : and this is typescript code : Result in java and typescript : Why i have difference result ? What part of code has wrong ? UPDATEInteresting , I tr... | randomBytes ( Base64 ) : wqzowTahVBaxuxcN8vKAEUBEo0wOfcg4e6u4M9tPDFk= private String salt = `` 1234 '' ; private static final String KEY_ALGORITHM = `` AES '' ; private Key generateKey ( byte [ ] randomBytes ) throws Exception { var randomPassword = new String ( randomBytes ) ; KeySpec keySpec = new PBEKeySpec ( random... | Java and typescript generate difference PBKDF2 hash |
Java | I am still new to Docker and Gradle , but I am trying to setup a Gradle build that builds a Docker image.I just finished setting up a Dockerfile which locally deploys and runs the jar as expected . I have this in my build.gradle : I run ./gradlew build buildDocker to build the image . I am happy with this so far.Usuall... | buildscript { repositories { mavenCentral ( ) } dependencies { classpath 'se.transmode.gradle : gradle-docker:1.2 ' } } plugins { id 'com.github.johnrengelman.shadow ' version ' 1.2.3 ' } apply plugin : 'docker'jar { manifest { attributes 'Main-Class ' : 'com.myapp.Main ' } } task buildDocker ( type : Docker , dependsO... | Gradle task for Java playground |
Java | I 'm trying to integrate Eclipse Texo into my existing Hibernate project . I have modeled my domain model in ECore and generated both EMF and POJO code from there using Texo and the regular EMF code generation.Fetching entities ( POJOs ) stored in the database works without problems , now I would like to use Texo 's Mo... | public ModelObject < ? > getModelObject ( final Object target ) { /* ... snip ... */ final ModelDescriptor modelDescriptor = getModelDescriptor ( target.getClass ( ) , true ) ; return modelDescriptor.createAdapter ( target ) ; } final List < Object > objects = entities .stream ( ) .map ( o - > o instanceof HibernatePro... | Eclipse Texo ModelEMFConverter and Hibernate proxies |
Java | update : looks like it 's not a memory leak , would someone create on based on an extension of this example ? Original question : Suppose I create and starts a thread that does not terminate , the thread creates an object and references as long as it 's alive . See the following code . Would the JVM garbage collect x ?... | public class MyRunnable implements Runnable { public void run ( ) { X x = new X ( ) ; while ( true ) { } } } Thread t = new Thread ( new MyRunnable ( ) ) ; t.start ( ) ; | is this a java memory leak |
Java | I am working on the following problem : In a room with people , we will define two persons are friends if they are directly or indirectly friends . If A is a friend with B , and B is a friend with C , then A is a friend of C too . A group of friends is a group of persons where any two persons in the group are friends .... | 1 < - > 6 2 < - > 73 < - > 84 < - > 92 < - > 63 < - > 5 1-6-2-73-8-54-9 private static int findGroups ( final List < List < Integer > > inputs ) { if ( inputs == null || inputs.isEmpty ( ) ) { return 0 ; } int count = Integer.MAX_VALUE ; Map < Integer , List < Integer > > holder = new HashMap < > ( ) ; for ( List < Int... | find a smaller group of friends from the circle ? |
Java | æ , ø , å are latest letters in the norwegian alphabet When we try to sort it using Hibernate Lucene then Å clubs with A , Ø clubs with Ø , Æ clibs with A which is wrong . For example : Currrent Results : Aaalu , Åaalu , Baalu , Zaalu , Expected Results : Aaalu , Baalu , Zaalu , Åaalu , Following is working code : Main... | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z Æ Ø Å @ AnalyzerDef ( name = `` myOwnAnalyzer '' , tokenizer = @ TokenizerDef ( factory = KeywordTokenizerFactory.class ) , filters = { @ TokenFilterDef ( factory = ASCIIFoldingFilterFactory.class ) , @ TokenFilterDef ( factory = LowerCaseFilterFactory.class ) , @ Tok... | How to do case insensitive sorting of Norwegian characters ( Æ , Ø , and Å ) using Hibernate Lucene Search ? |
Java | I am a Javascript front-end developer , but need to write a simple Java program to write file and sent Email and HTTP request . Here is the Java code that I use to write log to disk file : You can ignore the detail . My real question is that for those heavy IO operation , e.g . : file reading , sending email and making... | @ Overridepublic void log ( String text ) { Date date = new Date ( ) ; DateFormat sdf = new SimpleDateFormat ( `` yyyyMMdd '' ) ; DateFormat sdf1 = new SimpleDateFormat ( `` HH : mm : ss '' ) ; String logDateString = sdf.format ( date ) ; //System.out.println ( `` logDateString : `` + logDateString ) ; BufferedWriter b... | Is there a callback function concept in Java to do async I/O as it is in Javascript ? |
Java | Basically this came up while trying to answer another question . Suppose this code : I understand the fact that IntStream # generate is an unordered infinite stream and for it to finish there has to be a short-circuiting operation ( limit in this case ) . I also understand that the Supplier is free to be called as many... | AtomicInteger i = new AtomicInteger ( 0 ) ; AtomicInteger count = new AtomicInteger ( 0 ) ; IntStream.generate ( ( ) - > i.incrementAndGet ( ) ) .parallel ( ) .peek ( x - > count.incrementAndGet ( ) ) .limit ( 5 ) .forEach ( System.out : :println ) ; System.out.println ( `` count = `` + count ) ; | Internal changes for limit and unordered stream |
Java | I have a list of objects and i want to process subset of objects based on condition and then create a new list with processed objects.The List if ObjectsIn the above list i want to the names which has two titles ( kim taylor ) and glue the title because prof is a subset of prof.dr . My final list should look like the f... | miss | shannon sperlingmr | john smithprof | kim taylorprof.dr | kim taylor miss | shannon sperlingmr | john smithprof.dr | kim taylor void gluetitles ( List title ) { for ( int i=0 ; i < title.size ( ) ; i++ ) { String names = ( String ) title.get ( i ) ; String [ ] titlename=names.split ( `` \\| '' ) ; \\split the li... | processing list of objects in Java |
Java | I am currently creating a Map < String , Map < LocalDate , Integer > > like this , where the Integer represents seconds : How could I instead create a Map < String , Map < LocalDate , Duration > > ? | Map < String , Map < LocalDate , Integer > > map = stream.collect ( Collectors.groupingBy ( x - > x.getProject ( ) , Collectors.groupingBy ( x - > x.getDate ( ) , Collectors.summingInt ( t - > t.getDuration ( ) .toSecondOfDay ( ) ) ) ) ) ; | How to get a custom type instead of Integer when using Collectors.summingInt ? |
Java | Possible Duplicate : Why use getters and setters ? This is a newbie question . Is it very much necessary to use getmethods to access property values ? Once the value has been assigned , one can get the values directory . For example , in the below code , displayName ( ) can display firstName value without the help of a... | class Test { private String firstName ; public void setName ( String fname ) { firstName = fname ; } public void displayName ( ) { System.out.println ( `` Your name is `` + firstName ) ; } } | Necessity of getter methods |
Java | I 'm trying to develop an static method in Java to generate a pure tone.In the begining it seemed easy , but when I 've try to write the double array to the loudspeakers I appreciate too much harmonics.I test it with an spectrum analyzer ( sonometer ) and then , also I 've drawn in a graphic the array resultant . When ... | /** * Genera un tono puro . * @ param bufferSize Tamaño del buffer . * @ param fs Frecuencia de muestreo . * @ param f0 Frecuencia central . * @ return El tono puro . */public static double [ ] generateTone ( int bufferSize , int fs , int f0 ) { double [ ] tone = new double [ bufferSize ] ; // Tono double angle ; // Án... | Reduce harmonics generating a pure tone in Java |
Java | When a Java member needs to be thread-safe , we do like the following : This syntax equivalent to : That is , it actually uses this for a lock.My question is , if I use synchronized with a static method , as follows : In this case , on what is the lock made for the synchronized method ? | public synchronized void func ( ) { ... } public void func ( ) { synchronized ( this ) { ... . } } class AA { private AA ( ) { } public static synchronized AA getInstance ( ) { static AA obj = new AA ( ) ; return obj ; } } | How a static synchronized function works ? |
Java | Is there any difference between following two initializations of static variables : Are these two different ways of initializing a static variable functionally the same ? | class Class1 { private static Var var ; static { var = getSingletonVar ( ) ; } } class Class2 { private static var = getSingletonVar ; } | Difference between static block and assigning static in class ? |
Java | Consider this example : Why does it print 1 in ( A ) , but 2 with ( B ) ? I know how method resolution works , so no need to explain that to me.I want to know the deeper motivation behind this `` feature '' .Why is there no erasure warning about it ? ( There is just one about Foo foo = new Foo ( ) . ) Why does method r... | import java.util . * ; class Foo < T > { public int baz ( List < String > stringlist ) { return 1 ; } public int baz ( ArrayList < Object > objectlist ) { return 2 ; } public static void main ( String [ ] args ) { Foo < String > foo = new Foo < String > ( ) ; // ( A ) //Foo foo = new Foo ( ) ; // ( B ) System.out.print... | Why do raw types in one place cause generic callsites somewhere else to be treated as raw ? |
Java | Consider this code : With javac version 1.6.0_29 , it fails to compile , stating : Yes , this is silly code and there are at least two obvious workarounds , but I 'm curious . Based on section 15.12.2 of the specification , this compilation error seems like a bug in javac , because the first step should remove the non-... | class Foo { public void doIt ( String ... strs ) { System.out.println ( `` this is varargs '' ) ; } private void doIt ( String str ) { System.out.println ( `` this is single '' ) ; } } class Bar { public static void main ( String [ ] args ) { new Foo ( ) .doIt ( `` '' ) ; } } VarArgsError.java:14 : doIt ( java.lang.Str... | Should Overload Resolution Select Private Methods ? |
Java | I wanted to create an enum where each constant has a Map associated with it . I accomplished this by giving each constant an instance initializer , like so : I found that if mMap is private , it can not be referenced in the instance initializer . The error is Can not make a static reference to the non-static field mMap... | import java.util.HashMap ; import java.util.Map ; public enum Derp { FOO { { mMap.put ( `` bar '' , 1 ) ; } } ; // can not be private protected final Map < String , Integer > mMap = new HashMap < > ( ) ; } | Why does this enum compile ? |
Java | Possible Duplicate : Why is there no Constant keyword in Java ? I recently started developing in Java and I was wondering why the keyword const was n't implemented and you had to use a rather long constant definition in a class : Instead of the expected wayIs there anyone who can point me out why you have to use ( or h... | protected static final String VALIDATION_ERROR = `` validationError '' ; const VALIDATION_ERROR = `` validationError '' | Usage of the Java keyword const |
Java | I 'm attempting to add markers to a map from a GeoJSON File that has been added to the `` asset '' folder.I 've attempted to follow the documentation however have been unable to get the expected result since the markers are no where to be found when running the app.My Attempt : I have noticed that SymbolLayer expects a... | public void onMapReady ( @ NonNull final MapboxMap mapboxMap ) { this.mapboxMap = mapboxMap ; mapboxMap.setStyle ( Style.MAPBOX_STREETS , new Style.OnStyleLoaded ( ) { @ Override public void onStyleLoaded ( @ NonNull Style style ) { enableLocationComponent ( style ) ; GeoJsonSource source = null ; try { source = new Ge... | Adding and displaying data from a locally stored GeoJSON file using MapBox |
Java | I 'm writing a backend application in Kotlin.To speed things up , I 'm currently relying on RxKotlin on the server to do parallel execution of IO tasks such as database calls & API calls . The code usually looks like this.However , since do n't work really work with multiple events ( just singles ) , Rx feels a bit mes... | val singleResult1 = Single.fromCallable { database.get ( ... . ) } .io ( ) val singleResult2 = Single.fromCallable { database.update ( ... . ) } .io ( ) Single.zip ( singleResult1 , singleResult2 ) { result1 : Result1 , result2 : Result2 - > ... . } .flatMap { //other RX calls } .subscribeOn ( Schedulers.io ( ) ) .obse... | Performance of mutlitheading in RX vs Theads vs Executors |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.