lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | I have a structure like that Thats the parent ..Now I have 3 children.. Every class has some different stuff do render .One is for example drawing yellow circle , second green text and the third is displaying image . But ... there is a thing . One Entity has for example 10 Bs ... and each B has 20 Cs ... So now .. I ha... | abstract Class Entity { //some variables ... //some methods ... public abstract void render ( Graphics g ) ; } Class A extends Entity { } Class B extends Entity { } Class C extends Entity { } Class A have List < B > ... Class B have List < C > ... for ( A a : listOfAs ) { for ( B b : listOfBs ) { for ( C c : listOfCs )... | Calling many methods of many objects many times per second |
Java | I have a ParentClass in a JAR , but not source code . I am implementing a SubClass , but i need to handle some corner cases.Is there a way to run the //lots of code 2 part after handling the exception in the overriding method ? I do n't want to duplicate code , and can not modify the ParentClass.P.S : The NullPointerEx... | class ParentClass { void foo ( ) { … // lots of code 1 ; // can possibly throw NullPointerException … // lots of code 2 } } class SubClass extends ParentClass { @ Override void foo ( ) { try { super.foo ( ) ; } catch ( NullPointerException npe ) { … /*handle exception*/ } finally { … /* resume lots of code 2 ? */ } } } | Is it possible to resume Java execution after exception ? |
Java | So I 'm working on a Breadth-First search function for a program I 'm working on for school , and when I go through the outgoing edges for a given node , by virtue of how I 'm going through my possible edges , it looks something like this : But what I really want is this : Where the first index of a pair is the name of... | [ [ A , 1 ] , [ D , 1 ] , [ C , 2 ] , [ D , 2 ] ] [ [ A , 1 ] , [ C , 2 ] , [ D , 1 ] , [ D , 2 ] ] | How can I sort an ArrayList < ArrayList < String > > ? |
Java | I am reading some books about java concurrency lately . Regarding thread safety , if it is not possible to make a class inmutable , you can always ensure thread safety by synchronizing its data . The following class would be clearly not thread safeThen i can synchronize the write , but it will remain not thread safeAs ... | public class NotThreadSafe { private int value ; public void setValue ( int value ) { this.value = value ; } public int getValue ( ) { return this.value ; } } public class StillNotThreadSafe { private int value ; public synchronized void setValue ( int value ) { this.value = value ; } public int getValue ( ) { return t... | Synchronized , volatile and thread safety |
Java | Before the introduction to generics to the Java language I would have written classes encapsulating collections-of-collections-of-collections . For example : Of course , with generics , I can just do : I tend to now opt for option # 2 ( over a generified version of option # 1 ) because this means I do n't end up with a... | class Account { private Map tradesByRegion ; //KEY=Region , VALUE=TradeCollection } class TradeCollection { private Map tradesByInstrument ; //KEY=Instrument , Value=Trade } class Account { private Map < Region , Map < Instrument , Trade > > trades ; } | To use nested genericized collections or custom intermediate classes ? |
Java | I stumbled upon this article on IBM - developerworks , and the code they posted had me raise some questions : Why is the building of the local variable Map wrapped within a synchronized block ? Note that they implicitly say there is only one producer thread.Actually , why would this snippet require a synchronized block... | static volatile Map currentMap = null ; // this must be volatilestatic Object lockbox = new Object ( ) ; public static void buildNewMap ( ) { // this is called by the producer Map newMap = new HashMap ( ) ; // when the data needs to be updated synchronized ( lockbox ) { // this must be synchronized because // of the Ja... | Why would I place a synchronized block within a single-threaded method ? |
Java | I am trying different combination of inner classes.I wonder that java gives you facility to write interface inside interface.It does not give me any compile time error.Can anybody tell me what is the use of this ? | public interface IA { public interface IB { } } | Why java provide facility to declare interface inside interface |
Java | I want to get the next element from a spliterator , not just `` perform action '' on the next element . For example by implementing the following methodAll search results I found just said that tryAdvance ( ) was like a combination of an iterators hasNext ( ) and next ( ) , except that is a BIG LIE because I ca n't get... | < T > T getnext ( Spliterator < T > s ) { } | How to return the next element from a spliterator in java |
Java | I would like to ask about generic classes . What happens when I create two object instance from a generic class . Do they share every static members , or both have it 's own static members ? So for example : Do both Integer and String have the same reference behind member ? | public A < ? > ( ) { public static Integer member = 0 ; } A < Integer > integer = new A < Integer > ( ) ; A < String > string = new A < String > ( ) ; | Do generic classes share static members ? |
Java | We are in the process of migrating a WebLogic 10.3.5 web app to WebLogic 12.1.3 and we 've run into an issue which we think might be related to web services security . The app uses Axis 1.5.6 to call out to a SOA Suite SOAP service ( still running on WebLogic 10.3.5 ) . When web service security is disabled , we get ba... | < ? xml version= '' 1.0 '' encoding= '' UTF-8 '' standalone= '' yes '' ? > < ns3 : getNamesResponse xmlns : ns2= '' http : //www.example.com/ABC/Common '' xmlns : ns3= '' http : //www.example.com/ABC/Profile '' > < ns3 : OperatingName > < ns3 : Number > 123456789 < /ns3 : Number > < ns3 : Name > Company Name , Inc. < /... | SOA Suite to Axis2 data being dropped |
Java | I have a JXtable . I would like to prevent the top 3 rows from being sorted . Basically the top 3 rows should always be on top and the remaining ones should be sorted according to their value.There is a similar question on SO but i am not sure how to really apply it to my useSort ROW except last rowThe major difference... | jTable1 = new JXTable ( ) ; if ( isClickable ) { jTable1.getTableHeader ( ) .setCursor ( Cursor.getPredefinedCursor ( Cursor.HAND_CURSOR ) ) ; //set the sorter here } else { jTable1.setSortable ( false ) ; } | prevent sorting of top 3 rows in jxtable |
Java | I work as an automation engineer for my company . Recently , I wrote a piece of code that my manager absolutely would not accept.I was asked to write some scripts for test cases involving different pieces of the GUI . The part of the code my manager would not accept was an if/else statement meant to check the current l... | switch ( button ) { case `` ok '' : if ( s.exists ( `` imagerepo/language/catalan_ok.png '' ) ! = null ) { s.click ( `` imagerepo/language/catalan_ok.png '' ) ; } else if ( s.exists ( `` imagerepo/language/suomi_ok.png '' ) ! = null ) { s.click ( `` imagerepo/language/suomi_ok.png '' ) ; } else if ( s.exists ( `` image... | How to simplify long list of similar if statements ? |
Java | the following code : When I uncomment the line 9 , that is let print if condition is true , though never it is going to happen since both object are not equal , then it takes 5000+ milli-seconds , and to my surprise by just commenting it takes only 5 milli-seconds , I am not getting the reason , why it takes so much ti... | String str1= '' asdfavaxzvzxvc '' ; String str2= '' werwerzsfaasdf '' ; Object c=str1 ; Object d=str2 ; System.out.println ( c ) ; long time1=System.currentTimeMillis ( ) ; for ( int i=0 ; i < 1000000000 ; i++ ) { if ( c.equals ( d ) ) { //System.out.println ( `` asfasdfasdf '' ) ; // line 9 } } long time2=System.curre... | Output timing problem |
Java | I was going through the Exchange Web Services Java API code and saw a design choice in the way the developers passed arguments to their methods . May you can help explain the benefits of the technique -- The type that is to be processed by the method is wrapped by a Generic Wrapper class before being passed into the me... | class Param < T > { private T param ; public T getParam ( ) { return param ; } public void setParam ( T param ) { this.param = param } } protected HttpWebRequest emit ( OutParam < HttpWebRequest > request ) throws Exception { request.setParam ( this.getService ( ) .prepareHttpWebRequest ( ) ) ; OutputStream urlOutStrea... | A curious way of passing a parameter to a method |
Java | Today I was exploring classes of huge applications ( like jboss server with apps ) with javaagent and instrumentation on my openjdk 7 . I called retransform on all classes every 10 seconds , so their bytecode got in my ClassFileTransformer implementation.My implementation simply keeps track of how bytecode of classes c... | pool : ... # 17 Float NaNfmethod : # 1 fload # 17 //NaNf ... pool : ... # 17 Float NaNf # 18 Float NaNfmethod : # 1 fload # 18 //NaNf < - look , it loads # 18 now | Bytecode changes over time in undocumented manner |
Java | I have the following codeI thought it would raise a NPE but it is giving Mount Everest as output can anyone clarify ? | public class Test { static String mountain = `` Everest '' ; static Test favorite ( ) { System.out.print ( `` Mount `` ) ; return null ; } public static void main ( String [ ] args ) { System.out.println ( favorite ( ) .mountain ) ; } } | Why does n't calling a static variable chained from a static method that returns null throw a NPE ? |
Java | I am new to java and trying some accessing methods and i encountered something that i do not understand . The code below working fine , prints 9 and not giving any compilation errors . I think this code should give a compilation error and number should be inaccessible from the test method , since new Human ( ) is an in... | public class Test { public static void main ( String [ ] args ) { int number = 9 ; test ( `` holla '' , new Human ( ) { @ Override void test ( ) { // TODO Auto-generated method stub System.out.println ( number ) ; // I think this line should not compile } } ) ; } private static void test ( String a , Human h ) { h.test... | Accessing a private element through an inline created object in java |
Java | I am wondering if there is n't a better way to convert whole Lists or Collections as the way I show in the following code example : Every time I produce a method like this , I start thinking , is n't there a better way ? My first thought would be to create maybe a solution with some generics and reflections , but this ... | public static List < String > getAllNames ( List < Account > allAccounts ) { List < String > names = new ArrayList < String > ( allAccounts.size ( ) ) ; for ( Account account : allAccounts ) { names.add ( account.getName ( ) ) ; } return names ; } | Better way to convert an List < MyDataType > to List < String > |
Java | I have my own service calling a third party rest service that is returning a text based response.This text based response is not a proper service response and needs to be parsed for content as well as errors . For purposes of discussion , assume the 3rd party rest service can not be changed.Given these circumstance I a... | public void MyDao { private RestTemplate restTemplate ; private ResponseParser responseParser ; public myDao ( RestTemplate restTemplate , ResponseParser responsePaser ) { this.restTemplate = restTemplate ; this.responseParser = responseParser ; } public MyResponse sendRequest ( MyRequest myRequest ) { ResponseEntity <... | In Which Layer , Dao or Service , Should I Parse a Rest Client Response ? |
Java | My question is what is a good way to implement upgrading outdated objects ? For example say you have a class like this : and then you serialize this object . Then later on you add more functionality to your class by say adding : You still want to retain the information that is in the serialized object but I know that i... | public class Foo ( ) implements Serializable { int a ; String b ; } ... int c ; ... | Deserialization version conflicts |
Java | I 'm using a Comparator implementation to sort a large collection of objects . Depending on the type of objects in this collection the sort takes a few milliseconds to half a minute . Is there any way to determine the progress of the Comparator while sorting ? I 'd like to visualize this for the user.The collection may... | Collections.sort ( sorted , new Comparator < Object [ ] > ( ) { public int compare ( Object [ ] o1 , Object [ ] o2 ) { /* do it ... */ return order ; } } | Can one determine the progress of a Java Comparator ? |
Java | I have a scenario where I have to maintain a Map which can be populated by multiple threads , each modifying their respective List ( unique identifier/key being the thread name ) , and when the list size for a thread exceeds a fixed batch size , we have to persist the records to the database.Aggregator classThere is on... | private volatile ConcurrentHashMap < String , List < T > > instrumentMap = new ConcurrentHashMap < String , List < T > > ( ) ; private ReentrantLock lock ; public void addAll ( List < T > entityList , String threadName ) { try { lock.lock ( ) ; List < T > instrumentList = instrumentMap.get ( threadName ) ; if ( instrum... | Missing updates with locks and ConcurrentHashMap |
Java | Please consider this example : What interests me here is the first test . Why is it using MyConsumer instead of Consumer ? What if I had more different possible Consumers with the same lambda structure , who has priority ? Plus , the cast I do on Test 2 is marked as Redundant by my IDE . That means the lamdba is create... | import java.util.function.Consumer ; public class Example { public static void main ( String [ ] args ) { Example example = new Example ( ) ; example.setConsumer ( test - > System.out.println ( `` passed string is `` + test ) ) ; //uses MyConsumer , why ? example.getConsumer ( ) .accept ( `` Test 1 '' ) ; example.setCo... | What decides which functional interface to create from a lambda ? |
Java | I have a tree data structure I 'd like to store using Neo4j.There is a parent node : CodeSet , which is always the root of the tree and a child nodes : Node , which themselves can have child nodes of the same type . They are connected with relationship of type : SUBTREE_OF as follows : The parent node is displayed in r... | public abstract class AbstractNode { private Long id ; @ NotEmpty private String code ; @ Relationship ( type = `` SUBTREE_OF '' , direction = Relationship.INCOMING ) private Set < Node > children ; < getters & setters omitted > } public class CodeSet extends AbstractNode { @ Relationship ( type = `` SUBTREE_OF '' , di... | How to code the hierarchical relationship to the node of the same type properly in spring data neo4j ? |
Java | I am testing out the new Stream API in java-8 and want to check the outcome of 10000 random coinflips . So far I have : but this throws the exception : I understand why this is happenning but how can i print the count for heads and tails if I can only use the stream once ? | public static void main ( String [ ] args ) { Random r = new Random ( ) ; IntStream randomStream = r.ints ( 10000,0 , 2 ) ; System.out.println ( `` Heads : `` + randomStream.filter ( x - > x==1 ) .count ( ) ) ; System.out.println ( `` Tails : `` + randomStream.filter ( x - > x==0 ) .count ( ) ) ; } java.lang.IllegalSta... | Getting two different outputs from a Stream |
Java | My understanding is that static members belong to the class . Why then does Java allow me to access them with an object ? To understand what I mean , please see the following example : Here number is a static field that belongs to class Student , but I can still access it as shown below : What is the rationale behind t... | public class Student { public static int number = 0 ; } Student s = new Student ( ) ; int n = s.number ; | Why does Java allow accessing of a static member with an object instance |
Java | I put together an RSS reader that works as-is but , I want to setup the connection to the RSS URL using HttpUrlConnection method . When I tried it , the program locked up after I clicked Read Rss button : This is the connection method I am stuck using which works : Thanks for any help you can provide ! | private class getRssFeedTask extends AsyncTask < String , Void , String > { @ Override protected String doInBackground ( String ... params ) { try { URL rssUrl = new URL ( params [ 0 ] ) ; HttpURLConnection urlIn = ( HttpURLConnection ) rssUrl.openConnection ( ) ; InputStream in = new BufferedInputStream ( urlIn.getInp... | Using HttpUrlconnection in Rss Reader causes Android to hang |
Java | Why does throw outerE ; generate a compilation error ? I know that throw e ; should not generate a compiler error because of the precise rethrow feature.They 're the same Exception object , but one is scoped inside the catch block only and one is scoped outside the try-catch block.Should n't neither of these generate a... | static void preciseRethrowTest ( ) { Exception outerE ; try { } catch ( Exception e ) { outerE = e ; // Compilation error here . Unhandled exception type Exception // throw outerE ; throw e ; // No compiler error } } | Why do either of these rethrown exceptions create a compiler error ? |
Java | When I was going through ArrayList implementation , I found a weird piece of code in toArray ( T [ ] ) method.The part is , why only the element at this index in the array is set to null ? Once the array is filled with the contents of the list , the elements at the remaining indices should have been set to null , right... | public < T > T [ ] toArray ( T [ ] a ) { if ( a.length < size ) // Make a new array of a 's runtime type , but my contents : return ( T [ ] ) Arrays.copyOf ( elementData , size , a.getClass ( ) ) ; System.arraycopy ( elementData , 0 , a , 0 , size ) ; if ( a.length > size ) a [ size ] = null ; return a ; } if ( a.lengt... | toArray ( T [ ] ) method in ArrayList |
Java | In following code the issue is , that I can not test dao.add ( ) without using dao.list ( ) .size ( ) and vice versa.Is this approach normal or incorrect ? If incorrect , how can it be improved ? | public class ItemDaoTest { // dao to test @ Autowired private ItemDao dao ; @ Test public void testAdd ( ) { // issue - > testing ADD but using LIST int oldSize = dao.list ( ) .size ( ) ; dao.add ( new Item ( `` stuff '' ) ) ; assertTrue ( oldSize < dao.list ( ) .size ( ) ) ; } @ Test public void testFind ( ) { // issu... | How to test `` add '' in DAO without using `` find '' etc . ? |
Java | I am getting out of memory error with just 50000 objects . I checked computeIfAbsent implementation but unfortunately did not find any thing peculiar.My machine configuration is 16 GB ram and core I7.and my ListObject is below : Can some one please help me understand this behavior . | public class Test { public static void main ( String [ ] args ) { int count = 50000 ; List < ListObject > list = new ArrayList ( ) ; for ( int i = 0 ; i < count ; i++ ) { int key = ThreadLocalRandom.current ( ) .nextInt ( 100000 ) ; int value = ThreadLocalRandom.current ( ) .nextInt ( 1000000 ) ; list.add ( new ListObj... | Unwanted out of memory error in ArrayList : :new - Why ? |
Java | I encountered misunderstanding of primitive promotion in the next code snippet.What would I expect ? long b = ( int ) a > > 4L ; long b = a > > 4L ; int b = a > > 4L ; int > > long will promote to the larger data type ( long ) and it wo n't compile with resulted int type.What have I received ? It compiles fine . Why ? | byte a = 2 ; int b = a > > 4L ; | primitive promotion for > > [ Java ] |
Java | While migrating my JAX-RS application from Jersey to Quarkus/Resteasy , I came across a behavior change with the method evaluatePreconditions ( Date lastModified ) . Indeed , in my use case , the last modified date contains milliseconds and unfortunately the date format of the headers If-Modified-Since and Last-Modifie... | @ Path ( `` /evaluatePreconditions '' ) public class EvaluatePreconditionsResource { @ GET @ Produces ( MediaType.TEXT_PLAIN ) public Response findData ( @ Context Request request ) { final Data data = retrieveData ( ) ; final Date lastModified = Timestamp.valueOf ( data.getLastModified ( ) ) ; final Response.ResponseB... | What is the right behavior of evaluatePreconditions on a date with milliseconds according to the specification ? |
Java | Experienced programmer new to Java seeking your wisdom : If there is no way to ensure that some particular chunk code is executed as an object goes out of scope , then what other approaches are there that would offer the same functionality ? ( it seems finalize is clearly not meant for that ) A classic example is the s... | void method ( ) { // Thread-unsafe operations { ... } { // < - New scope // Give a mutex to the lock ScopedLock lock ( m_mutex ) ; // thread safe operations { ... } if ( ... ) return ; // Mutex is unlocked automatically on return // thread safe operations { ... } } // < - End of scope , Mutex is unlocked automatically ... | Java techniques for end-of-lifetime of objects |
Java | The difference I see is ( running on JDK 1.7 ) : setVisible ( false ) , invokes componentHidden but not windowClosed ( The API states only on dispose ( ) so it 's OK even if it irritates me ) but dispose ( ) , invokes windowClosed but not componentHiddenShort running example code ( MCVE ) : NOTE : The example features ... | public class JDialogTest extends JDialog { private static final long serialVersionUID = 1L ; public JDialogTest ( JFrame owner ) { super ( owner , ModalityType.APPLICATION_MODAL ) ; init ( ) ; } private void init ( ) { this.getContentPane ( ) .setLayout ( new GridLayout ( 1,2 ) ) ; JButton btnVisible = new JButton ( ``... | Why are the Window/Component Listeners invoked differently when setVisible ( false ) and dispose ( ) are called ? |
Java | So here is the simple thing I am trying to test , what is faster a mod operation or a AND one ( assuming power of two ) - this is what hashMap does internally . Is this a correctly spelled `` test '' ? I have to admit that the internals of jmh and getting to write a correct micro benchmark after going through all the s... | @ State ( Scope.Thread ) @ BenchmarkMode ( org.openjdk.jmh.annotations.Mode.AverageTime ) @ OutputTimeUnit ( TimeUnit.NANOSECONDS ) public class MeasureSpeedModuleVsAnd { public static void main ( String [ ] args ) throws Exception { Options opt = new OptionsBuilder ( ) .include ( MeasureSpeedModuleVsAnd.class.getSimpl... | How to benchmark ' & ' vs ' % ' cost correctly , using JMH |
Java | Reading the source code for Instant class , I bumped into this methodThe description got me curious . What is a `` malicious stream '' ? And how is this method defending against it ? | /** * Defend against malicious streams . * * @ param s the stream to read * @ throws InvalidObjectException always */private void readObject ( ObjectInputStream s ) throws InvalidObjectException { throw new InvalidObjectException ( `` Deserialization via serialization delegate '' ) ; } | What does it mean that Instant.readObject method `` Defend [ s ] against malicious streams '' ? |
Java | I have a string that is dynamially generated . I need to split the string based on the Relational Operator.For this I can use the split function.Now I would also like to know that out of the regex mentioned above , based on which Relational Operator was the string actually splitted.An example , On input applyingwill gi... | String sb = `` FEES > 200 '' ; List < String > ls = sb.split ( `` > | > =| < | < =| < > |= '' ) ; System.out.println ( `` Splitted Strings : `` +s ) ; Splitted strings : [ FEES , 200 ] Splitted strings : [ FEES , 200 ] Splitted Relational Operator : > | Obtaining the split value after java string split |
Java | When manipulating scala objects ( primarily from the the scala.collection package ) the operator overloaded functions seem to be available to be used in Java.i.e . in scalaso in Java , looking at scala.collection.Set in eclipse autocomplete , I can see the prototypesBut I 'm unable to use them correctlyHow are these sc... | var s = Set ( 1 , 2 , 3 ) var t = s + 4var x = s | t import scala.collection.Set ; Set < Integer > s = new Set < Integer > ( ) ; Set < Integer > t = s. $ plus ( 4 ) ; /* compile error with javac , or runtime error with eclipse/* | scala operators as methods in java |
Java | We 're upgrading a Java 6 project to Java 8 . Recompiling with Java 8 gives errors in a java.awt.Frame subclass , I 've simplified to the following : org/example/Foo.javaorg/example/Type.javaWhat appears to be happening is a static enum java.awt.Window.Type introduced in Java 7 is taking precedence even though there is... | package org.example ; import org.example.Type ; import java.awt.Frame ; public class Foo extends Frame { public Foo ( ) { System.out.println ( Type.BAZ ) ; // < === error here , BAZ can not be resolved } } package org.example ; public class Type { public static final int BAZ = 1 ; } | Java 8 upgrade causes compiler error with inherited static enum |
Java | I am trying to close Android emulator using telnet command via Appium script but after executing the telnet command waiting for manual input for `` kill '' command.Unable to execute the `` Kill '' command along with Appium script . | Runtime.getRuntime ( ) .exec ( `` telnet localhost 5554 '' ) ; Process proc= Runtime.getRuntime ( ) .exec ( `` kill '' ) ; BufferedReader r = new BufferedReader ( new InputStreamReader ( proc.getInputStream ( ) ) ) ; System.out.println ( `` executed3 '' ) ; String line ; while ( true ) { line = r.readLine ( ) ; if ( li... | Android emulator close using telnet via appium script |
Java | I recently ran across this scenario in code that I did n't write and while there may be some design benefit to this approach , I ca n't seem to squeeze this rationale out of my own brain . So before I go and look foolish , I 'm hoping for some feedback here . Service interface something like this : Then , a base class ... | public interface Service { ... } public class ServiceBase < T extends Service > implements Service { ... } public class MyService extends ServiceBase < MyService > { ... } | Benefits of Using Generics in a Base Class that Also Implement the Same Class |
Java | I faced below Interview question.what is the output of the below code.It is giving output :10But i am confuse why its output 10.Anyone can answer me please what happening here.ThanksSItansu | package com.demo ; import java.util.HashSet ; import java.util.Set ; public class Test { public static void main ( String [ ] args ) { Set < Short > set=new HashSet < Short > ( ) ; for ( short i = 0 ; i < 10 ; i++ ) { set.add ( i ) ; set.remove ( i-1 ) ; } System.out.println ( set.size ( ) ) ; } } | Java interview puzzle related to set |
Java | In Java 1.8 , the following lambda expression complies with both Runnable and Callable functional interfaces : Still , if I submit it to an ExecutorService using a single-argument method , and ignore the return value ( i. e. no type inference information is available ) , ExecutorService # submit ( Callable ) is chosen ... | ( ) - > { throw new RuntimeException ( `` FIXME '' ) ; } | Choosing between overloaded methods if actual parameter is a lambda |
Java | I have a object model like the one given belowI have a list of objects like List < Employees > Based on the Filter inputs , I want to construct the predicate on the property and apply that to the list of employees.Example : The operators are like Contains , StartsWith , EndsWith , EqualsI would like to construct the pr... | public class Filter { public String field ; public ConditionalOperator operator ; public String value ; } Employees FirstName LastName CreatedOn ( Timestamp ) Status ( FullTime/ parttime ) IsActive ( True / False ) Filter conditions will be looking like [ { `` field '' : '' FirstName '' , `` operator '' : '' StartsWith... | Construct a predicate using custom object model in java |
Java | I am using a heterogeneous container similar to this one . I can put and receive objects from the container with ease : But there seem to be no easy way to iterate over such container . I can add a keySet ( ) method to the Favorites class and simply return the key set of the internal Map object : Now , I would like to ... | Favorites f = new Favorites ( ) ; f.putFavorite ( String.class , `` Java '' ) ; String someString = f.getFavorite ( String.class ) ; public Set < Class < ? > > keySet ( ) { return favorites.keySet ( ) ; } for ( Class < ? > klass : f.keySet ( ) ) { // f.getFavorite ( klass ) . < SOME_METHOD_SPECIFIC_TO_THE_CLASS-KEY > } | Iterating over heterogeneous container |
Java | What is the CodeSignature in aspectJ ? I tried to find JavaDocs but did n't find anything useful . For Instance , thy is the following signature is a CodeSignature : Is there a JoinPoint such that thisJoinPoint.getSignature ( ) that is not a CodeSignature ? | pointcut log ( ) : execution ( @ Log * * ( .. ) ) ; before ( ) : log ( ) { String [ ] names = ( ( CodeSignature ) thisJoinPoint.getSignature ( ) ) .getParameterNames ( ) ; } | CodeSignature aspectJ |
Java | What is the difference between both these ways of lambda creation ? Why does n't the first one compile ? Gives : error : incompatible types : Predicate < Object > can not be converted to Predicate < Integer > = Predicate.isEqual ( 0 ) .or ( Predicate.isEqual ( 1 ) ) ; This one works . | Predicate < Integer > predicate = Predicate.isEqual ( 0 ) .or ( Predicate.isEqual ( 1 ) ) ; Predicate < Integer > pred21 = Predicate.isEqual ( 0 ) ; Predicate < Integer > pred22 = pred21.or ( Predicate.isEqual ( 1 ) ) ; | Lambda as a combination of methods from the Predicate interface does n't compile if it is written as one statement |
Java | I 'm trying to sort the release versions in form of `` a.b.c '' I 'm using mongo-java-driverI have created the index with collation : I have implemented the aggregation query with java driver : And I 'm returning the list in a document as API response.But the output I 'm getting is : And when I tried the same with Mong... | < dependency > < groupId > org.mongodb < /groupId > < artifactId > mongo-java-driver < /artifactId > < version > 3.8.0 < /version > < /dependency > { `` v '' : 2 , `` key '' : { `` version '' : 1 } , `` name '' : `` version_1 '' , `` ns '' : `` db.sysversion '' , `` collation '' : { `` locale '' : `` en '' , `` caseLev... | Getting unwanted output from MongoDB collation |
Java | Like many log4j users , we often have debug level logging that is expensive to evaluate . So we guard those cases with code like : However , that is uglier than a plain _logger.debug call , and sometimes the programmer does n't realize the evaluation could be expensive.It seems like it should be fairly simple to write ... | if ( _logger.isDebugEnabled ) _logger.debug ( `` Interesting , my foojes are goofed up : `` + getFullDetails ( ) ) | Making simple performance modifications to an already compiled jar ? |
Java | I seem not to understand this.To my surprise , I am not null is printed on the console . Why is myMethod not seeing the passed obj parameter as null . | public class NewClass { public static void main ( String [ ] args ) { Object obj = null ; myMethod ( obj ) ; } public static void myMethod ( Object ... objArr ) { if ( objArr ! = null ) { System.out.println ( `` I am not null '' ) ; } } } | Why is my method not seeing null Object |
Java | Excuse me for my ignorance . I could n't understand the difference between the following seemingly similar lines of code . final int num1 = 1 ; final int num2 ; num2 = 2 ; What makes the num2 not eligible for a switch case constant ? | switch ( expression ) { case num1 : System.out.println ( `` Case A '' ) ; case num2 : System.out.println ( `` Case B '' ) ; } | What is the difference between the two following lines of java code ? |
Java | Why is n't b equal to true if you run this code on Windows ? I want s to be `` \n '' and not `` \r\n '' , even on Windows . | System.setProperty ( `` line.separator '' , `` \n '' ) ; String s=String.format ( `` % n '' ) ; boolean b= '' \n '' .equals ( s ) ; | How to make `` % n '' equal to `` \n '' |
Java | Say I have an array that is stored in 0° rotation : And I want it returned in a good approximation if I pass , for example 30° as parameter , it would be something like:45° would beI am aware of the solutions posted for 90° rotations . But I do n't think that will help me here ? I do n't have any examplecode because I ... | 0 0 1 0 00 0 1 0 0 1 1 1 0 0 0 0 0 0 00 0 0 0 0 0 0 0 1 01 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 10 1 0 1 00 0 1 0 0 0 0 0 0 0 0 0 0 0 0 class Rotation { public Rotation ( ) { A = new int [ xs , ys ] { { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 0,0,0,9,0,0,0 } , { 9,9,9,9,0,0,0 } , { 0,0,0,0,0,0,0 } , { 0,0,0,0,0... | How can I rotate a 2d array by LESS than 90° , to the best approximation ? |
Java | I am new to Mockito and PowerMockito as well . I found out that I can not test static methods with pure Mockito so I need to user PowerMockito ( right ? ) .I have very simple class called Validate with this very easy methodSo I need to verify that:1 ) When I call that static method on null message argument , IllegalArg... | public class Validate { public final static void stateNotNull ( final Object object , final String message ) { if ( message == null ) { throw new IllegalArgumentException ( `` Exception message is a null object ! `` ) ; } if ( object == null ) { throw new IllegalStateException ( message ) ; } } import static org.mockit... | For what reason should I mock ? |
Java | At first glance , I have the same problem as many . But my case a bit more complex.Preconditions : Project language : Java 11Network Server : Orbiwise NS ( https : //eu.saas.orbiwise.com/ ) Device : ( STM32 + Wifi module ) connection via Lorawan gateway to Orbiwise and using TCP socket via wifi . Input data : From TCP ... | 40 24 fa fa 01 c2 c5 25 03 06 01 43 a4 99 5a c185 71 0c 87 38 84 53 9a 80 6c 5a 14 da f8 ff 7c21 83 8f 78 8e ec f2 7d 4e 4e 07 31 19 10 07 01 13 51 25 09 01 00 00 00 00 33 0400 00 5A 00 00 00 EB 0D 00 00 64 EB package org.thethingsnetwork.main.java.org.thethingsnetwork.util.security ; import java.util.Base64 ; import j... | Java . LoraWan package decription . AES-128 |
Java | In this java assignment we have a for loop that reads through a text file we use in this program , and we are supposed to replace it with a stream . Here is part of the program and what we are supposed to replace : I have tried this and I ca n't seem to figure out anything else : | import java.io.FileNotFoundException ; import java.util.List ; import java.util.Map ; import java.util.TreeMap ; public class FrequentWords { public static void main ( String [ ] args ) throws FileNotFoundException { String filename = `` SophieSallyJack.txt '' ; if ( args.length == 1 ) { filename = args [ 0 ] ; } Map <... | Using Java 8 Stream to replace for loop and populate a Map |
Java | Say I have this resource : Should I write tests that confirm that certain ( test ) users get a response from the endpoints , and certain users do n't ? And if so : How can I write those tests ? I 've tried something like this : but I 'm not sure how to actually test the function of the @ RequiresRoles-annotation . I 'v... | import javax.ws.rs.GET ; import javax.ws.rs.Path ; import javax.ws.rs.PathParam ; import javax.ws.rs.Produces ; import javax.ws.rs.core.MediaType ; import javax.ws.rs.core.Response ; import org.apache.shiro.authz.annotation.RequiresAuthentication ; import org.apache.shiro.authz.annotation.RequiresRoles ; import io.swag... | Shiro : How to write a test for an endpoint protected with @ RequiresRoles ? |
Java | I am using OrientDB in an embedded situation in Java . I am creating the database and classes in my application and inserting the data . When I go to view the data through the console , I can see the classes in the database , along with the correct number of rows in the classes . However when I try to browse the data i... | private void createNewOrientDatabase ( ) { String dbPath = `` plocal : ./db/test '' ; orientDatabase = new ODatabaseDocumentTx ( dbPath ) .create ( ) ; } public void createClasses ( Table t ) { if ( orientDatabase.getMetadata ( ) .getSchema ( ) .getClass ( t.getName ( ) ) == null ) { orientDatabase.getMetadata ( ) .get... | OrientDB error when trying to browse a class via console |
Java | I know there are many questions on the subject even a very recent one but I still ca n't work my head around one thing . Consider the following functional interface : And this implementation : If I look at these threads 1 and 2 , I expect the following code to output `` Bob '' and not throw a NullPointerException becau... | @ FunctionalInterfaceinterface PersonInterface { String getName ( ) ; } class Person implements PersonInterface { private String name ; public Person ( String name ) { this.name = name ; } public String getName ( ) { return name ; } public void setName ( String name ) { this.name = name ; } } Person p = new Person ( ``... | Method reference does not always seem to capture instance |
Java | I 'm brushing up on my Java have been asked this question in an exercise . How could the following result in a deadlock ? My guess is that if methodB calls methodA while it has the Thread.sleep function going , the two method would start cascading and cause an indefinite sleep ? Thoughts ? | private Object sync = new Object ( ) ; public void methodA ( ) throws InterruptedException { synchronized ( this.sync ) { Thread.sleep ( 1000 ) ; } } public void methodB ( ) throws InterruptedException { synchronized ( this.sync ) { this.methodA ( ) ; } } | How can this cause a deadlock ? |
Java | I 've been doing some Java Streams manipulation , and of course it does n't like my code and is refusing to provide useful error messages . ( For reference , I have no problems whatsoever with C # and Linq , so I understand conceptually everything I 'm trying to do . ) So I started digging into adding the explicit gene... | public static < T > Collector < T , ? , List < T > > toList ( ) { return new Collectors.CollectorImpl < > ( ( Supplier < List < T > > ) ArrayList : :new , List : :add , ( left , right ) - > { left.addAll ( right ) ; return left ; } , Collectors.CH_ID ) ; } Wrong number of type arguments : 2 ; required : 3 Incompatible ... | Why does Java Collector.toList ( ) require a wildcard type placeholder in its return type ? |
Java | I 've created a utility that combines zip file archives into a single archive . In doing so , I originally had the following method ( see this question for some background on ExceptionWrapper ) : Here is the code for ExceptionWrapper.wrapConsumer and ConsumerWrapperThis results in the compilation errors : However , the... | private void addFile ( File f , final ZipOutputStream out , final Set < String > entryNames ) { ZipFile source = getZipFileFromFile ( f ) ; source.stream ( ) .forEach ( ExceptionWrapper.wrapConsumer ( e - > addEntryContent ( out , source , e , entryNames ) ) ) ; } public static < T > Consumer < T > wrapConsumer ( Consu... | Why compile fails inlining Consumer < ZipEntry > but works externally ? |
Java | This is a follow-up question to some previous questions about String initialization in Java.After some small tests in Java , I 'm facing the following question : Why can I execute this statementwhen str2 a String object initialized to null ( String str2 = null ; ) but I can not call the method toString ( ) on str2 ? Th... | String concatenated = str2 + `` a_literal_string '' ; | Concatenation of a null String object and a string literal |
Java | I use to the advice given by Joshua Bloch 's Effective Java , Item 52 : Refer to objects by their interfaces.However , in most of the sample code comes with Android , I realize the following code is quite common.I understand this is due to performance optimization purpose , as the following code will be slower.However ... | private ArrayList < Integer > mPhotos = new ArrayList < Integer > ( ) ; private List < Integer > mPhotos = new ArrayList < Integer > ( ) ; | Should we refer to objects by their interfaces in Android platform |
Java | I need your advice . For a start I would like to describe preconditions.I have some third party Java objects with default java.lang.Object 's hashCode ( ) and equals ( ) implementation . Comparable interface is not implemented . The size is insignificant.I need to store such objects for some time in memory . I will rea... | import java.util.Comparator ; public class ObjectComparator implements Comparator < Object > { public int compare ( Object o1 , Object o2 ) { return o1.hashCode ( ) - o2.hashCode ( ) ; } } | Concurrent collection to 50/50 read/write |
Java | The application I 'm developing needs to receive events from a SAP Contact Center for interactions happening on phones . Events such as IciEvent_phoneCallChanged , for example . I am already able to receive user events by sending a subscription request . I am sending a subscription request for the Container interface a... | containerSubscriber = new ContainerSubscriber ( `` urn : IciContainerInterface '' , `` IciContainerService '' , `` http : // < client_address > /oii/icicontainerservice.asmx ? wsdl '' ) ; IciContainerServiceSoap port = containerSubscriber.getPort ( ) ; com.dvsoft.sap.containerici.client.SubscribeResponseResponse respon... | How to receive phone call events |
Java | I 'm wondering why this code does n't compile : Whereas this code does : I think the priority is for pre and then post decrements then the subtraction should be applied . | int x=-3 ; System.out.println ( x -- -- -x ) ; int x=-3 ; System.out.println ( x -- - -- x ) ; | Java expression compilation error |
Java | I am new in cloud boost.I am using cloud boost in my android application for chat feature.We have integrated cloud boost SDK on our server.Now I want to use cloud boost in my android app with my server URL but I am not able to init CloupApp with custom URL . I have also tried following method but it not work.Can someon... | CloudSocket.init ( cloudUrl ) ; CloudApp.init ( appId , appKey ) ; | How to set up cloudboost in android app with my own server ? |
Java | I have been trying to understand the concept and rationale behind the lower bounded wildcard in Java Generics . I can understand the reasoning behind the upper bounded wildcard being read only and where and how it can be used . I am still not able to get a grasp of the lower bounded wildcard . I have a set of classes w... | Automobile - Bus - Minibus - Doubledecker - Electricbus - Car - Sedan - Hatchback - Coupe - Truck - Minivan - Pickuptruck - Suv - Fullsuv - Midsuv import java.util.ArrayList ; import java.util.List ; public class Garage { public static void main ( String [ ] args ) { List < ? super Suv > list = null ; Suv s = new Suv (... | Lower bounded wildcard |
Java | I have created an inner class in an inner class : I have been surprised that java allows the InnerInnerClass to access directly the EnclosingClass . How is this code implemented internally by Java ? The InnerInnerClass keeps two pointers ( one on the InnerClass and the other on the EnclosingClass ) or the InnerInnerCla... | public class EnclosingClass { public class InnerClass { private EnclosingClass getEnclosing ( ) { return EnclosingClass.this ; } public class InnerInnerClass { private InnerClass getEnclosing ( ) { return InnerClass.this ; } private EnclosingClass getEnclosingOfEnclosing ( ) { return EnclosingClass.this ; } } } } | How java implement the access to the enclosing class from an inner inner class ? |
Java | I 'm currently learning Java online and am confused about the following code and what one of the elements in the array is evaluating to : I am looking at a [ 3 ] and the number that this evaluates to , and when I am debugging the code , my IDE is showing that a [ a [ i ] ] is evaluating to 9 , which is where I 'm a bit... | int [ ] a = new int [ ] { 9 , 8 , 3 , 1 , 5 , 4 } ; for ( int i = 0 ; i < a.length ; i++ ) { if ( a [ i ] % 2 == 0 ) { a [ i ] += 1 ; } else if ( a [ i ] < a.length ) { a [ i ] += a [ a [ i ] ] ; } } | Nested array references |
Java | Given this Java code , this outputs 0 and 4 : And with this identical C # code , this outputs 4 and 4using System ; Though I figure out that the output should be 4 and 4 on Java , but the answer is actually 0 and 4 on Java . Then I tried it in C # , the answer is 4 and 4What gives ? Java rationale is , during construct... | class A { A ( ) { print ( ) ; } void print ( ) { System.out.println ( `` A '' ) ; } } class B extends A { int i = Math.round ( 3.5f ) ; public static void main ( String [ ] args ) { A a = new B ( ) ; a.print ( ) ; } void print ( ) { System.out.println ( i ) ; } } class A { internal A ( ) { print ( ) ; } virtual interna... | Java constructor is not so intuitive . Or perhaps it 's not Java , it 's C # that is not intuitive |
Java | I am a reasonably experiences hobby programmer , and I have good familiarity with C++ , D , Java , C # and others.With the exception of Go , almost every language requires me to explicitly state that I am implementing an interface . This is borderline ridiculous , since we today have compilers for languages like Haskel... | interface ITest { void Test ( ) ; } class Test { void Test ( ) { } } void main ( ) { ITest x ; x = new Test ; } | What other languages support Go 's style of interfacing without explicit declaration ? |
Java | I am reading LinkedHashMap source code in JDK 11 and I found a piece of dead code ( I 'm not sure ) As we all know , LinkedHashMap use a doubly linked list to preserve the order of all the elements.It has a member called accessOrderBy default it is false , but if it is set to true , everytime you run get , it will move... | final boolean accessOrder ; //if accessOrder were set as true , after you visit node e , if e is not the end node of the linked list , //it will move the node to the end of the linkedlist . void afterNodeAccess ( Node < K , V > e ) { LinkedHashMap.Entry < K , V > last ; if ( accessOrder & & ( last = tail ) ! = e ) { //... | Is it dead code in LinkedHashMap in JDK11? |
Java | I 'm trying to initialize a HashMap using rJava with type < String , Double > but do not understand how to accomplish this using the rJava interface . I am basically looking for the equivalent ofbut using rJava instead . I can easily produce a HashMap < String , String > as the following example shows , but naturally c... | HashMap < String , Double > x = new HashMap < String , Double > ( ) ; library ( rJava ) .jinit ( ) # this works but gives me a < String , String > hashmapx < - .jnew ( `` java/util/HashMap '' ) .jrcall ( x , `` put '' , `` a '' , `` 1 '' ) x # > [ 1 ] `` Java-Object { { a=1 } } '' # failing example of what I 'd like to... | Initializing a HashMap < String , Double > through rJava |
Java | I profiled my code and found that my program spent roughly 85 % of the time executing this particular recursive function . The function aims to calculate the probability of reaching a set of states in a markov chain , given an initial position ( x , y ) . I was once told that 99 % of recursive functions could be replac... | private static boolean condition ( int n ) { int i = 0 ; while ( n > = i ) { if ( n == i*4 || n == ( i*4 - 1 ) ) return true ; i++ ; } return false ; } public static double recursiveVal ( int x , int y , double A , double B ) { if ( x > 6 & & ( x- 2 > = y ) ) { return 1 ; } if ( y > 6 & & ( y- 2 > = x ) ) { return 0 ; ... | Recursive function taking ages to run |
Java | I am wondering whether the below code should work in any scenario ? It works in my Android studio but not in some other 's PC . What is making it work for me ? | Object value = attValue.getValue ( ) ; // Returns an Object , might contain an Integer if ( value instanceof Integer ) { if ( mAccount.getValue ( ) ! = value ) { // mAccount.getValue ( ) return int // Do something here } } | Any chance of Object auto casting to Integer ? |
Java | In following question : Possible Spring Boot or Spring Security Memory LeakThe user prints the java objects as follows : What command did the user use to print this info ? Btw , I have added following arguments to my java process.I hope I have phrased the question correctly . | num # instances # bytes class name -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 1 : 395984 32564344 [ C 2 : 388697 9328728 java.lang.String 3 : 61258 5915088 [ B 4 : 100297 4814256 java.util.HashMap 5 : 50892 4478496 org.apache.catalina.session.StandardSession 6 : 58774 3656824 [ Ljava.util.Hash... | how to print java objects memory usage |
Java | After reading Sun 's documentation on Generics I moved to the Q and E section at http : //docs.oracle.com/javase/tutorial/java/generics/QandE/generics-questions.html.For Q8 - Write a generic method to find the maximal element in the range [ begin , end ) of a list.the code I wrote is : and Sun 's answer is : Can someon... | private static < T extends Comparable < T > > T max ( List < T > l , int i , int j ) { List < T > sublist = l.subList ( i , j ) ; System.out.println ( `` Sublist `` +sublist ) ; int c = 0 ; T max = null ; for ( T elem : sublist ) { if ( c == 0 || max.compareTo ( elem ) < 0 ) { max = elem ; } ++c ; } return max ; } publ... | Max element - Sun 's answer VS mine |
Java | I 'm trying to remove all the entry of which the value is null . The code is : My question is iterator is bind to map.values , why it can remove the whole entry ? | Map < String , String > map = new HashMap < > ( ) ; map.put ( `` one '' , null ) ; map.put ( `` two '' , null ) ; map.put ( `` three '' , `` THREE '' ) ; Iterator iterator = map.values ( ) .iterator ( ) ; while ( iterator.hasNext ( ) ) { if ( iterator.next ( ) == null ) { iterator.remove ( ) ; } } for ( Map.Entry < Str... | Why the iterator on map.vaules can be used to remove HashMap # Entry ? |
Java | I have a question regarding the Java Memory Model . Given the following example : acquire and release can be any synchronizes-with edge ( lock , unlock , start thread , join thread , detect thread interruption , volatile-write , volatile-read , etc . ) Is it guaranteed that action 3 ca n't be moved before the acquire a... | action 1action 2synchronized ( monitorObject ) { //acquire action 3 } //releaseaction 4 /* 1 */ synchronized ( syncA ) { /* 2 */ x = 1 ; /* 3 */ } /* 4 */ y = 0 ; /* 5 */ synchronized ( syncB ) { /* 6 */ y = 1 ; /* 7 */ } y = 0 ; synchronized ( syncB ) { y = 1 ; synchronized ( syncA ) { x = 1 ; } } | Are synchronizes-with edegs compiler re-ordering barriers in both directions ? |
Java | I have a matrix that implements John Conway 's life simulator in which every cell represents either life or lack of it.Every life cycle follows these rules : Any live cell with fewer than two live neighbors dies , as if caused by under-population.Any live cell with two or three live neighbors lives on to the next gener... | import java.util.Random ; public class LifeMatrix { Cell [ ] [ ] mat ; public Action currentAction = Action.WAIT_FOR_COMMAND ; public Action changeAction ; public enum Action { CHECK_NEIGHBORS_STATE , CHANGE_LIFE_STATE , WAIT_FOR_COMMAND } // creates a life matrix with all cells alive or dead or random between dead or ... | Designing a multi-thread matrix in Java |
Java | I have a SpringBoot app.I have created this test : whereand local configuration.properties : but when I run the test . I got this error : Caused by : org.springframework.beans.factory.NoSuchBeanDefinitionException : Nobean named 'entityManagerFactory ' availableI also tried with : but then I have the error : Caused by ... | @ ContextConfiguration ( classes= { TestConfig.class } ) @ RunWith ( SpringRunner.class ) @ SpringBootTestpublic class SuncionServiceITTest { @ Test public void should_Find_2 ( ) { // TODO } } @ Configuration @ EnableJpaRepositories ( basePackages = `` com.plats.bruts.repository '' ) @ PropertySource ( `` local-configu... | SpringBoot : Configuring Spring DataSource for Tests |
Java | I have an array list of apps , I have a directory which will only contain jar files ( I am using reflection to access these jar files in my platform ) . I want to loop through all of the files inside the directory , find all of the jar files and then check that they are part of the array list of verified apps and from ... | App.getAppStore ( ) .stream ( ) .filter ( o - > { File [ ] listOfFiles = new File ( `` C : /Temp/MyApps/ '' ) .listFiles ( ) ; Object [ ] foo = Arrays.stream ( listOfFiles ) .filter ( x - > x.getName ( ) .contains ( o.getName ( ) ) ) .toArray ( ) ; return true ; } ) .toArray ( ) ; ArrayList < Application > verifiedApps... | How to check two arrays against each other using streams |
Java | Suppose I have an Animal interface and particular classes implementing it Cat and Dog . Right at the entry to the program , there 's this : I 'd like to have the choice parameter be populated at compile time ( e.g. , during Maven build ) , so that : if I compile with choice == 0 , the Dog class does n't get compiledif ... | if ( choice == 0 ) { Animal A = new Cat ( ) ; } else if ( choice == 1 ) { Animal A = new Dog ( ) ; } | Choose class implementation at compile time |
Java | Given the following code , can someone please explain why the assertion returns true ? Despite having searched around countlessly , I have n't been able to get any appropriate answer for why this might be the case , and what the Java feature ( s ) cause this behaviour and what restrictions / requirements I would have i... | interface X { default int foo ( ) { return 1 ; } String bar ( ) ; } public class Exercise { public static void main ( String [ ] arg ) { X foo1= ( ) - > '' hello '' ; assert ( foo1.bar ( ) ) .equals ( `` hello '' ) ; } } | Java Functional Interfaces and Lambda Expressions |
Java | I do know that loading a file in Java without specifying the encoding to use is platform dependant . But my question is about the text contained in the .java source files themselves : Is the encoding used for those files still relevant once compiled ? For example , if I have a test.java file on Windows which is Cp1252 ... | private String encodingTest = `` Bœuf fûmé '' ; | Java source files - Is encoding still relevant once compiled ? |
Java | I 'm reading about java streams API and I encountered the following here : The operation forEachOrdered processes elements in the order specified by the stream , regardless of whether the stream is executed in serial or parallel . However , when a stream is executed in parallel , the map operation processes elements of... | public class MapOrdering { public static void main ( String [ ] args ) { // TODO Auto-generated method stub List < String > serialStorage = new ArrayList < > ( ) ; System.out.println ( `` Serial stream : '' ) ; int j = 0 ; List < String > listOfIntegers = new ArrayList ( ) ; for ( int i = 0 ; i < 10 ; i++ ) listOfInteg... | does stateful map operation of ordered stream process elements in deterministic way ? |
Java | Before this question is marked as duplicate , please read it . ; ) There are already several questions about coverage tools and such , however this is a bit different than the usual ones ( I hope ) .According to wikipedia there are several different kind of 'coverage ' variations that affect several different aspects o... | public class Dummy { public int a = 0 ; public int b = 0 ; public int c = 0 ; public void doSomething ( ) { a += 5 ; b += 5 ; c = b + 5 ; } } public class DummyTest { @ Test public void testDoSomething ( ) { Dummy dummy = new Dummy ( ) ; dummy.doSomething ( ) ; assertEquals ( 10 , dummy.c ) ; } } | Is there some kind of 'assertion ' coverage tool ( for Java ) ? |
Java | Suppose I have a simple method like this for processing two lists : And suppose I want to call it like this : This wo n't compile , because javac is n't smart enough to figure out I was trying to create two lists of Integers . Instead , I have to write : How should I change the declaration of foo to allow the first ver... | public static < B > void foo ( List < B > list1 , List < B > list2 ) { } foo ( ImmutableList.of ( ) , ImmutableList.of ( 1 ) ) ; foo ( ImmutableList. < Integer > of ( ) , ImmutableList.of ( 1 ) ) ; | Java Generics : Inferring types over two parameters |
Java | I am wondering if there is a way to call .apply ( ) or .get ( ) on a lambda function directly in the same expression it is defined . The question came to mind when I wanted to initialize a variable which could be private , but I can not declare it final because the value is the return value of a function that can throw... | final s = Files.size ( path ) ; // code that uses s s = 0 ; try { s = Files.size ( ) ; } catch ( IOException e ) { } // code that uses s const s = [ ] ( ) { try { return Files.size ( path ) ; } catch ( ... ) { return 0 ; } } ( ) ; final int s = new IntSupplier ( ) { @ Override public int getAsInt ( ) { try { return Fil... | Initialize variable by evaluating lambda directly |
Java | I 've got some classes defined in java , similar to the code below.I 'm trying to access SomeValue through a derived java class , which is allowed in java , but not in kotlin.Is there a way to access the field through the derived class ? | // java file// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -class MyBaseClass { public static final class MyInnerClass { public static int SomeValue = 42 ; } } final class MyDerivedClass extends MyBaseClass { } // kotlin file// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -... | Accessing static inner class defined in Java , through derived class |
Java | Decompiling the .class file of the following for-each loop produces interesting results.Source - Main.java : Result - Main.class : The file was decompiled with IntelliJ IDEA.Why was true assigned to the unused int ? Why was the var3 variable redeclared ? Is this a mistake on behalf of the decompiler ? | public class Main { public static void main ( String [ ] args ) { String [ ] names = new String [ 3 ] ; int var3 = 3 ; for ( String name : names ) { System.out.println ( name ) ; } } } //// Source code recreated from a .class file by IntelliJ IDEA// ( powered by Fernflower decompiler ) //public class Main { public Main... | Decompiling for-each loop |
Java | |= I 'm curious to learn about this operator , I 've seen this notation used while setting flags in Java.for example : Does it perform some kind of bit manipulation ? What does this mark exactly do ? Are there any other well known signs similar to this ? | notification.flags |= Notification.FLAG_AUTO_CANCEL ; | What does this sign exactly mean ? |= |
Java | Alright , so Java does n't allow the following : This makes sense -- after all , what 's the point of generics if you 're just gon na box/unbox everything anyways ? What 's weird , is Java does allow this : Granted , this actually accomplishes more , though at some point , there would be a cast to get whatever Bar is w... | Foo < ? > hello = new Foo < ? > ( ) ; Foo < Bar < ? > > howdy = new Foo < Bar < ? > > ( ) ; Foo < ? extends Mal > bonjour = new Foo < ? extends Mal > ( ) ; | Generics and Wildcards : Java likes `` new Foo < Bar < ? > > '' |
Java | I have been experimenting with JNI recently , in order to port some existing C++ libraries . As part of my testing I created a simple 'helloworld ' program . I am calling a simple native function in C++ , that just prints messages . I am a bit curious about some behavior I have observed while executing the program - it... | public static void main ( String [ ] args ) { HelloWorld app = new HelloWorld ( ) ; System.out.println ( `` say '' ) ; app.print ( ) ; System.out.println ( `` what '' ) ; app.print ( ) ; } saywhathola , world ! hola , world ! Java_HelloWorld_print ( JNIEnv *env , jobject obj ) { printf ( `` hola , world ! \n '' ) ; ret... | JNI calls interleaved with regular Java calls - what is the execution order ? |
Java | I have below Strings Here I do n't know why concatenation of Strings , one created in the constant pool , and the other in the heap , results in creating the new String in the heap . I do n't know the reason , why does it happen ? | String str1 = `` Abc '' ; //created in constant poolString str2 = `` XYZ '' ; //created in constant poolString str3 = str1 + str2 ; //created in constant poolString str4 = new String ( `` PQR '' ) ; //created in heapString str5 = str1.concat ( str4 ) ; //created in heap String str6 = str1 + str4 ; //created in heap | Why concatenation of String object and string literal is created in heap ? |
Java | Ok so from my stand point my code is pretty decent enough to get a passing grade but I am having trouble adding a simple refresh/shuffle button . NOT USING the aids of JOptionPane.Eclipse doesnt seem to recognize that I have created the button which doesnt make sense at all for me because its telling me something about... | import javafx.application.Application ; import javafx.scene.Scene ; import javafx.scene.layout.BorderPane ; import javafx.scene.layout.HBox ; import javafx.scene.layout.Pane ; import javafx.geometry.Insets ; import javafx.geometry.Pos ; import javafx.stage.Stage ; import javafx.scene.image.Image ; import javafx.scene.i... | Adding a Simple Button in java , but java is not allowing me to |
Java | There are texts on my static layout , the layout is an item in a Recyclerview . The touch event of the Recyclerview class controls the pinch zoom to the text with ScaleGestureDetector . The zooming senario is , when the user action move the screen of Recyclerview , getting the screenshot of the recyclerview and display... | private ScaleListener mScaleListener ; private ScaleGestureDetector mScaleGestureDetector ; @ Overridepublic boolean onTouchEvent ( MotionEvent event ) { int action = event.getAction ( ) & MotionEvent.ACTION_MASK ; if ( event.getPointerCount ( ) == 2 & & ( action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTI... | Android restrict the size when text sizing with pinch zoom and temp image |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.