text
stringlengths
46
37.3k
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 ...
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 ...
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 ....
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 t...
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 ... ? <code> | Welcome to JShell -- Version 14.0.1| For an introducti...
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 ? <code> public class AnimalException extends Exception { public AnimalException ( String ...
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 . <code> public int...
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 : <code> public Product getMostExpensiveProduct ( HashMap < Integer , Product > items ) { Product maxPriceProduct = items.entrySe...
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 ...
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 ? <code> Class klasa = Enum.class ; for ( Type t : k...
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...
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 s...
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...
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 ? <code> import java.util.HashMap ; import java.util.Iterator ; import java...
Displaying trouble in hash map
Java : Why prints 5000 msbut prints 44 msSecond solution 115 time faster <code> 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.currentTimeMi...
Why does time for initialize array different
Java : Here is some sample code ( assuming Java 8 ) . Is s effectively final inside the loop ? <code> 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 ? <code> 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 a...
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 n...
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 demo...
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 : I...
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 . <code> for ( GlobalPricingRequest globalPricingRequest : globalPricingRequests ...
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 '' w...
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 ? <code> ( ( rrd == null || ! rrd ) & & null ! = dam & & null ! = dam.getac ( ) & & null ! = dam.getac ( ) .getc ( ) & & null ! = sname & & sname.equalsIgnoreCase ( dam.getac ( ) .getc ( ) ) ) ( ( rrd...
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...
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 ? <code> abstract class Parent < V > { protected static < T extends Parent < V > , V > T newInstance ( final Class < T > type , final V value ) { // ... } } class Child extends...
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 , noth...
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 . ...
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 exp...
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 ...
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 para...
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 <code> public class Test16Jit { public static void main ( String [ ] s ) { int max = Integer.MAX_VALUE ; int i = 0 ; long li = 0 ; while ( i > = 0 ) { ...
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 a...
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 diffe...
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 : <code> class Student { String name ; int age ; } HashMap < String , Student > ...
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 . <code> class test { public static void main ( String arg [ ] ) { short x=1 ; 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 fo...
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 . <code> class Parent { private void method1 ( ) { System.out.println ( `` Parent 's method1 ( ) '' ) ; } public void method2 ( ) { System.out.println...
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 d...
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 Navig...
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 t...
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 ? <code> class A { String co...
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 whe...
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 . <code> public static int indexOf ( byte ...
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 > ? <c...
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 encapsulatio...
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 d...
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 h...
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 . <code> void m ( ...
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 . <code> /** * Returns a ...
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 : <code> public static class MyModel { private int left ; private int right ; private i...
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...
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 <co...
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 u...
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 ? <code> public void setValue ( int value ) { this.value = value ; } private static int value = 7...
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 : <code> public final class Object1 { private String a ; private String b ; // constructor getter and setter } public class Obje...
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 <code> @ Testpublic void predicateTest ( ) { Predicate < Boolean > test1 = p - > 1 == 1 ; Predicate < Boolean > test2 = p - >...
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 , JsonRead...
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 par...
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 . <code> public static void main ( String [ ] args ) { System.out.print...
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...
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 ] el...
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 : <code> for ( int omega = 0 ; omega < 1080 ; ...
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 s...
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 di...
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 . <code> public class Fo...
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 ActionListe...
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 ? <code> static String [ ] ipLis...
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 ...
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 ... <code> public enum MyEnum { FIRST { @ Override public void someMethod ( ) { ... } } , SECOND { @ Override public void someMetho...
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...
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 ded...
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 k...
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...
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 ...
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...
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 ) ? <code> public List < Entry > getEntriesForUserId ( int userId ) { User u = DataBaseConnector .getAllUsers ( ) .stream ( ) .filter ( u...
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 ? <code> if ( ++j == 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 ...
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 ...
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 pr...
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 opti...
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...
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 ) . <code> while ( fileInputStream.available ( ) > 0 ) { fileOutputStream.write ( fileInputStream.read ( ) ) ; } whi...
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 '...
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 '' ] } . <code> List < Entry < Integer , String > > list...
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 . <code> ArrayList < Integer > myList = new ArrayList < > ( ) ; f...
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 de...
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 ...
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 ... <code> public static < T > boolean equals ( T a , ...
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.L...
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 . <code> cl...
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 ? <code> ArrayList < String > iName = new ArrayList < String > ( ) ; String [ ] array= iName.toArray ( new String [ iName.size ( ) ] ) ; //1 String [ ] array= iNa...
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...
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 <code> CallCost : Rs.13.04 Duration:00:00:02 Bal : Rs.14.67 2016 mein Promotion Pattern p = Pattern.compile ( `` \\d*\\.\\...
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 qu...
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 fo...
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 b...
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 belo...
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.cl...
Spring Integration 5.1 - integration flow convertion with @ IntegrationConverter does n't work