lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | It was my understanding that a child cast to the parent type ( as in Super sc = new Child ( ) ; ) would call the parent class 's static methods , and access the parent class 's non-hidden fields , but would make use of the child class 's instance methods . This does not seem to hold true for the case of private instanc... | package whatever ; public class A { public void method1 ( ) { System.out.println ( `` A method1 ( ) . `` ) ; } //using `` final '' here to emphasize that this is a hiding , not an override . private final void method2 ( ) { System.out.println ( `` A private method2 ( ) . `` ) ; } public static void main ( String [ ] ar... | Why do child classes cast to parent type default to parent version of private instance methods , but not of other instance methods ? |
Java | Suppose I have a third party class as follows : Now suppose that I have a factory interface like so : The idea is that I wish to have a MyObjectFactory that builds a MyObject for a fixed Foo - that is , essentially adding in the @ Assisted annotation on the Bar constructor parameter from the outside . Of course , manua... | public class MyObject { @ Inject public MyObject ( Foo foo , Bar bar ) { ... } } public interface MyObjectFactory { public MyObject build ( Bar bar ) ; } public class MyObjectFactoryImpl implements MyObjectFactory { @ Inject private Provider < Foo > foo ; @ Override public MyObject build ( Bar bar ) { return new MyObje... | How can I make a non-assisted dependency assisted ? |
Java | Is it better to use the variable ' i ' or a meaningful name such as 'loopCount ' or 'studentsCount ' etc ? e.g.VSBy better ; the main considerations would be readability / conventions.Related question Loop iterator naming convention EDIT : I have tagged this a java , but answers for other languages are welcome . | for ( int i = 0 ; i < 10 ; i++ ) { for ( int j = 0 ; j < 5 ; j++ ) { System.out.println ( i + j ) ; } // End of j loop } // End of i loop for ( int outerLoop = 0 ; outerLoop < 10 ; outerLoop++ ) { for ( int innerLoop = 0 ; innerLoop < 5 ; innerLoop++ ) { System.out.println ( outerLoop + innerLoop ) ; } // End of innerL... | Looping : i vs loopCount |
Java | I am iterating over two collections and check if both collections containthe same elements . I ca n't use Java 8.edit 1 year after : I created the method in the question to check if two Collections contain the same elements , without thinking about the fact that I am passing two Collection implementations into the meth... | public static < T extends Comparable < T > > boolean isSame ( @ Nullable Collection < T > a , @ Nullable Collection < T > b ) { if ( a == null || b == null ) { return ( a == null & & b == null ) ; } if ( a.size ( ) ! = b.size ( ) ) { return false ; } Iterator < T > aIt = a.iterator ( ) ; Iterator < T > bIt = b.iterator... | Check two arguments for null in an elegant way |
Java | I was just playing around with JShell , and it seems that defining class Z { } and then definingvar z = new Z ( ) does not work . But using different class names , like class X and class A , does work.Surely I must be missing something obvious ... ? | | Welcome to JShell -- Version 14.0.1| For an introduction type : /help introjshell > class X { } | created class Xjshell > class Z { } | created class Zjshell > var x = new X ( ) x == > X @ 26a1ab54| created variable x : Xjshell > var z = new Z ( ) | Error : | unexpected type| required : class| found : type parameter ... | JShell error `` unexpected type '' when using specific class name |
Java | What I would like to do is when a wolf is caught in the constructor the value for foodis changed automatically to something else . I did try using getter-setters , however , I get the error of unreachable code.What do I do ? | public class AnimalException extends Exception { public AnimalException ( String error ) { super ( error ) ; } } public class Zoo { private String animal ; private String food ; public Zoo ( String animal , String food ) throws AnimalException { this.animal = animal ; if ( findWord ( animal , `` wolf '' ) ) { throw new... | Catching exception in constructor |
Java | I have the following code in Eclipse ( Helios ) /STS which runs and prints console output when doing a Run As > Java Application , in spite of obvious compilation issuesCan anyone pinpoint the reasoning behind this Eclipse functioning.Note : Doing a javac externally obviously fails to compile . | public interface ITest { String func ( ) ; } public static class Test implements ITest { void printFunc ( ) { System.out.println ( `` Inside Test Function '' ) ; } } public static void main ( String [ ] args ) { Test test = new Test ( ) ; test.printFunc ( ) ; } | Interface binding in Eclipse |
Java | I have a HashMap of Products . Each Product has a Price . I know how to find the Product with the max Price . But using Java 8 Streams is really puzzling me . I tried this but no luck : | public Product getMostExpensiveProduct ( HashMap < Integer , Product > items ) { Product maxPriceProduct = items.entrySet ( ) .stream ( ) .reduce ( ( Product a , Product b ) - > a.getPrice ( ) < b.getPrice ( ) ? b : a ) ; return maxPriceProduct ; } | Using Java 8 Streams , how to find the max for a given element in a HashMap |
Java | My problem can be summed-up by this snippet : My class A uses an instance of TheClass with its generics type unknown . It features a method with a target passed as Object since the TheClass instance can be parameterized with any class . However , the compiler wo n't allow me to pass the target like this , which is norm... | public interface TheClass < T > { public void theMethod ( T obj ) ; } public class A { private TheClass < ? > instance ; public A ( TheClass < ? > instance ) { this.instance = instance ; } public void doWork ( Object target ) { instance.theMethod ( target ) ; // Wo n't compile ! // However , I know that the target can ... | Generics and casting to the right type |
Java | It is detail , but I want to know why this happens.Exemplary code : Output o the program : Why on the output there is no interface word before java.lang.Comparable < E > . It is interface , yes ? In my opinion output should be : Comparable is specially treated ? | Class klasa = Enum.class ; for ( Type t : klasa.getGenericInterfaces ( ) ) System.out.println ( t ) ; java.lang.Comparable < E > interface java.io.Serializable **interface** java.lang.Comparable < E > interface java.io.Serializable | No interface word before interface Comparable |
Java | This is my very first question down here , so i 'll try to make it clear as far as i can . Other error : type mismatch ; questions here are not related to this error.I have this odd problem with scala/java inter-operability : Let 's suppose we have a Java classAnd then i have another Scala class i just wanted to wrap t... | public class JavaClass { public static < T > T [ ] toArray ( Class < T > t , Collection < T > coll ) { return null ; // return null to make it simple } } object ScalaClass { def toArray [ T ] ( t : java.lang.Class [ T ] , coll : java.util.Collection [ T ] ) : Array [ T ] = { JavaClass.toArray [ T ] ( t , coll ) ; } } e... | Calling Java Generic Typed Method from Scala gives a Type mismatch error : Scala |
Java | I 've tried to migrate a google cloud project using JDO from endpoints v1 to v2 . I 've followed the migration guide and some solutions here to try to make the datanucleous plugin enhance my classes , and upload them to the google cloud , but there is no luck . I 'm gon na post the build.gradle followed by the server e... | buildscript { repositories { mavenCentral ( ) mavenLocal ( ) } dependencies { // App Engine Gradle plugin classpath 'com.google.cloud.tools : appengine-gradle-plugin:1.3.3 ' // Endpoints Frameworks Gradle plugin classpath 'com.google.cloud.tools : endpoints-framework-gradle-plugin:1.0.2 ' } } repositories { mavenCentra... | Migrated JDO project to google cloud endpoints v2 , server returns NoClassDefFoundError |
Java | I want to make a part of a JFrame transparent . It should look similar like OneNote Screen Clipper . I basically have a fullscreen overlay of a partially transparent JFrame and then inside this JFrame I want to make some rectangles by dragging the mouse and make those rectangles fully transparent , like so : How would ... | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -| partially transparent || || -- -- -- -- -- - || | fully | || | transp . | || -- -- -- -- -- - | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- public class Overlay extends JFrame implements MouseMotionListener , MouseListener { private Rectangle2D... | JFrame - only a part transparent |
Java | Hi ! I 've created a hash map which contains product informations in a supermarket . However , I ca n't display my key values ( which is an array ) correctly . It shows me irrelevant things except product 's name . How can I correct this ? | import java.util.HashMap ; import java.util.Iterator ; import java.util.Map ; import java.util.Scanner ; import java.util.Set ; public class mainClass { static Scanner keyboard = new Scanner ( System.in ) ; static HashMap < Integer [ ] , String > hMap ; public static void createAHashMap ( ) { System.out.print ( `` Expr... | Displaying trouble in hash map |
Java | Why prints 5000 msbut prints 44 msSecond solution 115 time faster | long t = System.currentTimeMillis ( ) ; int size = 3333333 ; int [ ] [ ] [ ] arr = new int [ size ] [ 6 ] [ 2 ] ; // int [ ] [ ] [ ] arr= new int [ 2 ] [ 6 ] [ size ] ; pr ( System.currentTimeMillis ( ) - t ) ; long t = System.currentTimeMillis ( ) ; int size = 3333333 ; // int [ ] [ ] [ ] arr = new int [ size ] [ 6 ] ... | Why does time for initialize array different |
Java | Here is some sample code ( assuming Java 8 ) . Is s effectively final inside the loop ? | while ( true ) { Socket s = serverSocket.accept ( ) ; // some code here ... we do n't assign anything to s again here ... } | Is this `` s '' effectively final ? |
Java | I have a java code snippet below : Output is : What exactly is happening in line 3 ? | int arr [ ] = new int [ 5 ] ; int index = 0 ; arr [ index ] = index = 3 ; System.out.println ( `` arr [ 0 ] = `` + arr [ 0 ] ) ; System.out.println ( `` arr [ 3 ] = `` + arr [ 3 ] ) ; arr [ 0 ] = 3arr [ 3 ] = 0 | Assigning multiple values to an array in same statement |
Java | I have been testing problem with too slow DataInputStream.readByte ( ) method working , and found interesting , but incomprehensible issue . I 'm using jdk1.7.0_40 , Windows 7 64 bit.Consider we have some huge byte-array and reading data from it . And let 's compare 4 methods for reading byte-by-byte from this array : ... | @ Testpublic void testBytes1 ( ) throws IOException { byte [ ] bytes = new byte [ 1_000_000_000 ] ; Random r = new Random ( ) ; for ( int i = 0 ; i < bytes.length ; i++ ) bytes [ i ] = ( byte ) r.nextInt ( ) ; do { System.out.println ( ) ; bytes [ r.nextInt ( 1_000_000_000 ) ] = ( byte ) r.nextInt ( ) ; testLoop ( byte... | Strange method invocation optimization issue |
Java | You can not create arrays of parameterized types , so this code in EclipseCa n't be parameterized , but Eclipse shows a warning Type safety : The expression of type ArrayList [ ] needs unchecked conversion to conform to ArrayList < Integer > [ ] And also shows suggestion Infer Generic Type Arguments which does nothing ... | ArrayList < Integer > [ ] list = new ArrayList [ 1 ] ; | Eclipse - why infer generic suggested for Java 's array |
Java | While trying to understand the differences between Phaser and CyclicBarrier I have come across some links Difference between Phaser and CyclicBarrier and https : //www.infoq.com/news/2008/07/phasers/ I read that the Phaser is compatible with Fork/Join interface while CyclicBarrier is not , here is a code to demonstrate... | public static void main ( String [ ] args ) throws InterruptedException { CountDownLatch countDownLatch = new CountDownLatch ( 1 ) ; Phaser phaser = new Phaser ( 16 ) { @ Override protected boolean onAdvance ( int phase , int registeredParties ) { return phase ==1 || super.onAdvance ( phase , registeredParties ) ; } } ... | Phaser Vs CyclicBarrier in the context of Fork/Join |
Java | I have the following maps : The following code returns these maps : The method getExecutionCount ( ) returns a single map . For the example I have given above , I have four chroms where each chrom will returns a single map.I would like to sum the values of each key seperately so that the final result will be : Is it po... | { 21=0 , 22=2 , 11=0 , 12=0 } { 21=3 , 22=0 , 11=6 , 12=3 } { 21=6 , 22=0 , 11=7 , 12=0 } { 21=5 , 22=7 , 11=9 , 12=1 } for ( Chrom t : obj.getChroms ) { Map < Integer , Integer > result = t.getExecutionCount ( ) ; } 21 = 1422 = 911 = 2212 = 4 | Summing map values per each key |
Java | How can i write below code using lambda expression in java8 . I am new to Java 8 . I have tried the below code as yet as per the suggestion . Is there any other thing which we can improve in this code to write it using lambdas more . | for ( GlobalPricingRequest globalPricingRequest : globalPricingRequests ) { BigDecimal feePerTrans = globalPricingRequest.getFeePerTransact ( ) ; if ( feePerTrans ! = null & & feePerTrans.intValue ( ) < 0 ) { throw ExceptionHelper.badRequest ( `` Fee Per Transaction ca n't be less than zero '' ) ; } List < EventTypePri... | Convert looping into lambda and throw exception |
Java | A downloaded dependency , e.g . log4j is cached in the Gradle user home directory like ~/.gradle/caches/modules-2/files-2.1/org.apache.logging.log4j/log4j.But why modules-2 and files-2.1 instead of modules and files ? It does n't look like the version of Gradle . For instance , there is no `` 6 '' or `` 6.0 '' while I ... | ~/.gradle/caches/jars-1~/.gradle/caches/jars-2~/.gradle/caches/jars-3~/.gradle/caches/modules-2~/.gradle/caches/modules-2/files-2.1~/.gradle/caches/transforms-1~/.gradle/caches/transforms-2 | Why are there numbers in Gradle cache directories ? |
Java | Actual java code is : But when I look into class file it 's : All || and & & interchanged.Can anyone explain why ? | ( ( rrd == null || ! rrd ) & & null ! = dam & & null ! = dam.getac ( ) & & null ! = dam.getac ( ) .getc ( ) & & null ! = sname & & sname.equalsIgnoreCase ( dam.getac ( ) .getc ( ) ) ) ( ( rrd ! = null ) & & ( rrd.booleanValue ( ) ) ) || ( ( ( ( null == dam ) || ( null == dam.getac ( ) ) || ( null == dam.getac ( ) .getc... | why java revert logical operators while compile |
Java | I 'm facing the following problem in my project with Java generics type inference . This is a code sample that 's similar to my original one : This code breaks at new Implementer < String > , but works if I use new Builder < String , String > instead of new Builder < > .Why ca n't Java infer that the type of the Builde... | public class BuildableObject < R , S > { public static class OneParameter < R > { } public static class TwoParameters < R , S > { } interface TwoParamInterface < R , S > { } public static class Implementer < T > implements TwoParamInterface < T , T > { } private final OneParameter < R > first ; private final OneParamet... | Generic type inference limits in Java |
Java | Let me say there is an abstract class which looks likeWithin following Child classWhich one is preferable ? newInstance1 or newInstancw2 ? | abstract class Parent < V > { protected static < T extends Parent < V > , V > T newInstance ( final Class < T > type , final V value ) { // ... } } class Child extends Parent < XXX > { public static Child newInstance1 ( final XXX value ) { // ... } public static Parent < XXX > newInstance2 ( final XXX value ) { // ... ... | generic factory method convention |
Java | While playing with jmh I came across a weird thing I can not explain.The results are belowI am running on JDK 1.8.0_101 , VM 25.101-b13 , Intel ( R ) Core ( TM ) i7-4770 CPU @ 3.40GHz ( family : 0x6 , model : 0x3c , stepping : 0x3 ) If I set the const equal to the value or if I set the value to 0xffffffff , nothing cha... | @ BenchmarkMode ( Mode.SingleShotTime ) @ Measurement ( iterations = 10 , batchSize = Integer.MAX_VALUE ) @ Warmup ( iterations = 5 , batchSize = Integer.MAX_VALUE ) @ State ( Scope.Thread ) public class Tests { private int value ; @ Setup ( Level.Iteration ) public void setUp ( ) { value = 1230 ; } @ Benchmark public ... | Why ( n mod const ) is faster than ( const mod n ) ? |
Java | I have this non-static inner class that causes memory leaks , because it holds an implicit reference to the enclosing class : In order to stop it from leaking , I need to make it static : It is impossible to make updateCalendar ( ) static because in it I access other non-static variables and it becomes a mess . What do... | private class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { @ Override public void onScheduleUpdatedEvent ( ) throws RemoteException { updateCalendar ( ) ; } } private static class CalendarScheduleUpdatedEventListener extends ScheduleUpdatedEventListener.Stub { @ Override public void ... | Workaround to accessing non-static member method from a static inner class |
Java | I am new to multithreading , and I came across this example : This causes the following sample output : i.e , there is a deadlock . However , if we change the order of locks obtained in the second thread so that it looks like this now : It works as expected , and a sample output looks like this : Can someone explain to... | public class TestThread { public static Object Lock1 = new Object ( ) ; public static Object Lock2 = new Object ( ) ; public static void main ( String args [ ] ) { ThreadDemo1 T1 = new ThreadDemo1 ( ) ; ThreadDemo2 T2 = new ThreadDemo2 ( ) ; T1.start ( ) ; T2.start ( ) ; } private static class ThreadDemo1 extends Threa... | Understanding why deadlock happens in this implementation |
Java | I am working on detecting sentences which start and end with hashtags . As of now , I only have code to find words , which is part of this mechanism . How can I find sentences depending upon case below.Case 1 : In this case , I want to detect how are you . Now if there is only a word , then the above case is to be igno... | Hello , # how are you # today . Hello , # how are you # today . @ Overridepublic List < String > findHashTags ( String text ) { if ( text == null ) { return new ArrayList < > ( ) ; } String [ ] tagSet = text.split ( `` `` ) ; Set < String > sortedTags = new HashSet < > ( ) ; List < String > processedTags = new ArrayLis... | Find sentences begining and ending with hash |
Java | Why does List [ scala.Int ] type erase to List [ Object ] whilst Integer in List [ java.lang.Integer ] seemsto be preserved ? For example , javap for outputswhere we see Integer was preserved in second case . The docs state Replace all type parameters in generic types with their bounds or Object if the type parameters ... | object Foo { def fooInt : List [ scala.Int ] = ? ? ? def fooInteger : List [ java.lang.Integer ] = ? ? ? } public scala.collection.immutable.List < java.lang.Object > fooInt ( ) ; public scala.collection.immutable.List < java.lang.Integer > fooInteger ( ) ; | Difference in type erasure of List [ Int ] and List [ Integer ] |
Java | The code belowOutputs below in java 1.7xOutputs below in Java 1.6xIs there a reason for this behavior ? Also if I change It behaves exactly same in 1.6x and 1.7x | public class Test16Jit { public static void main ( String [ ] s ) { int max = Integer.MAX_VALUE ; int i = 0 ; long li = 0 ; while ( i > = 0 ) { i++ ; li++ ; if ( i > max ) { System.out.println ( `` i is : `` + i ) ; System.out.println ( `` max is : `` + max ) ; System.out.println ( `` Woo ! ! something really went wron... | Why is it that the code below behaves differently in Java 1.6 and 1.7 |
Java | I 've recently been reviewing code an noticed the use of this syntax in a for loopas opposed to : With the reasoning that it is more efficient as you do n't have to keep looking up the myArray.length property with each loop.I created a test to check if this was the case , and in all my tests the first for loop approach... | for ( int i = 0 , len = myArray.length ; i < len ; i++ ) { //some code } for ( int i = 0 ; i < myArray.length ; i++ ) { //some code } | Declaring a variable in a for loop for the array length |
Java | Overloading overridden method in subclass , am I overloading parent method or sub-classes method ? I understand generally what overloading and overriding is.Overloading - same method different parameters and maybe return type in the same class.Overriding - in subclass same method signature as in parent but different im... | class A { public void a ( ) { System.out.println ( `` A.a '' ) ; } } class B extends A { public void a ( ) { super.a ( ) ; System.out.println ( `` B.a '' ) ; } public void a ( int x ) { } } | Overloading overridden method am I overloading parent or sub-class method |
Java | We have a Map < String , Student > studentMap , where Student is a class as follows : We need to return a list of all Ids eligibleStudents , where the age > 20.Why does the following give a compilation error at the Collectors.toList : | class Student { String name ; int age ; } HashMap < String , Student > studentMap = getStudentMap ( ) ; eligibleStudents = studentMap .entrySet ( ) .stream ( ) .filter ( a - > a.getValue ( ) .getAge ( ) > 20 ) .collect ( Collectors.toList ( Entry : :getKey ) ) ; | Filter map and return list of keys |
Java | I have just created a simple java program by using datatype short.The program looks like this : This program throws an error : How compiler founds int ? There is no int variable in this program all variable are declared as short . | class test { public static void main ( String arg [ ] ) { short x=1 ; short x_square=x*x ; } } java:6 : possible loss of precisionfound : intrequired : short | unexpected behavior in types |
Java | This is what I 've written so far . The problem I encounter is that i is 0 at the first iteration making i % 6=0 as well and making it so that row 1 consists of arr [ 0 ] [ 0 ] only and each next row ends with the actual first of the next one.I have a feeling the solution must be easy but I have n't found one for the p... | int [ ] [ ] arr = { { 11 , 12 , 13 , 14 , 15 , 16 } , { 21 , 22 , 23 , 24 , 25 , 26 } , { 31 , 32 , 33 , 34 , 35 , 36 } , { 41 , 42 , 43 , 44 , 45 , 46 } , { 51 , 52 , 53 , 54 , 55 , 56 } , { 61 , 62 , 63 , 64 , 65 , 66 } } ; int sum = 0 ; int rowsSum = 0 ; int rowIndex = 0 ; for ( int i = 0 ; i < arr.length * arr.leng... | Finding sum of rows of 2D array , using 1 loop in java |
Java | ans is If i am creating object of Child class then why output is of parent class method ? ? even method1 is private in parent.It shakes my all inheritence concept . | class Parent { private void method1 ( ) { System.out.println ( `` Parent 's method1 ( ) '' ) ; } public void method2 ( ) { System.out.println ( `` Parent 's method2 ( ) '' ) ; method1 ( ) ; } } class Child extends Parent { public void method1 ( ) { System.out.println ( `` Child 's method1 ( ) '' ) ; } public static voi... | Why Inheritance output is unexpected |
Java | Clojure offers a good Java interop . However , I really want to have this : I guess that is what called a DSL and in Lisp world it is done via Macros . I 'm not sure how/where to start . refiy and extends forms are definitely have important role here but I do n't know how that would fit into Macros . How start doing th... | ( servlet IndexServlet ( service [ parmas ] ... . ) ( do-post [ params ] ... . ) ( do-get [ params ] ... . ) ) ( servlet-filter SecurityFilter ( do-filter [ params ] ... . ) ) | Starting points to morph regular Servlets coding to my DSL |
Java | I am trying to create a property page using plugin.xml . I want this property page to appear only when you right click - > properties of folders only.I used this code : This works when I open the properties from Navigator . But when opening it from Project Explorer , I ca n't see the properties page ! From Navigator : ... | < extension point= '' org.eclipse.ui.propertyPages '' > < page class= '' my.properties.page.class '' id= '' my.properties.page.id '' name= '' My Properties Page '' > < enabledWhen > < instanceof value= '' org.eclipse.core.resources.IFolder '' / > < /enabledWhen > < /page > < /extension > | Eclipse RCP- Property Page for folders only |
Java | I 'm using ColdFusion 11 and Java ( com.lowagie.text.pdf.PdfStamper ) to fill in pdf but when I enter a value with a single apostrophe such as 32 ' it only saves in the pdf as 32 instead of 32 ' . The value is going into a multi-line text area in the PDF . I 've tried with and without rich-text enabled . I 've tried re... | this.pdfFile = this.pdfService.read ( source=infile ) ; this.pdfReader = createObject ( `` java '' , '' com.lowagie.text.pdf.PdfReader '' ) .init ( tobinary ( this.pdffile ) ) ; this.pdfWriter = createObject ( `` java '' , `` java.io.FileOutputStream '' ) .init ( CreateObject ( `` java '' , `` java.io.File '' ) .init (... | Missing single quote when using PDFStamper |
Java | I have a collection of objects of Class AI have to populate the largestTimestamp field for each object ( the largest `` timestamp '' value in the group of objects with the same code ) . I can do this in two steps as follows - Is there a way to combine these into a single stream chain ? | class A { String code ; long timestamp ; long largestTimestamp ; } Map < String , Long > largestTimestampMap = list.stream ( ) .collect ( Collectors.toMap ( A : :getCode , A : :getTimestamp , Long : :max ) ) ; list.forEach ( a - > a.setLargestTimestamp ( largestTimestampMap.get ( a.getCode ( ) ) ) ) ; | Java 8 streams - modifying all elements in a group |
Java | I 've run some simple experiments like this : and get output like this : But I wonder if anything is done to an exception when it is thrown . This is a primarily academic question , though it could be relevant under certain circumstances if an exception were part of an API and may or may not have been thrown when provi... | public static void main ( String [ ] args ) { try { NullPointerException n = new NullPointerException ( ) ; System.out.println ( Lists.newArrayList ( n.getStackTrace ( ) ) ) ; n.printStackTrace ( ) ; System.out.println ( Lists.newArrayList ( n.getStackTrace ( ) ) ) ; throw n ; } catch ( NullPointerException e ) { e.pri... | Does throwing an exception change its state ? |
Java | I have to execute this line of cose several million times , I wonder if there is a way to optimize it ( maybe precomputing something ? ) .a.contains ( b ) || b.contains ( a ) Thank youedit : the code executed by the contains method already checks for a.length < b.length . | public static int indexOf ( byte [ ] value , int valueCount , byte [ ] str , int strCount , int fromIndex ) { byte first = str [ 0 ] ; int max = ( valueCount - strCount ) ; for ( int i = fromIndex ; i < = max ; i++ ) { [ ... ] } return -1 ; } | Is there a more efficient way to assess containment of strings ? |
Java | I get `` Type mismatch : can not convert from List < CherryCoke > to List < Coke < ? > > '' It looks like a 'list of cherry cokes ' is not a 'list of cokes ' . This is counterintuitive.How can I create that 'xs ' anyway , if it has to be a List < Coke < ? > > and I have to have a subclass of Coke < Cherry > ? | class Taste { } class Cherry extends Taste { } abstract class Coke < T extends Taste > { } class CherryCoke extends Coke < Cherry > { } class x { void drink ( ) { List < Coke < ? > > xs = Arrays.asList ( new CherryCoke ( ) ) ; } } | Is a 'list of cherry cokes ' a 'list of cokes ' ? |
Java | Let 's say I have a classA , that has its own methods with its own private fields and what have you ( bascically adhere to encapsulation standards ) . Then I have classB , that needs for its execution the final state ( that is obtained through one of the methods of classA , which somewhat breaks the encapsulation ) of ... | classA a = new classA ; ... //classA does its stuffclassB b = new classB ( a.getFinalState ( ) ) ; ... // again class does its stuff based on outcome of AclassC c = new classC ( b.getFinalState ( ) ) ; | Too high coupling or okay to design like this ? |
Java | I have a parent class - ProductAnd 3 sub-classes which extends it : public class Vinyl extends Product { } public class Book extends Product { } public class Video extends Product { } All sub-classes override the preview ( ) method with their specific implementation.Now , I have a new design demand : I need to define a... | public abstract class Product { } | How to propely design a combination of many sub-classes ? |
Java | Recently I am working on a android project . I am parsing data from wordpress api . But detail post content are in html formet . I have to remove html tags . Using Html.fromHtml ( ) .toString ( ) java method I deleted all tags . But there are some image caption which I have to delete . For delete the caption I have to ... | < p class= '' wp-caption-text '' > android m marshmallow < / yourHtml = yourHtml.replaceAll ( `` Your_Regular_Expression '' , '' '' ) ; yourHtml = Html.fromHtml ( yourHtml ) .toString ( ) ; | How to delete specific html class with content using Java Html Class |
Java | When looking into the source code of IntelliJ IDEA Community Edition project in github , in one of the files I found the following notation : What does this < selection > annotation mean ? By which tool is it being processed ? The complete source of afterEnumConstantWithArgs.java is as follows . | void m ( ) { < selection > < caret > System.out.println ( `` '' ) ; < /selection > } // `` Use existing implementation of 'm ' '' `` true '' enum I { A ( `` a '' ) { void m ( ) { < selection > < caret > System.out.println ( `` '' ) ; < /selection > } } , B ( `` b '' ) { public void m ( ) { System.out.println ( `` '' ) ... | What does this annotation in Intellij source code mean ? |
Java | Below is the source code snippet of String.hashCode ( ) method from Java 8 ( 1.8.0_131 to be precise ) You can see that , the documentation says , that hashCode ( ) is computed using below formulawhile the actual implementation is differentAm I missing any obvious thing ? Please help me . | /** * Returns a hash code for this string . The hash code for a * { @ code String } object is computed as * < blockquote > < pre > * s [ 0 ] *31^ ( n-1 ) + s [ 1 ] *31^ ( n-2 ) + ... + s [ n-1 ] * < /pre > < /blockquote > * using { @ code int } arithmetic , where { @ code s [ i ] } is the * < i > i < /i > th character ... | String hashCode ( ) documentation vs implementation |
Java | I have a MyModel class and a List < MyModel > and i want to produce , with a MyModel will map with 1 or 2 Integer value ( left , right or both ) I can do with 1 but do n't know how to do with 2This is how I am currently doing : | public static class MyModel { private int left ; private int right ; private int state = 0 ; public MyModel ( int left , int right , int state ) { this.left = left ; this.right = right ; this.state = state ; } public int getLeft ( ) { return left ; } public void setLeft ( int left ) { this.left = left ; } public int ge... | How to map more than 1-1 record in java stream ? |
Java | I am trying to create an application in Java which allows for generation of large Provenance graphs from small seed graphs but I am having a little trouble figuring out the best way to design my classes.To begin with , Provenance essentially has a graph structure , nodes and edges . I have created a Java library which ... | class WeighableAgent extends Agent implements Weighable class WeighableNode implements Weighable { private Node node ; public WeighableNode ( Node node ) { this.node = node ; } etc etc ... Node getNode ( ) ; presentationNode.getWeighableNode ( ) .getNode ( ) instanceof Agent instanceof WeighableAgent | Unsure how approach design of application |
Java | Trying to get the Big O of this coding . Struggling to understand how the loops interact . When I run it , I get n = 25 count = 898960 . I 've tried O ( n ) ^5+9 all the way to O ( n ) ^5/nAll other examples of this problem do n't deal with I is used in the second loop ( I*I ) and j is used in the third loop | count++ ; count++ ; count++ ; for ( int i = 0 ; i < n ; i++ ) { for ( int j = 0 ; j < i*i ; j++ ) { for ( int k = 0 ; k < j ; k++ ) { count++ ; sum++ ; } } } count++ ; return count ; } | Big O for multi loops |
Java | I am using Java . I have the following text : Why ( hy ) ( ? ! [ a-z ] ) returns two `` hy '' s. The idea is to match any `` hy '' that is not followed by any character between a-z.If I do hy ( ? ! [ a-z ] ) ( hy without parentheses ) it works ( finds only the second `` hy '' ) but I do n't understand why if I use pare... | `` hyst and hy '' | Should capturing parentheses affect a separate negative lookahead ? |
Java | When I write setters for instance methods , I use this to disambiguate between the instance variable and the parameter : So , what do I do when value is a class variable ( static ) instead of a member of an instance ? | public void setValue ( int value ) { this.value = value ; } private static int value = 7 ; public static void setValue ( int value ) { value = value ; // compile fails ; ambiguous } | What name do you use for the parameter in a static variable setter method ? |
Java | I have two object . The first one : The second one : I have a Map < Object1 , Object2 > : I want to group this map with the same a in a list of Object2 like : I try something like this : | public final class Object1 { private String a ; private String b ; // constructor getter and setter } public class Object2 { private BigDecimal value1 ; private BigDecimal value2 ; // constructor getter and setter } Object1 { a= '' 15 '' , b= '' XXX '' } , Object2 { value1=12.1 , value2=32.3 } Object1 { a= '' 15 '' , b... | Java 8 collect to Map < String , List < Object > > |
Java | I 'm completely new to Java 8 and I 'm trying to wrap my head around why the last test is false.Output : test1 - true : true test1 - false : true test2 - true : true test2 - false : false | @ Testpublic void predicateTest ( ) { Predicate < Boolean > test1 = p - > 1 == 1 ; Predicate < Boolean > test2 = p - > p == ( 1==1 ) ; System.out.println ( `` test1 - true : `` +test1.test ( true ) ) ; System.out.println ( `` test1 - false : `` +test1.test ( false ) ) ; System.out.println ( `` test2 - true : `` +test2.... | Understanding lambdas and/or predicates |
Java | I 'm browsing through the Android source , just kind of reading it , and I 've come across a strange chunk of code in Android.Util.JsonReader . It is as follows : What is this doing exactly ? That is , the scope immediately following the new assignment ? If I understand correctly , whenever this class , JsonReader is i... | private final List < JsonScope > stack = new ArrayList < JsonScope > ( ) ; { push ( JsonScope.EMPTY_DOCUMENT ) ; } | Peculiar Java Scope |
Java | Suppose I have a long set of of parameters all of the same type for some method . I have a similar operation to do on each parameter ( if they are not null ) . Assume I have no control over the method signature since the class implements an interface . For example.. something simple like this . Set of String params..Is... | public void methodName ( String param1 , String param2 , String param3 , String param4 ) { //Only print parameters which are not null : if ( param1 ! =null ) out.print ( param1 ) ; if ( param2 ! =null ) out.print ( param2 ) ; if ( param3 ! =null ) out.print ( param3 ) ; if ( param4 ! =null ) out.print ( param4 ) ; } | Good way to null check a long list of parameters |
Java | I found a bit of generic code and it has stumped me as to how it actually works.I do n't understand where it gets the generic type that is used for T.This is an oversimplified example but I still do n't understand how this is valid Java code . | public static void main ( String [ ] args ) { System.out.print ( get ( ) ) ; } public static < T > T get ( ) { return ( T ) getObj ( ) ; } public static Object getObj ( ) { return Boolean.FALSE ; } | Where does this Java function infer its generic type from ? |
Java | I 'm building a Spring backend . I 've got a controller which gets a `` search object '' - an object with like 10 fields which only one of them should be filled , so the search function ( which I did not write but need to make changes to and refactor ) is written like this : Notice the 2 special cases in the end- one o... | if ( param1 ! = null ) user = getUserByParam1 ( param1 ) ; else if ( param2 ! = null ) user = getUserByParam2 ( param2 ) ; ... else if ( lastName ! = null || lastName ! = null ) user = getUserByName ( firstName , lastName ) ; else user = getUserById ( id ) ; if ( user == null ) throw costumException ; return user ; | Java semantics - Is there a way to write this better ? |
Java | I 'm trying to understand the following Java exercise . Even running the debugger I do n't understand the details of the second and third printout:1 , 2 , 3 , 41 , 2 , 4 , 41 , 2 , 4 , 8I understand that the first print is the array as it is , second line prints [ 2 ] element of the array and third line [ 3 ] element .... | public class TR1 { public static void main ( String [ ] args ) { int [ ] v = { 1 , 2 , 3 , 4 } ; print ( v ) ; x ( v , v [ 2 ] - 1 ) ; print ( v ) ; x ( v , v [ 3 ] - 1 ) ; print ( v ) ; } public static void x ( int array [ ] , int y ) { array [ y ] = array [ y - 1 ] * 2 ; } public static void print ( int array [ ] ) {... | print out for java exercise explanation |
Java | I have created a loop using processing that draws circles , the overall shape should be a circle . However they are mainly drawn close to X and Y axis . I have randomized the angle for the calculus of its location , I can not see where the problem is.Code as follows : | for ( int omega = 0 ; omega < 1080 ; omega++ ) { //loop for circle creation radius = ( int ) random ( 80 ) ; //random radius for each circle int color1= ( int ) random ( 100 ) ; //little variation of color for each circle int color2= ( int ) random ( 100 ) ; int locationY = ( int ) ( sin ( radians ( omega ) ) *random (... | Circles drawn mainly in X an Y axises , WHY ? |
Java | Is there any way to figure out how many pixels wide a certain String in a certain Font is ? In my Activity , there are dynamic Strings put on a Button . Sometimes , the String is too long and it 's divided on two lines , what makes the Button look ugly . However , as I do n't use a sort of a console Font , the single c... | String test = `` someString '' ; if ( someString.length ( ) > /*someValue*/ ) { // decrement Font size } private void setupButton ( ) { Button button = new Button ( ) ; button.setText ( getButtonText ( ) ) ; // getButtonText ( ) is a custom method which returns me a certain String Paint paint = button.getPaint ( ) ; fl... | Figure out width of a String in a certain Font |
Java | On line 3 , it 's a compiler error if we do n't typecast the result to a byte -- that may be because the result of addition is always int and int does not fit into a byte . But apparently we do n't have to typecast on line 6 . Are n't both statements , line 3 and line 6 , equivalent ? If not then what else is different... | byte b1 = 3 ; byte b2 = 0 ; b2 = ( byte ) ( b2 + b1 ) ; // line 3System.out.println ( b2 ) ; b2 = 0 ; b2 += b1 ; // line 6System.out.println ( b2 ) ; | different compiler behavior when adding bytes |
Java | Simple question : Why would this be preferred : over this : or this : ? To me these all look essentially identical , so I 'm not sure what would be the best way to synchronize access to static fields , or why one would be better than another , but I 've heard the first is often preferred . | public class Foo { final private static Object foo = new Object ( ) ; public static void doSomething ( ) { synchronized ( Foo.foo ) { //code } } } public class Foo { public static void doSomething ( ) { synchronized ( Foo.class ) { //code } } } public class Foo { public synchronized static void doSomething ( ) { //code... | Synchronization : Why is it preferred to lock a private final static object instead of the class 's class object ? |
Java | If you add a Key Binding in java with a mask - let 's just say the ActionEvent.ALT_MASK with KeyEvent.VK_A - and then you perform that key ( ALT + A ) BUT , you release the alt key just before the ' A ' key , you will usually encounter a problem where the actionPerformed ( ) in a class ( implementing ActionListener ) w... | public ConwayPanel ( ) { super ( ) ; setBackground ( new Color ( 245 , 255 , 245 , 255 ) ) ; // BG slightly green - all ready paused = true ; // nothing to play ... in FUTURE put cool organism in startX = 0 ; // starting position of the left of the grid startY = 0 ; // starting position of the top of the grid zoom = 15... | KeyBindings stuck on actionPerformed ( ) |
Java | Hello I have been trying to add a String to a String [ ] . Here is what I have , But , I keep getting java.lang.ArrayIndexOutOfBoundsException because it wont let me make any new Strings . I ca n't modify my declaration of ipList [ ] without a lot of modifications , what can I do ? | static String [ ] ipList = { `` 127.0.0.1 '' , `` 173.57.51.111 '' , `` 69.696.69.69 '' } ; @ Overridepublic void actionPerformed ( ActionEvent e ) { String newIpGet = textfield.getText ( ) ; try { for ( int i = 0 ; i < Main.ipList.length ; i++ ) { Main.ipList [ i+1 ] = newIpGet.toString ( ) ; // < -- -- ***** Main.wri... | Java Adding string to a string array |
Java | One often sees the advice that variables should be declared with some interface , not the implementing class . For example : However , say I am using this list for an algorithm that really depended on the O ( 1 ) random access of an ArrayList ( e.g . Fisher-Yates shuffling ) . In that case , the key abstraction that Ar... | List < Integer > list = new ArrayList < > ( ) ; ArrayList < Integer > list = new ArrayList < > ( ) ; | Should variables always be declared with interface in Java ? |
Java | Please consider the following code sample : Is it possible to call someOtherMethod ( ) ? I tried MyEnum.SECOND.someOtherMethod ( ) but the IDE could not resolve it.Thanks in advance ... | public enum MyEnum { FIRST { @ Override public void someMethod ( ) { ... } } , SECOND { @ Override public void someMethod ( ) { ... } public void someOtherMethod ( ) { ... } } ; public abstract void someMethod ( ) ; } | Can enum instances declare their own public methods ? |
Java | I 'm currently investigating in some pathTraversal related security mechanisms and came across a weird behavior of java.io.File.getCanonicalPath ( ) . I thought CanonicalPath will always represent the true unique path of the abstract underlying File . However if the file name consists a of two dots followed by a space ... | File root = new File ( `` c : /git/ '' ) ; String relative = `` .. /.. \\ '' ; File concatFile = new File ( root.getCanonicalPath ( ) , relative ) ; System.out.println ( `` ConcatFileAbsolute : ' '' + concatFile.getAbsolutePath ( ) + `` ' '' ) ; System.out.println ( `` ConcatFileCanonical : ' '' + concatFile.getCanonic... | Java file canonicalPath with tailing '.. ' leads to inconsistent behavior |
Java | How do I add my tests to my production code at test-runtime so that both are in the same Java 9 module and can access each other using reflections ? I have tried so far : Remove the Java 9 modularity ( actually the module-info.java ) → it worked perfectly , but is not what I 'm looking for.Move my tests to a dedicated ... | java \ -- patch-module com.stackoverflow.examplemodule=ModuleInfoTest : ModuleInfoExample \ -- module-path ModuleInfoExample \ -- add-opens com.stackoverflow.examplemodule/com.stackoverflow.examplepackage=com.stackoverflow.examplemodule \ -- add-opens com.stackoverflow.examplemodule/com.stackoverflow.examplepackage=ALL... | Patch Java 9 module with test-code to work with reflections |
Java | I 'm new to java and still learning , so keep that in mind . I 'm trying to write a program where a user can type in a keyword and it 'll convert it to numbers and put it in an array . My problem is the array needs to keep repeating the int's.My code is : Right now if I try to get any key [ i ] higher than the keyword.... | String keyword=inputdata.nextLine ( ) ; int [ ] key = new int [ keyword.length ( ) ] ; for ( int k = 0 ; k < keyword.length ( ) ; ++k ) { if ( keyword.charAt ( k ) > = ' a ' & & keyword.charAt ( k ) < = ' z ' ) { key [ k ] = ( int ) keyword.charAt ( k ) - ( int ) ' a ' ; } } | Repeating Java Array |
Java | I have a use case where I have all the Employee data in a list ( List < Employee > employeesList ) and I would like to get the required employees by providing another list of employee ID 's ( List < String > employeeIdList ) I need the same order of employeeIdList for the employees after retrieval . I am able to achiev... | package com.test ; import java.util.ArrayList ; import java.util.LinkedList ; import java.util.List ; import java.util.stream.Collectors ; /** * The Class SimpleClass . */public class SimpleClass { /** * The main method . * * @ param args the arguments */ public static void main ( String [ ] args ) { Employee employee1... | Need to get the second list ordering when validating the content between 2 different lists by using Java Streams |
Java | We are currently using Java Compiler 11 and deploy our main artifacts to Java 11 . No problem here . Unfortunately , a service we use only supports Java 8 so we compile some of them targetting Java 8 . No problem here.Our issue is that developers might reference methods that are not available at runtime in Java 8 . E.g... | grep -- recursive -- extended-regexp ' [ \ ( ] ( List|Set|Map ) .of ' 'our_project ' | Is there a way to lint incompatible Java API references with PMD , Checkstyle , SpotBugs , etc ? |
Java | Inspired by this question , I started to play with ordered vs unordered streams , parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that do n't respect it.In one answer to the linked question , a code similar to this one is shown : And the lists are indeed differ... | List < Integer > ordered = Arrays.asList ( 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 , 1 , 2 , 3 , 4 , 4 , 3 , 2 , 1 , 1 , 2 , 3 , 4 ) ; List < Integer > result = new CopyOnWriteArrayList < > ( ) ; ordered.parallelStream ( ) .forEach ( result : :add ) ; System.out.println ( ordered ) ; System.out.println ( result ) ; CopyOnWriteAr... | Encounter order friendly/unfriendly terminal operations vs parallel/sequential vs ordered/unordered streams |
Java | I have the following code : getEntries ( ) returns a List < Entry > . How can I add the return statement into this lambda expression ? Something like .map ( User : :getEntries ) ? | public List < Entry > getEntriesForUserId ( int userId ) { User u = DataBaseConnector .getAllUsers ( ) .stream ( ) .filter ( user - > user.getUserId ( ) == userId ) .findFirst ( ) .orElse ( new User ( -1 , `` Error '' ) ; return u.getEntries ( ) ; } | Java Stream API how to improve expression |
Java | I 'm trying to translate one of my Java projects to Python and I 'm having trouble with one certain line . The Java code is : What I think this is supposed to be in python is ... but I am getting an error SyntaxError : invalid syntax.How can I translate this Java to Python ? | if ( ++j == 9 ) return true ; if ( j += 1 ) ==9 : return True | ++i operator in Python |
Java | Imagine finding out if two shapes intersect . An intersection of two shapes may be either another shape , or nothing . If there is no intersects ( Shape ) method in Shape , then , I believe , the proper object-oriented solution would be : In JDK , Optional is a final class , not an interface . To properly solve problem... | public final class ShapesIntersection implements Maybe < Shape > { public ShapesIntersection ( Shape a , Shape b ) { this.a = a ; this.b = b ; } @ Override public boolean isPresent ( ) { // find out if shapes intersect } @ Override public Shape get ( ) { // find the common piece of two shapes } } public inteface Maybe ... | Implementing classes that should behave as Optional |
Java | The code snippet shown below works . However , I 'm not sure why it works . I 'm not quite following the logic of how the lambda function is passing information to the interface . Where is control being passed ? How is the compiler making sense of each n in the loop and each message created ? This code compiles and giv... | import java.util.ArrayList ; import java.util.List ; public class TesterClass { public static void main ( String [ ] args ) { List < String > names = new ArrayList < > ( ) ; names.add ( `` Akira '' ) ; names.add ( `` Jacky '' ) ; names.add ( `` Sarah '' ) ; names.add ( `` Wolf '' ) ; names.forEach ( ( n ) - > { SayHell... | How do lambda calls interact with Interfaces ? |
Java | I have a class PDF which implements an interface fileReader.I notice that there are scope issues for variables fin . Another implementation I made was : But now I could not access fileContent.How can I combine the try-catches so that I do n't have scope problems ? Can there be a better design approach to this problem ?... | import java.io.File ; import java.io.FileInputStream ; import java.io.FileNotFoundException ; import java.io.IOException ; public class PDF implements fileReader { @ Override public byte [ ] readFile ( File pdfDoc ) { if ( ! pdfDoc.exists ( ) ) { System.out.println ( `` Could not find '' + pdfDoc.getName ( ) + `` on th... | Issues in scope of variables while using try-catch in Java |
Java | Java 8 here . I need to search two lists of POJOs for a string and want to use the Stream/Optional APIs correctly.If the name appears in the first list ( `` lunches '' ) then I want to return an optional containing it . Else , if the name appears in the second list ( `` dinners '' ) then I want to return an optional co... | public class Restaurant { private String id ; private String name ; private List < Food > lunches ; private List < Food > dinners ; public Optional < Food > findFoodByName ( String name ) { return Optional.of ( lunches.stream ( ) .filter ( food - > food.getName ( ) .equalsIgnoreCase ( name ) ) .findFirst ( ) ) .orElse ... | Defaulting Optional orElse with Optional.empty in Java 8 |
Java | I was going through java.net package and read this : URLs are `` write-once '' objects . Once you 've created a URL object , you can not change any of its attributes ( protocol , host name , filename , or port number ) .But , if we look into the java.net.URL we will find this : andSo , I know these are protected method... | protected void set ( String protocol , String host , int port , String file , String ref ) protected void set ( String protocol , String host , int port , String authority , String userInfo , String path , String query , String ref ) public static void setURLStreamHandlerFactory ( URLStreamHandlerFactory fac ) | How URLs are write once ? |
Java | Can someone explain me why this construction wont work : and this one works just fine : As for me they are identical , but 1st one wont write data correctly ( will write half of file lenght / data ) . | while ( fileInputStream.available ( ) > 0 ) { fileOutputStream.write ( fileInputStream.read ( ) ) ; } while ( fileInputStream.available ( ) > 0 ) { int data = fileInputStream.read ( ) ; fileOutputStream.write ( data ) ; } | java read / write construction |
Java | I 'm currently brushing up my Java and reading up on Generics . Since they were not treated extensively in my Java class , I 'm still having some trouble wrapping my mind about it , so please keep that in mind when answering.First of all , I 'm pretty sure that what I 'm trying to is not possible . However , I 'd like ... | public interface CalledInterface < E > { public E get ( ) { ... } public set ( E e ) { ... } } public class Called implements CalledInterface < String > { ... } public class Caller { protected CalledInterface < ? > c ; public Caller ( CalledInterface < ? > arg ) { c = arg ; } public void run ( ) { // I can do this : c.... | Can I work with generic types from a calling class ? |
Java | How do I convert a List < Entry > to Map < Entry : :getKey , List < Entry : :getValue > > using streams in Java 8 ? I could n't come up with a good KeySelector for Collectors.toMap ( ) : What I want to get : { ' 1 ' : [ `` a '' , `` c '' ] , ' 2 ' : [ `` b '' ] } . | List < Entry < Integer , String > > list = Arrays.asList ( Entry.newEntry ( 1 , `` a '' ) , Entry.newEntry ( 2 , `` b '' ) , Entry.newEntry ( 1 , `` c '' ) ) ; Map < Integer , List < String > > map = list.stream ( ) .collect ( Collectors.toMap ( e - > e.getKey ( ) , e - > e.getValue ( ) ) ) ; | How do I convert a List < Entry > to Map where value is a list using streams ? |
Java | Is there a more concise , perhaps one liner way , to write the following : Using Java 8 features , and functionally insipred approaches . I 'm not expecting a Haskell solution like : But something more elegant than the traditional imperative style . | ArrayList < Integer > myList = new ArrayList < > ( ) ; for ( int i = 0 ; i < 100 ; i++ ) { myList.add ( i ) ; } ls = [ 1..100 ] | Java 8 Way of Adding in Elements |
Java | I have several enums with a name property and a byName method which is roughly like this for all of them : Since the byName method is duplicated across different enums , I 'd like to factor it out in a single place and avoid duplicated code.However : Enums can not extend an abstract classJava8 interfaces with default m... | public static Condition byName ( String name ) throws NotFoundException { for ( Condition c : values ( ) ) { if ( c.name.equals ( name ) ) { return c ; } } throw new NotFoundException ( `` Condition with name [ `` + name + `` ] not found '' ) ; } | Factoring out a method appearing across many enums |
Java | I am taking data structures and analysis . We have gone over how assignment and comparisons of object types is much slower than assignment and comparisons for basic types , such as int.I recall learning C ( all those almost thirty years ago ) and how pointers in C are ( or were ) integer calls . Is Java similar today ,... | if ( MyObject ! = null ) { ... } | Are Java 'pointers ' integers ? |
Java | Is there anywhere in the Java standard libraries that has a static equality function something like this ? I just implemented this in a new project Util class , for the umpteenth time . Seems unbelievable that it would n't ship as a standard library function ... | public static < T > boolean equals ( T a , T b ) { if ( a == null ) return b == null ; else if ( b == null ) return false ; else return a.equals ( b ) ; } | Does Java have generic test for equality that also handles nulls ? |
Java | TL ; DR : Half-width : Regular width characters.Eg . ' A ' and ' ニ'Full-width : Chars that take two monospaced English chars ' space on the displayEg . ' 中 ' , ' に ' and ' A ' I need an implementation of this function : No this is not about data structures for those chars , it 's only about the displayed width.Long Sto... | /** * @ return Is this character a full-width character or not . */fun Char.isFullWidth ( ) : Boolean { // What is the most efficient implementation here ? } | Kotlin/Java - How to identify full width characters ? |
Java | what is the result ? to this question I expected the answer `` compilation fails '' because final method can not be overridden and it does not allow inheritance . but the answer was `` Cliddet '' why is that ? did I misunderstand something in this concept . how can this be the output ? please explain . | class Clidder { private final void flipper ( ) { System.out.println ( `` Clidder '' ) ; } } public class Clidlet extends Clidder { public final void flipper ( ) { System.out.println ( `` Clidlet '' ) ; } public static void main ( String args [ ] ) { new Clidlet ( ) .flipper ( ) ; } } | exact way how final methods works in java |
Java | what is fundamental difference in these two following approach for converting collection to array objectwhen should use approach-1 and when approach-2 ? | ArrayList < String > iName = new ArrayList < String > ( ) ; String [ ] array= iName.toArray ( new String [ iName.size ( ) ] ) ; //1 String [ ] array= iName.toArray ( new String [ 0 ] ) ; //2 | Difference in these two approach for converting collection to array object |
Java | I 'm looking to convert an array of char to a Set of Characters.Logically if I wrote out something like How to convert an Array to a Set in Java instead of using the built in functions it would work . However using built in functions with generics it does not.Why does n't it cast array of char to characters ? As a foll... | TreeSet < Character > characterSet = Sets.newTreeSet ( ) ; String myString = `` string '' ; Character [ ] characterArray = { 's ' , 't ' , ' r ' , ' i ' , ' n ' , ' g ' } ; Collections.addAll ( characterSet , characterArray ) ; // This works Collections.addAll ( characterSet , myString.toCharArray ( ) ) ; // This Does ... | Why does n't implicit casting happen here ? |
Java | I want to parse float values from From above string i need 13.04 and 14.67 . I used following regexBut using this i am getting `` .13 '' , `` .04 '' , `` .14 '' , `` .67 '' Thanks in advance | CallCost : Rs.13.04 Duration:00:00:02 Bal : Rs.14.67 2016 mein Promotion Pattern p = Pattern.compile ( `` \\d*\\.\\d+ '' ) ; Matcher m = p.matcher ( s ) ; while ( m.find ( ) ) { System.out.println ( `` > > `` + m.group ( ) ) ; } | How to parse float values from string using REGEX in java |
Java | Question : Most efficient way to get the highest number from a collection of integersI was recently discussing this question , I had 2 solutions in mind . 1 ) Iterating over the collection and find the highest number ( code below ) 2 ) Use a sorting algorithm . The first method will have O ( n ) efficiency My question ... | int getHighestNumber ( ArrayList < Integer > list ) { if ( list ! = null & & list.size ( ) > 0 ) { if ( list.size ( ) == 1 ) return list.get ( 0 ) ; int maxNum = list.get ( 0 ) ; for ( int item : list ) { if ( item > maxNum ) maxNum = item ; } return maxNum ; } return null ; } | Most efficient way to get the highest number from a collection of integers |
Java | I have a data sample : it 's just a compressed EMF image . I try to decompress it by code : and get a CORRECT answerAfter that i 'm try to compress it back by code : And get a result : the more similar result was achieved when i uncomment deflater initialization and using in DeflateOutputStream constructor.As for me it... | byte [ ] b = new byte [ ] { 120 , 1 , -67 , -107 , -51 , 106 , 20 , 81 , 16 , -123 , 107 , 18 , -51 , -60 , 31 , -30 , 117 , -4 , -53 , -60 , -123 , 25 , 70 , 71 , 23 , -111 , 89 , 12 , 8 , -83 , 49 , 4 , -14 , -93 , -63 , 73 , 32 , 89 , -55 , -112 , -123 , 10 , -30 , 66 , 69 , -110 , 69 , -64 , -107 , -77 , 8 , -72 , ... | Non symmetric java compression |
Java | Has anybody ever used those machines at a gas station or grocery store where you get money for donating your recyclables ? Well , I wanted to make a virtual one of those and so far everything 's okay until I had to do some math . I 'm only 13 , so this part was pretty tricky even though I thought it was gon na be simpl... | import java.awt.event.ActionEvent ; import java.awt.event.ActionListener ; import javax.swing . * ; public class Machine { static JLabel label ; static JComboBox typeList ; static JComboBox amountList ; public static void GUI ( ) { JFrame frame = new JFrame ( `` Recyclables Machine '' ) ; frame.setVisible ( true ) ; fr... | Math `` equations '' not working properly |
Java | Say I have an arrayList containing items of different classes , all of them having the same method : draw ( ) ; I have a third class with a method drawItems ( ) that takes in the arrayList as a parameter . Now , how can I call the draw ( ) method on those objects if they are passed as generic objects ? This below does ... | public void drawItems ( ArrayList < T > data ) { data.forEach ( ( T item ) - > { item.draw ( ) ; } ) ; } public interface Drawable { public void draw ( ) ; } public class Item implements Drawable { @ Override public void draw ( GraphicsContext gc ) { // ... } } public void drawItems ( ArrayList < Drawable > data ) { da... | How can I call an instance method from a generic object ? |
Java | I upgrade my Spring boot version from 2.0.5.RELEASE to 2.1.8.RELEASE ( so Spring Integration from 5.0 to 5.1 ) and the automatic type casting inside integration flow does n't work anymore . I am used to define a set of @ IntegrationConverter components and automatic casting with the operation transform ( Type.class , p... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' ? > < project xmlns= '' http : //maven.apache.org/POM/4.0.0 '' xmlns : xsi= '' http : //www.w3.org/2001/XMLSchema-instance '' xsi : schemaLocation= '' http : //maven.apache.org/POM/4.0.0 https : //maven.apache.org/xsd/maven-4.0.0.xsd '' > < modelVersion > 4.0.0 < /modelV... | Spring Integration 5.1 - integration flow convertion with @ IntegrationConverter does n't work |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.