lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | In my JavaFx application , I want to call a method when the main frame gains focus . However , I want to react only in the case where the focus was outside my application and came back ( not when a dialog closes for example ) .When the application was in Swing , I could use the method ( which corresponds to the element... | FocusEvent.getOppositeComponent primaryStage.addEventFilter ( Event.ANY , e - > System.out.println ( `` event `` + e ) ) ; | Equivalent of FocusEvent.getOppositeComponent in JavaFx |
Java | Consider the below scenario : Code:1Commenting the code as below , there are no errors and following output has been displayed.Code:2Output-If the execution is based on the order in which static variables or blocks have been written.why compilation error is not thrown for the initialization ( b=5 ) as shown in Code:2.A... | public class StaticDemo { static { b=5 ; System.out.println ( `` Static B : '' +b ) ; /*Compilation error : '' Can not reference a field before it is defined '' */ } static int b ; static { System.out.println ( `` B : '' +b ) ; } public static void main ( String [ ] args ) { } } public class StaticDemo { static { b=5 ;... | How the order of execution is performed between static variables and blocks ? |
Java | There was a question asked : `` Presented with the integer n , find the 0-based position of the second rightmost zero bit in its binary representation ( it is guaranteed that such a bit exists ) , counting from right to left . Return the value of 2position_of_the_found_bit . `` I had written below solution which works ... | int secondRightmostZeroBit ( int n ) { return ( int ) Math.pow ( 2 , Integer.toBinaryString ( n ) .length ( ) -1-Integer.toBinaryString ( n ) .lastIndexOf ( ' 0 ' , Integer.toBinaryString ( n ) .lastIndexOf ( ' 0 ' ) -1 ) ) ; } int secondRightmostZeroBit ( int n ) { return ~ ( n| ( n+1 ) ) & ( ( n| ( n+1 ) ) +1 ) ; } | How bit manipulation works ? |
Java | My class GraphicButton.java creates a custom JButton with a certain text and font and a rectangular border . My problem is that there is some extra space between the last character in the string and the end of the border that I would like to remove.Here is what an instance of a GraphicButton looks like with the string ... | public class GraphicButton extends JButton { private static final long serialVersionUID = 1L ; //Fields private String text ; private Font font ; //Constructor public GraphicButton ( String text , Font font ) { super ( text ) ; this.text = text ; this.font = font ; //Setting preferred size here . this.setPreferredSize ... | How to remove the space from the end of a string displayed with Graphics in Java ? |
Java | I have the following codeI am expecting the output to be false , true , true , false and true.However , the output is false , true , false , false , false.I am looking for how the output is false for the 3rd and 5th case . What is the behavior of HashMap containsKey ? Why is the output false even though the Key object ... | import java.util.HashMap ; import java.util.Map ; import java.util.Objects ; public class Person { private String name ; private long birthTime ; @ Override public int hashCode ( ) { return Objects.hash ( name , birthTime ) ; } @ Override public boolean equals ( Object obj ) { if ( this == obj ) { return true ; } if ( ... | Java HashMap containsKey |
Java | What do parenthesis do in Java other than type casting.I 've seen them used in a number of confusing situations , here 's one from the Java Tutorials : I only know only two uses for parenthesis , calls , and grouping expressions . I have searched the web but I ca n't find any more information.In the example above I kno... | //convert strings to numbersfloat a = ( Float.valueOf ( args [ 0 ] ) ) .floatValue ( ) ; float b = ( Float.valueOf ( args [ 1 ] ) ) .floatValue ( ) ; | Unexplained parenthesise in Java |
Java | This is the line where crash occursThe values I got by catching the Exception and dumping the variables , The variable TreeMap < Long , Long > offsets is parsed from a json file by using the code below.After examining the code many times , I ca n't identify a situation where this code can throw a Any ideas ? Updates 1 ... | offsetDuration = duration - ( offsets.containsKey ( freq ) ? offsets.get ( freq ) : 0l ) ; long offsetDuration = 0 ; long duration = 391144 ; TreeMap < Long , Long > offsets = { 0=4024974.0 , 1036800=8588.0 , 1190400=88216.0 , 1267200=49763.0 , 1497600=87476.0 , 1574400=7469.0 , 1728000=54553.0 , 1958400=60512.0 , 2265... | Werid ClassCastException in TreeMap.containsKey ( ) |
Java | I have the following codes : What I want its output format would be : However , given the above codes , it results to : How do I get rid of the delimiter , as the first character in every line ? Thank you . | StringJoiner stringJoiner = new StringJoiner ( `` , '' ) ; List < Person > persons = Arrays.asList ( new Person ( `` Juan '' , `` Dela Cruz '' ) , new Person ( `` Maria '' , `` Magdalena '' ) , new Person ( `` Mario '' , `` Santos '' ) ) ; persons.forEach ( person - > { stringJoiner.add ( person.getFirstName ( ) ) .add... | StringJoiner remove delimeter from first position for every line |
Java | I 'm working a project to replace a Resource Management system ( QuickTime Resource Manager on Mac and Windows ) that has been deprecated and I have been using the current model that Qt uses where data is retrieved from the resource file using a string key.For example , I may have an image in my resource file , `` Hung... | image = GetImageResource ( `` BearPlugin/Images/HungryBear.png '' ) ; oldActiveResourceFile = GetActiveResourceFile ( ) ; // think of a stack of resource filesSetActiveResourceFile ( `` BearPlugin '' ) ; image = GetImageResource ( 1 ) ; // Perhaps other resources are retrieved and other functions called// Possibly intr... | Why are string identifiers used to access resource data ? |
Java | I am new to python recently . Previously all my programming knowledge are limited on Java . So here I have a question about object variables in Python . I know that object variables in Python share on class instances . For example.So my questions is that how many memory copies does A.list have ? only 1 or just as many ... | class A : list= [ ] y=A ( ) x=A ( ) x.list.append ( 1 ) y.list.append ( 2 ) x.list.append ( 3 ) y.list.append ( 4 ) print x.list [ 1,2,3,4 ] print y.list [ 1,2,3,4 ] | How many memory copies do object variables in Python have ? |
Java | I have a hashmap which has key value pair of String and object . It is the conversion of something like below json . But , I am not converting to map . I have just that map . If this may has key and value , I have to do write some logic based on that value . I implemented as below : Now , I wanted to avoid the nested i... | { `` test1 '' : { `` test2 '' : { `` test3 '' : { `` key '' : `` value '' } , `` somefields12 '' : `` some value2 '' } , `` somefields '' : `` some value '' } } if ( map.containsKey ( `` test1 '' ) ) { final HashMap < String , Object > test1 = ( HashMap < String , Object > ) map.get ( `` test1 '' ) ; if ( test1.contain... | avoid nested if in hashmap which is created from complex json |
Java | I would like to write a program in Java which , given an array , finds the sum of all the numbers in the array - with an exception ! Since the number 13 is very unlucky , I propose that we shall completely exclude the number 13 , and the number directly after 13 , if it exists , from the total sum.The program , which I... | public int sum13 ( int [ ] nums ) { int sum = 0 ; for ( int i = 0 ; i < nums.length ; i++ ) { // we start by adding all the non-13s to the sum if ( nums [ i ] ! = 13 ) sum += nums [ i ] ; } // now we go back and remove all the non-13s directly after a 13 for ( int j = 0 ; j < nums.length ; j++ ) { // the outermost loop... | Finding the sum of numbers in an array - excluding the number 13 and the number directly after it |
Java | The author of java 8 in action writes this class : Then he talks about what different values in Characteristic enum mean . And then he explains why this collector he wrote is IDENTITY_FINISH and CONCURRENT and not UNORDERED , saying : The ToListCollector developed so far is IDENTITY_FINISH , because the List used to ac... | class ToListCollector < T > implements Collector < T , List < T > , List < T > > { @ Override public Supplier < List < T > > supplier ( ) { return ArrayList : :new ; } @ Override public BiConsumer < List < T > , T > accumulator ( ) { return List : :add ; } @ Override public BinaryOperator < List < T > > combiner ( ) { ... | Confusion about Characteristics.UNORDERED in Java 8 in action book |
Java | I code a mini Android game scenario inspired by Space Invaders and Moon Patrol . It is possible to shoot an alien horizontally ( see above ) . It is also possible to shoot an alien vertically ( see below ) . But adding aliens does n't `` scale '' , it will be very difficult to add for instance 15 aliens moving with res... | import android.content.Context ; import android.graphics.Bitmap ; import android.graphics.BitmapFactory ; import android.graphics.Canvas ; import android.graphics.Color ; import android.graphics.Paint ; import android.graphics.Rect ; import android.support.v4.view.MotionEventCompat ; import android.util.Log ; import an... | Improve movement of space aliens |
Java | Sorry guys I am new to Java and I have an issue with my code . I have read through the threads and have seen many examples regarding this specific error ( java.lang.NoSuchMethodError : main Exception in thread `` main '' ) . I just cant seem to wrap my head around where I would add ( static void main ( String [ ] args ... | public class Employee { String name ; String department ; double hourlyRate ; Employee ( String name , String department , double hourlyRate ) { this.name = name ; this.department = department ; this.hourlyRate = hourlyRate ; } public void setDepartment ( String department ) { this.department = department ; } public vo... | Having trouble with MAIN please advise |
Java | I have a string which contains a series of bits ( like `` 01100011 '' ) and some Integers in a while loop . For example : Now I want a nice fastest way to convert string and int to byte array . Until now , what I have done is convert int to String and then apply the getBytes ( ) method on both strings . However , it is... | while ( true ) { int i = 100 ; String str = Input Series of bits // Convert i and str to byte array } | Java Byte Array conversion Issue |
Java | I have code that consumes a large number ( millions currently , eventually billions ) of relatively short ( 5-100 elements ) arrays of random numbers and does some not-very-strenuous math with them . Random numbers being , well , random , ideally I 'd like to generate them on multiple cores , since random number genera... | for ( int i=0 ; i < 1000000 ; i++ ) { for ( RealVector d : data ) { while ( ! converged ) { double [ ] shortVec = new double [ 5 ] ; for ( int i=0 ; i < 5 ; i++ ) shortVec [ i ] =rng.nextGaussian ( ) ; double [ ] longerVec = new double [ 50 ] ; for ( int i=0 ; i < 50 ; i++ ) longerVec [ i ] =rng.nextGaussian ( ) ; /*Do... | High-performance buffering for a stream of rands |
Java | I 'm trying to create a program to compare the amount of time it takes various haskell scripts to run , which will later be used to create graphs and displayed in a GUI . I 've tried to create said GUI using Haskell libraries but I have n't had much luck , especially since I 'm having trouble finding up to date GUI lib... | import java.io . * ; public class TestExec { public static void main ( String [ ] args ) { try { Process p = Runtime.getRuntime ( ) .exec ( `` ghc test.hs 2 2 '' ) ; BufferedReader in = new BufferedReader ( new InputStreamReader ( p.getInputStream ( ) ) ) ; String line = null ; while ( ( line = in.readLine ( ) ) ! = nu... | Getting the results of a Haskell script from Java |
Java | I have multiple time series : Frustratingly in my dataset there is n't always a matching date in both series . For scenarios where there is one missing I want to use the last available date ( or 0 if there isnt one ) .e.g for 2017-01-03 I would use y=3 and x=1 ( from the date before ) to get output = 3 + 1 = 4I have ea... | x| date | value || 2017-01-01 | 1 || 2017-01-05 | 4 || ... | ... | y| date | value || 2017-01-03 | 3 || 2017-01-04 | 2 || ... | ... | class Timeseries { List < Event > x = ... ; } class Event { LocalDate date ; Double value ; } List < TimeSeries > allSeries = ... Map < LocalDate , Double > byDate = allSeries.stream ( )... | Java : Sum two or more time series |
Java | I 'm learning Java in school right now and our latest topic are sort algorithms in Java . The one that I 'm trying to understand is quicksort.To understand how that algorithm sorts numbers in an array I decided to go through my code step for step in the Eclipse debugger window.Now there was one step that I can not comp... | public class QSort { public static void quickSort ( int [ ] arr , int left , int right ) { int i = left ; int j = right ; int temp ; int pivot = arr [ ( left+right ) /2 ] ; System.out.println ( `` \n\nleft = `` + left + `` \tright = `` + right ) ; System.out.println ( `` Pivot is : `` + pivot + `` ( `` + ( left+right )... | Java Quicksort why / where do the values change ? |
Java | I want to publish or advertise my device name over WiFi , which is variable and can be changed by user.For example , Take a file transfer application Xender . We can see the device name set by users on screen when we select receive option in the app . Here is screen shot.You can see in the image that name shah.kaushal ... | @ Overrideprotected Void doInBackground ( Void ... voids ) { System.out.println ( `` array list '' ) ; ArrayList < File > files = new ArrayList < > ( ) ; System.out.println ( `` about to create . `` ) ; files.add ( new File ( wholePath ) ) ; System.out.println ( `` file created.. '' ) ; try { //Receiving IP addresses w... | How to publish device name ( Variable ) over WiFi , as some File transfer applications do ? |
Java | Is it really possible to view partially constructed object in the thread created in the constructor because of the lack of synchronization and the leaking this instance ? Except for the case when there is a child class , of course , or we are doing implicit construction with clone or something like that - so let 's sup... | final class SomeClass { public ImportantData data = null ; public Thread t = null ; public SomeClass ( ImportantData d ) { t = new MyOperationThread ( ) ; // t.start ( ) ; // Footnote 1 data = d ; t.start ( ) ; // Footnote 2 } } | Does happens before Program order rule work in constructors ? |
Java | I have a temperature record something like thisI have to parse this into a POJO and calculate the average delta as per the following problem statement : Use the Streams API to calculate the average annual temperature delta for each country . To calculate delta the average temperature in 1900 would be subtracted from th... | dt |AverageTemperature |AverageTemperatureUncertainty|City |Country |Latitude|Longitude -- -- -- -- -- + -- -- -- -- -- -- -- -- -- -+ -- -- -- -- -- -- -- -- -- -- -- -- -- -- -+ -- -- -- -+ -- -- -- -- + -- -- -- -- + -- -- -- -- -1963-01-01|-5.417000000000002 |0.5 |Karachi|Pakistan|57.05N |10.33E 1963-02-01|-4.76500... | Java 8 Streams multiple grouping By |
Java | I have an issue which I hope I will solve by writing this question but if not I will post and see if anyone can help.I am using a client library ( which is poorly written I feel ) to interact with a real time chat server that utilises COMET style long-polling over HTTP . I 'm having issues with cancelling the long-poll... | doLongPoll ( ) { while ( true ) } //IF channel field boolean unsubscribe == TRUE , if so BREAK ; //perform GET request ( and store channel HTTPClient used for this call ) //remove HTTPClient used for this call //IF channel field boolean unsubscribe == true , if so BREAK ; //IF connection problem sleep ( 1500 ) then CON... | Concurrency issue for cancellation of long-poll loop |
Java | I am facing this problem for 2 hours.The problem is I have other classes that are working well . I do n't know why this error is happening for the current class.But the code works for other tables ( other classes ) .It was working so fine until today . Is there anyone that faced this problem before ? I got this line be... | org.hibernate.exception.JDBCConnectionException : unable to obtain isolated JDBC connectionCaused by : java.sql.SQLTransientConnectionException : HikariPool-1 - Connection is not available , request timed out after 351ms . 2020-03-13 13:52:25,392 [ main ] WARN com.zaxxer.hikari.HikariConfig -ScraperPool - idleTimeout i... | Unable to obtain isolated JDBC connection : org.hibernate.exception.JDBCConnectionException |
Java | I have a problem using JXSE.Let 's say i have a rendezVous peer and an Edge peer , not on the same local network.The rendezVous peer create a peerGroup `` test '' , and publish an advertisement in this group with the name `` test advertisement '' Let 's say i 'm sure than my EdgePeer is connected to the rendezVous peer... | public void addGroup ( final String name ) { ModuleImplAdvertisement mAdv = null ; PeerGroup group = null ; temp = null ; defaultGroup.getDiscoveryService ( ) .getRemoteAdvertisements ( null , DiscoveryService.GROUP , `` Name '' , name , 1 , new DiscoveryListener ( ) { @ Override public void discoveryEvent ( DiscoveryE... | Join existing PeerGroup in JXTA/JXSE |
Java | I was testing some Java8 streams API codes , but i ca n't figure out what is happening with this one.I was thinking about ParallelStream and how this works and i made some comparisons.Two different methods that do a big iteration adding 32.768.000 BigDecimals , one using ParallelStream , other using normal iteration . ... | private static void sumWithParallelStream ( ) { BigDecimal [ ] list = new BigDecimal [ 32_768_000 ] ; BigDecimal total = BigDecimal.ZERO ; for ( int i = 0 ; i < 32_768_000 ; i++ ) { list [ i ] = new BigDecimal ( i ) ; } total = Arrays.asList ( list ) .parallelStream ( ) .reduce ( BigDecimal.ZERO , BigDecimal : :add ) ;... | Java8 streams strange behavior |
Java | Possible Duplicate : Questions about Java 's String pool Recently I read a java article and found the following statement `` improved the String pooling technology in java 6 onward '' . One of the example that they have mentioned as followsNumber of objects created by above example is = 1Here I am little confused , eve... | String one = `` one '' ; String two = new String ( `` one '' ) ; | How many string objects will be created by JVM version 1.6 |
Java | I 'm coming from Python , and trying to understand how lambda expressions work differently in Java . In Python , you can do stuff like : How can I accomplish something similar in Java ? I have read a bit on Java lambda expressions , and it seems I have to declare an interface first , and I 'm unclear about how and why ... | opdict = { `` + '' : lambda a , b : a+b , `` - '' : lambda a , b : a-b , `` * '' : lambda a , b : a*b , `` / '' : lambda a , b : a/b } sum = opdict [ `` + '' ] ( 5,4 ) Map < String , MathOperation > opMap = new HashMap < String , MathOperation > ( ) { { put ( `` + '' , ( a , b ) - > b+a ) ; put ( `` - '' , ( a , b ) - ... | How to map lambda expressions in Java |
Java | In Android , I can monitor if certain events are triggered through the use of Broadcast Receivers . Are there any tools which let me view ALL events on an android device I am debugging instead of having to add a broadcast receiver to listen to them ? For example , in a Broadcast receiver , I can monitor for a call forw... | START u0 { act=android.intent.action.MAIN cmp=com.android.phone/.GsmUmtsCallForwardOptions } | Monitor All Android Devices events remotely |
Java | Using the code of a question I just answered as an exampleStarting with the string What if we wanted to replace the space after every four-digit number with an @ such that you end up with something like this : How much more efficient is it to use a back-reference rather than a positive lookbehind ( if at all ) ? back-r... | 30-Nov-2012 30-Nov-2012 United Kingdom , 31-Oct-2012 31-Oct-2012 UnitedArab Emirates , 29-Oct-2012 31-Oct-2012 India 30-Nov-2012 @ 30-Nov-2012 @ United Kingdom , 31-Oct-2012 @ 31-Oct-2012 @ UnitedArab Emirates , 29-Oct-2012 @ 31-Oct-2012 @ India inputString.replaceAll ( `` ( \\d { 4 } ) \\s '' , `` $ 1 @ '' ) ; inputSt... | Is it more efficient to use a positive look-behind or a back reference ? |
Java | I have a List of A , To execute filtering I need to map A to B . But once the filtering logic is done I still need A for further operations , So My question is would it be at all possible to achieve this ? One approach I can think of is storing both A and B into a third type , so I have both available , while processin... | List < A > a ; List < B > b = a.stream ( ) .map ( i - > load ( i ) ) .filter ( need A here in addition to b ) | Storing/Reusing intermediate results on a java 8 stream |
Java | andSpecifically , I 'm not clear as to why synchronized is required in the second instance when a synchronized list provides thread-safe access to the list . | List < String > list = new ArrayList < String > ( ) ; list.add ( `` a '' ) ; ... list.add ( `` z '' ) ; synchronized ( list ) { Iterator < String > i = list.iterator ( ) ; while ( i.hasNext ( ) ) { ... } } List < String > list = new ArrayList < String > ( ) ; list.add ( `` a '' ) ; ... list.add ( `` z '' ) ; List < Str... | What is the difference in behavior between these two usages of synchronized on a list |
Java | Given list like : List < String > names = Lists.newArrayList ( `` George '' , `` John '' , `` Paul '' , `` Ringo '' ) I 'd like to transform it to a string like this : George , John , Paul and RingoI can do it with rather clumsy StringBuilder thing like so : Is there a bit more elegant approach ? I do n't mind using a ... | String nameList = names.stream ( ) .collect ( joining ( `` , `` ) ) ; if ( nameList.contains ( `` , '' ) ) { StringBuilder builder = new StringBuilder ( nameList ) ; builder.replace ( nameList.lastIndexOf ( ' , ' ) , nameList.lastIndexOf ( ' , ' ) + 1 , `` and '' ) ; return builder.toString ( ) ; } | How to join items of list , but use a different delimiter for the last item ? |
Java | I just performed a quick experiment in Eclipse.When the method-reference test fails , the trace beginsThere is no reference back to the line on which the method reference is used although the end of the trace ( not shown ) does link back to line with findFirst on.While the lamdba stacktrace beginsWhich correctly identi... | public class StackTractTest { static class Nasty { public Integer toInt ( ) { if ( 1 == 1 ) throw new RuntimeException ( ) ; return 1 ; } } @ Test public void methodReference ( ) { Stream.of ( new Nasty ( ) ) .map ( Nasty : :toInt ) .findFirst ( ) ; } @ Test public void lambda ( ) { Stream.of ( new Nasty ( ) ) .map ( n... | Are stack traces less navigable when using method references vs lambdas ? |
Java | I new to java so bear with me if this is a ridiculously simple question but I am curious about this method call which has { code } being taken in - see code below for an example in the method addSelectionListener . What is the purpose of this ? I have been looking through docs for an explaination but cant seem to find ... | setStatusLine.addSelectionListener ( new SelectionAdapter ( ) { public void widgetSelected ( SelectionEvent e ) { String message = `` I would like to say hello to you . `` ; if ( pressed ) { message = `` Thank you for using me '' ; } setStatusLine ( message ) ; pressed = ! pressed ; } } ) ; | What does that Java construct do ? |
Java | I have a following query where I join tables A , B , and C : C is related to B via C.B_IDB is related to A via B.A_IDI want to retrieve a report , where for each C , I want to retrieve also fields from corresponding B and A.If only a subset of fields is required , a projection and fetching to a POJO ( with required pro... | class CReportDTO { Long c_id ; Long c_field1 ; Long c_bid ; Long b_field1 ; // ... CReportDTO ( Long c_id , Long c_field1 , Long c_bid , Long b_field1 ) { // ... } // .. } public List < CReportDTO > getPendingScheduledDeployments ( ) { return dslContext.select ( C.ID , C.FIELD1 , C.B_ID , B.FIELD1 , B.A_ID A.FIELD1 , A... | JOOQ Howto fetch a result of join into POJO without flattening properties ? |
Java | According to https : //developer.android.com/training/data-storage/room/relationshipsWe can have one-to-many relationshipsIn both entity User and Playlist , we have added a column named sort_keyThe purpose is , when we perform query , we can do the followingWe can control the order of List < UserWithPlaylists > .But , ... | public class UserWithPlaylists { @ Embedded public User user ; @ Relation ( parentColumn = `` userId '' , entityColumn = `` userCreatorId '' ) public List < Playlist > playlists ; } @ Transaction @ Query ( `` SELECT * FROM User '' ) public List < UserWithPlaylists > getUsersWithPlaylists ( ) ; @ Transaction @ Query ( `... | Is there a way to control the order of child entity , when using one-to-many relationhips ? |
Java | I am getting stuck and do n't know where to look further.I have a Java application and one of its functionality is to grab some specific windows ( ie third party application windows ) and host them within itself ( with some extra frames , etc ... ) The whole thing works great , except when my Java application gets kill... | VisibilityNotify event , serial 13 , synthetic NO , window 0x20000a , state VisibilityPartiallyObscuredUnmapNotify event , serial 13 , synthetic NO , window 0x20000a , event 0x20000a , window 0x20000a , from_configure NOReparentNotify event , serial 13 , synthetic NO , window 0x20000a , event 0x20000a , window 0x20000a... | Xlib : Adding a window to the save-set using XAddToChangeSet does not work from Java/JNI |
Java | If I am working with Java streams , and end up with an IntStream of code point numbers for Unicode characters , how can I render a CharSequence such as a String ? I have found a codePoints ( ) method on several interfaces & classes that all generate an IntStream of code points . Yet I have not been able to find any con... | String output = `` input_goes_here '' .codePoints ( ) . ? ? ? ; | Make a string from an IntStream of code point numbers ? |
Java | In a method I have this : I do n't understand why it produces compilation error . The error says that x is not final or effectively-final , so it ca n't be accessed from the lambda body . There is no modification to x after the doLater call , so the value of x is actually already determined when doLater is called.I am ... | int x = 0if ( isA ( ) ) { x = 1 ; } else if ( isB ( ) ) { x = 2 ; } if ( x ! = 0 ) { doLater ( ( ) - > showErrorMessage ( x ) ) ; // compile error here } // no more reference to ' x ' here if ( x ! = 0 ) { final int final_x = x ; doLater ( ( ) - > showErrorMessage ( final_x ) ) ; } | Why is a local variable in Java not considered `` effectively final '' even though nothing modifies it afterwards ? |
Java | Considering the following Java code : And now let 's try to do the same in C # The Java example outputI 'm bI 'm bThe C # version outputI 'm aI 'm bIs there a way to implement class b so that it prints `` I 'm b '' twice ? Please notice i 'm not looking at a way to change a . | public class overriding { public static void main ( String [ ] args ) { b b = new b ( ) ; a a = ( a ) b ; a.Info ( ) ; b.Info ( ) ; } } class a { void Info ( ) { System.out.println ( `` I 'm a '' ) ; } } class b extends a { void Info ( ) { System.out.println ( `` I 'm b '' ) ; } } namespace ConsoleApplication2 { class ... | How to achieve same override experience in C # as in Java ? |
Java | I want to get Bitmap from drawable resource id , I found a solution to decode it using BitmapFactory decode method , but it 's giving null . | Bitmap bitmap = BitmapFactory.decodeResource ( getResources ( ) , R.drawable.ic_tick ) ; | Decoding bitmap from Drawable Resource Id is giving null |
Java | I am programmatically creating textviews with horizontal lines between each view . Using a drawable created programmatically.The problem is , the opacity starts off light and gradually increases for each line.I 've logged the opacity ( getAlpha ( ) ) of the drawable , paint , image view and linear layout at all the poi... | < LinearLayout android : id= '' @ +id/main '' android : layout_width= '' match_parent '' android : layout_height= '' match_parent '' android : orientation= '' vertical '' ... / > < Button android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : onClick= '' PaintDashedLines '' and... | Incremental Opacity , wanting constant opacity Image View with Drawable |
Java | What is the best way to convert Integer array to int array . The simple solution for it would be : In the above example I taken 0 for null values for the fact that default value for objects/wrappers is null and for int is 0.This answer shows how to convert int [ ] to Integer [ ] But I do n't find an easy way to convert... | public int [ ] toPrimitiveInts ( Integer [ ] ints ) { int [ ] primitiveInts = new int [ ints.length ] ; for ( int i = 0 ; i < ints.length ; i++ ) { primitiveInts [ i ] = ints [ i ] == null ? 0 : ints [ i ] ; } return primitiveInts ; } | What is the best way to convert Integer [ ] to int [ ] |
Java | ( I 'll use T to refer to a generic argument here , used in a parameterized class . ) I read that the reason that T ... is a potential source of heap pollution when used as an argument is that the compiler is making an exception to the normal ( no T [ ] arrays allowed ) rule , and allowing T ... ( which is varargs , an... | public class MyClass < T > { public void method ( T ... t ) { System.out.println ( t.getClass ( ) .getName ( ) ) ; //for MyClass < String > , this gives me // [ Ljava.lang.String } | Is T ... ( generics vararg parameter ) really stripped down to Object [ ] at compile time ? |
Java | I am still learning about generics and have a question . Say you had this generic class : All the statements compile but I do n't really know what makes them different . Can anyone give me a brief explanation on those three statements . | public class Test < T > { public static void main ( String [ ] args ) { Test t1 = new Test ( ) ; Test < String > t2 = new Test < String > ( ) ; Test t3 = new Test < String > ( ) ; } } | What is the difference between these statements in a generic class ? |
Java | I want to optimize this solution ( idiomatically ) .I have a string containing only integer values . I want to convert this string into reverse int array . The output should be an integer arrayHere is my solution : Please suggest how to do same . | private static int [ ] stringToReversedIntArray ( String num ) { int [ ] a = new int [ num.length ( ) ] ; for ( int i = 0 ; i < num.length ( ) ; i++ ) { a [ i ] = Integer.parseInt ( num.substring ( i , i + 1 ) ) ; } a = reverse ( a ) ; return a ; } /* * Reverses an int array */private static int [ ] reverse ( int [ ] m... | Convert string to reverse int array |
Java | The following code uses simple arrays of String in Java.In the above code snippet , we can initialize arrays like this.and we can directly pass it to a method without being assigned like this.If it is so , then the following statement should also be valid.but the compiler complains `` Illegal start of expression not a ... | package javaarray ; final public class Main { public void someMethod ( String [ ] str ) { System.out.println ( str [ 0 ] + '' \t '' +str [ 1 ] ) ; } public static void main ( String [ ] args ) { String [ ] str1 = new String [ ] { `` day '' , `` night '' } ; String [ ] str2 = { `` black '' , `` white '' } ; //Both of th... | Passing arrays as method parameters in Java |
Java | I 'm new to Java and I have come to having the following problem : I have created several classes which all implement the interface `` Parser '' . I have a JavaParser , PythonParser , CParser and finally a TextParser.I 'm trying to write a method so it will take either a File or a String ( representing a filename ) and... | public Parser getParser ( String filename ) { String extension = filename.substring ( filename.lastIndexOf ( `` . `` ) ) ; switch ( extension ) { case `` py '' : return new PythonParser ( ) ; case `` java '' : return new JavaParser ( ) ; case `` c '' : return new CParser ( ) ; default : return new TextParser ( ) ; } } | How should I return different types in a method based on the value of a string in Java ? |
Java | I have the following 2 methods overloaded in a class : When I invoke the method testMethod it print `` String '' .When I add one more overloaded method : It throws me compiler error : The method testMethod is ambigous for type Test..All this happens when I invoke the method with nullMy questions are : Why it prints Str... | public class Test { public static void main ( String [ ] args ) throws ParseException { Test t = new Test ( ) ; t.testMethod ( null ) ; } public void testMethod ( Object o ) { System.out.println ( `` Object '' ) ; } public void testMethod ( String s ) { System.out.println ( `` String '' ) ; } } public void testMethod (... | Method overloading and passing null |
Java | I 'm having trouble following the below code snippet : I know what the result of the code is and it 's correct in unit tests , but I 'm not overly familiar with guava or how/why this implementation works . Also currently it does n't appear to be safe if there is a null value in the list 'prices ' either ? So what I 'm ... | prices = pricesService.getProductsByCategory ( category ) ; List < Double > discountedPrices = Lists.newArrayList ( Iterables.transform ( prices , new Function < Double , Double > ( ) { public Double apply ( final Double from ) { return from *.88 ; } } ) ) ; | Strange looking guava code |
Java | I have a splash screen and a menu screen class that loads all my texture atlases and skins for the menu and processes lots of stuff . If I put the constructor for the menu screen in the SplashScreen constructor or in the create ( ) method of my main game class ( MyGame class ) then it would pass a lot of time with no s... | public class MyGame extends Game { ... public MainMenu menu ; ... @ Override public void create ( ) { this.screen_type == SCREEN_TYPE.SPLASH ; splashScreen = new SplashScreen ( ) ; setScreen ( splashScreen ) ; } ... @ Override public void pause ( ) { //never gets called if I press the HOME button in middle of splash sc... | Game crash if interrupted while Splash Screen is on - LIBGDX |
Java | In Java 8 , java.lang.Thread class got 3 new fields : as it said in Javadoc for being exclusively managed by class java.util.concurrent.ThreadLocalRandom.Furthermore , in ThreadLocalRandom they are used in very freakish way : ( the same code piece can be met also in LockSupport class ) .and then this offsets are used i... | /** The current seed for a ThreadLocalRandom */ @ sun.misc.Contended ( `` tlr '' ) long threadLocalRandomSeed ; /** Probe hash value ; nonzero if threadLocalRandomSeed initialized */ @ sun.misc.Contended ( `` tlr '' ) int threadLocalRandomProbe ; /** Secondary seed isolated from public ThreadLocalRandom sequence */ @ s... | New additional fields in java.lang.Thread , what is the idea ? |
Java | I compiled following code using Java-8 compiler : I compiled the above code using Java-8 compiler as : Version of my default Java Interpreter : And I can run the compiled code using Java-9 interpreter without any error.According to my knowledge : At runtime the package `` pack '' will be contained inside a special modu... | package pack ; import sun.util.calendar.CalendarUtils ; public class A { public static void main ( String [ ] args ) { System.out.println ( CalendarUtils.isGregorianLeapYear ( 2018 ) ) ; } } gyan @ gyan-pc : ~/codes/java $ ~/Documents/softwares/Linux/jdk1.8.0_131/bin/javac -d . a.javaa.java:2 : warning : CalendarUtils ... | How is Java 9 running code compiled with Java 8 that is using a non-exported package |
Java | First code : distance is called very often . When I compiled it with javac and then decompiled with javap -c I got this bytecode : It seems that javac has n't optimized second function , distance.Second code , I think , faster : And its bytecode : Is invokestatic so fast that it 's the same as inlining static function ... | public static int pitagoras ( int a , int b ) { return ( int ) Math.sqrt ( a*a + b*b ) ; } public static int distance ( int x , int y , int x2 , int y2 ) { return pitagoras ( x - x2 , y - y2 ) ; } public static int pitagoras ( int , int ) ; Code : 0 : iload_0 1 : iload_0 2 : imul 3 : iload_1 4 : iload_1 5 : imul 6 : ia... | Static functions inlining in Java |
Java | Here 's my code : Here 's my output : My understanding is that increment is synchronized . So , it should first increment one number and then release the lock and then give the lock to the thread t1 or t2 . So , it should increment one number at a time , right ? But why is my code incrementing two or three numbers at a... | private int count = 0 ; public synchronized void increment ( ) { count++ ; } public void doWork ( ) throws InterruptedException { Thread t1 = new Thread ( new Runnable ( ) { public void run ( ) { for ( int i = 0 ; i < 5 ; i++ ) { increment ( ) ; System.out.println ( count+ '' `` +Thread.currentThread ( ) .getName ( ) )... | Why is synchronized not working properly ? |
Java | If do not call System.gc ( ) , the system will throw an OutOfMemoryException . I do not know why I need to call System.gc ( ) explicitly ; the JVM should call gc ( ) itself , right ? Please advise.The following is my test code : As following , add -XX : +PrintGCDetails to print out the GC info ; as you see , actually ,... | public static void main ( String [ ] args ) throws InterruptedException { WeakHashMap < String , int [ ] > hm = new WeakHashMap < > ( ) ; int i = 0 ; while ( true ) { Thread.sleep ( 1000 ) ; i++ ; String key = new String ( new Integer ( i ) .toString ( ) ) ; System.out.println ( String.format ( `` add new element % d '... | OutOfMemoryException despite using WeakHashMap |
Java | Following is my codeThe error occurs at c.acceptParameterOfTypeA ( this ) ; .The error is The method acceptParameterOfTypeA ( A2 ) in the type C is not applicable for the arguments ( A ) From what I see , the method acceptParameterOfTypeA expects a parameter of type A , and this at the line giving the error is of type ... | class A < B2 extends B , A2 extends A < B2 , A2 > > { C < B2 , A2 > c ; void test ( ) { c.acceptParameterOfTypeA ( this ) ; } } class B { } class C < B2 extends B , A2 extends A < B2 , A2 > > { void acceptParameterOfTypeA ( A2 a ) { } } | Why Does the following code with Cyclic Generics not compile ? |
Java | The question is about java.util.stream.Stream.reduce ( U identity , BiFunction < U , ? super T , U > accumulator , BinaryOperator < U > combiner ) method.One of the requirements is that the combiner function must be compatible with the accumulator function ; for all u and t , the following must hold : If the combiner a... | combiner.apply ( u , accumulator.apply ( identity , t ) ) == accumulator.apply ( u , t ) ( * ) operator < T > op = ( x , y ) - > something ; stream.reduce ( id , op , op ) ; | Example of stream reduction with distinct combiner and accumulator |
Java | My Java textbook says that you can use the following code to randomly shuffle any given array : Would the following code that I wrote would be equally efficient or valid ? I tested my code and it does shuffle the elements properly . Is there any reason to use the textbook 's algorithm over this one ? | for ( int i = myList.length-1 ; i > =0 ; i -- ) { int j = ( int ) ( Math.random ( ) * ( i+1 ) ) ; double temp = myList [ i ] ; myList [ i ] = myList [ j ] ; myList [ j ] = temp ; } for ( int i = 0 ; i < myList.length ; i++ ) { int j = ( int ) ( Math.random ( ) * ( myList.length ) ) ; double temp = myList [ i ] ; myList... | Is there any difference between the following algorithms for shuffling arrays ? |
Java | Here 's snippet from java.util.ArrayList : Here 's snippet from com.google.collect.Preconditions : May somebody shed light on : why private outOfBoundsMsg is requiredmeaning of `` this outlining performs best ... '' should I start refactoring my code to include string returning methods for my exception constructors ? | /** * Constructs an IndexOutOfBoundsException detail message . * Of the many possible refactorings of the error handling code , * this `` outlining '' performs best with both server and client VMs . */private String outOfBoundsMsg ( int index ) { return `` Index : `` +index+ '' , Size : `` +size ; } /* * All recent hot... | Why is there private method outOfBoundsMsg in java.util.ArrayList ? |
Java | The JavaFX docs state that a WebView is ready when Worker.State.SUCCEEDED is reached however , unless you wait a while ( i.e . Animation , Transition , PauseTransition , etc . ) , a blank page is rendered.This suggests that there is an event which occurs inside the WebView readying it for a capture , but what is it ? T... | SnapshotRaceCondition.initialize ( ) ; BufferedImage bufferedImage = SnapshotRaceCondition.capture ( `` < html style='background-color : red ; ' > < h1 > TEST < /h1 > < /html > '' ) ; /** * Notes : * - The color is to observe the otherwise non-obvious cropping that occurs * with some techniques , such as ` setPrefWidth... | When is a WebView ready for a snapshot ( ) ? |
Java | I 'm confused by the Java spec about how this code should be tokenized : The spec says : The longest possible translation is used at each step , even if the result does not ultimately make a correct program while another lexical translation would.As I understand it , applying the `` longest match '' rule would result i... | ArrayList < ArrayList < Integer > > i ; | Are `` > > '' s in type parameters tokenized using a special rule ? |
Java | Am I breaking the “ Law of Demeter ” ? For example i create a Class person which contains name , phone and id and it match the column in my database.When I want to fill my Order info using person 's id.I do like this.I use getName and getPhone return by databaseComponent.That 's break LoD.Somebody recommend that I can ... | public static void fill ( Order order ) { DatabaseComponent databaseComponent = new DatabaseComponent ( ) ; Person person = databaseComponent.getById ( order.getUserId ( ) ) ; order.setName ( person.getName ( ) ) ; order.setPhone ( person.getPhone ( ) ) ; } public void fill ( Order order ) { DatabaseComponent databaseC... | Law of Demeter confusion in Java |
Java | I want to replace `` a '' of `` abababababababab '' with 001,002,003,004 ... ... that is `` 001b002b003b004b005b ... .. '' however this is poor efficiency , when the string is large enough , it will take minutes ! do you have a high efficiency way ? thanks very much ! | int n=1String test= '' ababababab '' ; int lo=test.lastIndexOf ( `` a '' ) ; while ( n++ < =lo ) Abstract=Abstract.replaceFirst ( `` a '' , change ( n ) ) ; //change is another function to return a string `` 00 '' +n ; | Java replace string with increasing number |
Java | Please take a look at below example i cant understand the relation between char and byteGive me compilation Error because c is type of char and b is type of byte so casting is must in such condition but now the tweest here is when i run below codeline 2 compile successfully it does n't need any casting at allso my ques... | byte b = 1 ; char c = 2 ; c = b ; // line 1 final byte b = 1 ; char c = 2 ; c = b ; // line 2 | char and byte with final access modifier - java |
Java | Considering the following toy example class : outerVar is volatile so all threads that may be using it will see it in the same state . But what about outerVar.innerVar ? Does the fact that its parent object ( outerVar ) is marked as volatile make it volatile also ? Or do we have to declare innerVar volatile explicitly ... | public class Test { private volatile Outer outerVar = new Outer ( ) ; static class Outer { Inner innerVar = new Inner ( ) ; } static class Inner { // state // setters // getters } private void multithreadedUse ( ) { // play with outerVar.innerVar } } | Is Java 's volatile keyword `` recursive '' regarding references tree , or must each reference be declared as volatile ? |
Java | compilation error : The left-hand side of an assignment must be a variable but when I tried this way , there is no compilation errorgetBoolean ( ) is returning a boolean value , so for the first case why the for loop is not accepting boolean value directly ? | class A { public static void main ( String [ ] args ) { for ( true ; true ; true ) { //compilation error } } } class A { public static void main ( String [ ] args ) { for ( getBoolean ( ) ; true ; getBoolean ( ) ) { } } public static boolean getBoolean ( ) { return true ; } } | why for loop is not accepting boolean value directly ? |
Java | Can you please run the below and explain ? I found that surprising as someone would expect 1 to be printed and not 1.0 | Object o = true ? new Integer ( 1 ) : new Double ( 2.0 ) ; System.out.println ( o ) ; | Strange java behaviour with conditional operator . Is it a bug ? |
Java | I am trying to test following method : Following is the Junit code : On the verify method call , I am getting following mockito exception : I do n't understand why mockito considers both the lambda 's are different ? UpdateI solved it without using Mockito . Here 's the other approach . Omitted empty overridden methods... | public void execute ( Publisher < T > publisher ) throws Exception { PublishStrategy < T > publishStrategy = publisher.getPublishStrategy ( ) ; publishStrategy.execute ( publisher : :executionHandler ) ; } @ Testpublic void testExecute ( ) throws Exception { PublishStrategy < Event > publishStrategy = Mockito.mock ( Pu... | Mockito how to verify lamba functions |
Java | While upgrading a build from Java 1.6 to 1.7 our unit tests started failing because of a difference between how the 2 versions handle the printing of trailing zeros on doubles.This can be reproduced with this example : Java 1.6 will output : Java 1.7 will output : I have 2 questions : Why is the printing of an inline c... | double preInit = 0.0010d ; System.out.println ( `` pre-init : `` + preInit ) ; System.out.println ( `` inline : `` + 0.0010d ) ; pre-init : 0.0010 inline : 0.0010 pre-init : 0.001 inline : 0.0010 | Difference in output printing a pre-initialized Java double vs. inline |
Java | I 'm trying to port some code from Linux to Windows . I really do n't know much about Windows , and so I 'm kind of flying blind . The code in question attempts to delete some directories using org.apache.commons.io.FileUtilssegments is a File , as is mergedSegFile . It dies with an IOException `` Unable to delete file... | // If the mergesegs worked , delete the segment dirs for ( File file : segments.listFiles ( ) ) { if ( ! file.equals ( mergedSegFile ) ) { LOG.debug ( `` deleting segment dir `` + file ) ; FileUtils.deleteDirectory ( file ) ; } } | Why is this code dying on Windows ? |
Java | I want to write an APP to record screen , there are two way , RecordHelper_Method_A and RecordHelper_Method_B .In RecordHelper_Method_A , I define mMediaRecorder , MediaProjection mMediaProjection and mVirtualDisplay as static var , it 's easy to invoke , such as StartRecord ( mContext , requestCode , resultCode , data... | public class RecordHelper_Method_A { private static MediaRecorder mMediaRecorder ; private static MediaProjection mMediaProjection ; private static VirtualDisplay mVirtualDisplay ; public static void StartRecord ( Context mContext , int requestCode , int resultCode , Intent data ) { mMediaRecorder = new MediaRecorder (... | Which one is the better between using static var and passing object parameter ? |
Java | I was given this assignment yesterday in class and thought I understood the process of selection sort but I feel a little unsure about it now . I thought that after each pass the numbers on the left become sorted and are not checked again until all the numbers on the right have been sorted first.Below are the instructi... | Original Array : 30 8 2 25 27 20 PASS 1 : 8 30 2 25 27 20 PASS 2 : 8 2 30 25 27 20 PASS 3 : 8 2 25 30 27 20 PASS 4 : 8 2 25 27 30 20 PASS 5 : 8 2 25 27 20 30 | Need help understanding Selection Sort Algorithm |
Java | I have this Java code some other person wrote , specifically JSPs . I am trying to understand where everything is.In my index.jsp ( the main file which is loaded ) it imports a certain namespace ( I suppose tomcat does all the compiling , I do n't know ) : This physical location does n't exist in my CLASSPATH so I supp... | < % @ page import= '' org.sgrp.SearchResults '' % > | Java code - looking for source code |
Java | I have searched through stackoverflow as well as a few other sites and sadly have not found this question asked , let alone answered . Maybe my approach is best attempted another way ? I am new to Java ; this should be a really easy answer I would think.The issue : I have a static method that I would like to return val... | public static String [ ] decodeText ( String codeString ) { //Parse codestring and return values ( not included in this example ) String [ ] data = new String [ 3 ] ; data [ 0 ] = '' This '' ; data [ 1 ] = '' does '' ; data [ 2 ] = '' work '' ; return data ; } public class JInputs extends JOptionPane { //A lot of missi... | How can I use a non-static ( dynamic instance ) object as return for a static method in Java ? |
Java | I successfully read an XSD schema using org.eclipse.xsd.util.XSDResourceImpl and process all contained XSD elements , types , attributes etc.But when I want to process a reference to an element declared in the imported schema , I get null as its type . It seems the imported schemas are not processed by XSDResourceImpl.... | final XSDResourceImpl rsrc = new XSDResourceImpl ( URI.createFileURI ( xsdFileWithPath ) ) ; rsrc.load ( new HashMap ( ) ) ; final XSDSchema schema = rsrc.getSchema ( ) ; ... if ( elem.isElementDeclarationReference ( ) ) { //element ref elem = elem.getResolvedElementDeclaration ( ) ; } XSDTypeDefinition tdef = elem.get... | Read XSD using org.eclipse.xsd.util.XSDResourceImpl |
Java | So I have a try/finally block . I need to execute a number of methods in the finally block . However , each one of those methods can throw an exception . Is there a way to ensure that all these methods are called ( or attempted ) without nested finally blocks ? This is what I do right now , which is pretty ugly : Is th... | protected void verifyTable ( ) throws IOException { Configuration configuration = HBaseConfiguration.create ( ) ; HTable hTable = null ; try { hTable = new HTable ( configuration , segmentMatchTableName ) ; // ... //various business logic here // ... } finally { try { try { if ( hTable ! =null ) { hTable.close ( ) ; //... | In java , is there a way to ensure that multiple methods get called in a finally block ? |
Java | I have a few classes that perform background tasks that might raise exceptions . They all implement the following interface : When one of the background tasks raises an exception , all the ExceptionHandlers are informed of the exception so that it can be properly handled / propagated.How would you call the interface ? ... | public interface HowDoYouCallMe { void addExceptionHandler ( ExceptionHandler handler ) ; } | What is this pattern ? |
Java | goal : I 'm using sharepoint REST APIs to create a list in my sharepoint site . In this case I 'm using okHttp as my Http library.expected result : should return 201 as response code when calling the request using okHttp.actual result : following are the steps I have implemented : create a bearer token set the required... | Exception in thread `` main '' java.io.IOException : unexpected code Response { protocol=http/1.1 , code=400 , message=Bad Request , url=https : //***.sharepoint.com/_api/web/lists } at com . **.list.ListImpl.createAList ( ListImpl.java:39 ) at com . **.Test.main ( Test.java:16 ) package com . ****.list ; import com . ... | Bad request with response code 400 , when posting json data to rest api using okHttp 4 . * |
Java | I have an Android Service running daily which does some data synchronization . Once a day it downloads a file and caches it to disk via context.openFileOutput : This happens on a background thread.I also have a UI which contains a WebView . The WebView uses those cached resources if they are available via context.openF... | String fileName = Uri.parse ( url ) .getLastPathSegment ( ) ; try ( FileOutputStream outputStream = context.openFileOutput ( fileName , Context.MODE_PRIVATE ) ) { outputStream.write ( bytes ) ; // ... } catch ( IOException e ) { // logging ... } @ Overridepublic WebResourceResponse shouldInterceptRequest ( WebView view... | Synchronization between Context.openFileInput and Context.openFileOutput |
Java | For example , if I userather thandecompiled code will contain getOwner , getName , getSignature methods in Java code , due to reflection . Do these methods counted against 64k limit ? | methodReference = : :method methodReference = { method ( it ) } | Does Kotlin generated byte code affect the method count ? |
Java | I am trying to use Java Streams to collects all the Strings of the greatest length from my list : I would like my longest to contain { `` long word '' , `` long wwww '' , `` llll wwww '' } , because those are the Strings that have the greatest lengths . In case of only having one of the Strings with greatest length , I... | List < String > strings = Arrays.asList ( `` long word '' , `` short '' , `` long wwww '' , `` llll wwww '' , `` shr '' ) ; List < String > longest = strings.stream ( ) .sorted ( Comparator.comparingInt ( String : :length ) .reversed ( ) ) .takeWhile ( ? ? ? ) .collect ( Collectors.toList ( ) ) ; static class IntWrappe... | How can I collect only the elements of the greatest length with Java Streams ? |
Java | I think that ( String ) x is an unchecked cast , but the compiler does not give any warning . Why does it happen ? | public static void main ( String [ ] args ) { Object x=new Object ( ) ; String y= ( String ) x ; } | Why does n't the following codes cause `` unchecked cast '' warning ? |
Java | I have this class , it perfectly does what I want . Now I need new class VSV which will derive from ( vertical ) ScrollView and be just the same . I surely can just copy whole block and change extends HorizontalScrolView to extends ScrollView , and then ( L , 0 ) to ( 0 , L ) ( oops , this was a mistake when publishing... | private class HSV extends HorizontalScrollView { public LinearLayout L ; public AbsoluteLayout A ; public HSV ( Context context ) { super ( context ) ; L = new LinearLayout ( context ) ; A = new AbsoluteLayout ( context ) ; } @ Override public void addView ( View child ) { A.addView ( child ) ; } void update_scroll ( )... | java sugaring , can I avoid almost-duplicate code here ? |
Java | I want to check whether JVM options for a particular application ( in this case , Matlab ) have been set to prefer IPV4 or if they still use IPV6.I know how to set the JVM to prefer IPV4 . In my case , it can be done by adding the line -Djava.net.preferIPv4Stack=trueto the java.opts file within $ MATLABROOT/bin/maci64/... | % OSX platform-specific : revert to IPv4if ( computer ( 'arch ' ) == 'maci64 ' ) javaoptspath = fileread ( [ matlabroot '/bin/ ' computer ( 'arch ' ) '/java.opts ' ] ) ; k = strfind ( javaoptspath , '-Djava.net.preferIPv4Stack=true ' ) ; if isempty ( k ) setenv ( 'DRAKE_IPV4_SET_MATLABROOT ' , matlabroot ) setenv ( 'DR... | Check programatically ( without string-matching ) whether using IPV6 or IPV4 for JVM |
Java | In xml file i do next : In class Keyboard in the method onKeyDown i create next constructionbut is dont work . What 's wrong ? | < Row > < Key android : codes= '' FLAG_EDITOR_ACTION '' android : keyLabel= '' Start '' / > < /Row > @ Overridepublic boolean onKeyDown ( int keyCode , KeyEvent event ) { switch ( keyCode ) { case KeyEvent.FLAG_EDITOR_ACTION : { return true ; } ... | How to create own key on soft Keyboard |
Java | I wonder how Hibernate finds NullValidator class which extends ConstraintValidator interface even if @ Null annotation definition as follows : | @ Target ( { METHOD , FIELD , ANNOTATION_TYPE , CONSTRUCTOR , PARAMETER } ) @ Retention ( RUNTIME ) @ Documented @ Constraint ( validatedBy = { } ) public @ interface Null { } | How HibernateValidator finds ConstraintValidator when validatedBy is empty ? |
Java | I encountered below code in my project . I was wondering if it can be optimized further may be by using java 8 streams or by collection APIs in general.Note : unfilteredSet and adminAreaSet hold different child types of Student | private Set < Student > getFilteredSet ( ) { Set < Student > unfilteredSet = getAllStudents ( ) ; Set < Student > adminAreaSet = getAdminStudents ( ) ; Set < String > adminAreaID = new HashSet < > ( ) ; Set < Student > filteredSet = new HashSet < > ( ) ; for ( final Student student : adminAreaSet ) { adminAreaID.add ( ... | Is there way of optimizing below code further using java8 ? |
Java | I want to have a constructor like the following.In this I would like to have a method called incrementValue ( Number n ) which will add n to value . I know you can not add two Number objects together due to the possible issues with casting . However , if I use a check to guarantee value and n are the same type is it po... | public Attribute ( String attrName , Number attrValue ) { this.name = attrName ; this.value = attrValue ; } | Java : add two values of the same type where both are subclasses of java.lang.Number |
Java | BackgroundAn existing system creates a plethora of HashMap instances via its Generics class : This is the single point of creation for all instances of classes that implement the Map interface . We would like the ability to change the map implementation without recompiling the application . This would allow us to use T... | import java.util.Map ; import java.util.HashMap ; public class Generics { public static < K , V > Map < K , V > newMap ( ) { return new HashMap < K , V > ( ) ; } public static void main ( String args [ ] ) { Map < String , String > map = newMap ( ) ; } } import java.util.Map ; import java.util.HashMap ; import gnu.trov... | Suppressing Warnings when using a dynamic class reference |
Java | So I have a class I have made which I wanted to be able to sort . To do so I simply had it implement the collection interface so it can be used in the Collections class . Now I have noticed that the class itself is just a hop , skip , and a jump away from a ListIterator and it would be nice to have it implement that in... | // from the Collection interface : public boolean add ( E someElement ) ; // from the ListIterator interface : public void add ( E someElement ) ; | Is it possible to implement both a ListIterator and a Collection in java ? |
Java | UPDATE solution is Java.lang.reflect.Proxy returning another proxy from invocation results in ClassCastException on assignmentMy test code proxies java.sql.Connection.I create my proxy like so : When I wrap an H2 DB connection , this works perfectly.When I try and wrap a MySQL connection , the cast of the proxy to Conn... | log.info ( `` connection is `` +connection.getClass ( ) .getName ( ) + '' , `` + ( connection instanceof Connection ) ) ; Object proxy = java.lang.reflect.Proxy.newProxyInstance ( connection.getClass ( ) .getClassLoader ( ) , connection.getClass ( ) .getInterfaces ( ) , new MockFailureWrapper ( connection ) ) ; log.inf... | can proxy some classes but not others |
Java | What is the equivalent c # generics notation of the above java generics ? Parameter listenerClass will be a type & not a object . But the object T has to belong to a specific hierachy . | public < T extends java.util.EventListener > T [ ] getListeners ( final Class < T > listenerClass ) { ... } | C # generics & not going insane |
Java | I 've created a minified JRE using the JLink toolI 've created a very basic application that connects to https : //www.example.comWhen I run this application using the JDK , everything works fine.When I run this using the minified JRE , I get the following : I 've noticed the lib\security\cacerts file in the JDK is muc... | jlink -- add-modules java.base , jdk.crypto.ec -- output jre Exception in thread `` main '' javax.net.ssl.SSLException : Unexpected error : java.security.InvalidAlgorithmParameterException : the trustAnchors parameter must be non-empty at java.base/sun.security.ssl.Alert.createSSLException ( Alert.java:133 ) at java.ba... | JRE created via JLink missing some security certificates ( cacerts ) |
Java | This code is benchmarking 3 different ways to compute the sum of the reciprocals of the elements of a double [ ] .a for-loopJava 8 streamsthe colt math libraryWhat is the reason that the computation using a simple for-loop is ~400 times faster than the one using streams ? ( Or is there anything needs to be improved in ... | import java.util.Arrays ; import java.util.List ; import java.util.Map ; import java.util.concurrent.TimeUnit ; import java.util.stream.Collectors ; import java.util.stream.IntStream ; import cern.colt.list.DoubleArrayList ; import cern.jet.stat.Descriptive ; import org.openjdk.jmh.annotations . * ; @ State ( Scope.Thr... | Why is the sum of reciprocals using a for-loop ~400x faster than streams ? |
Java | I have the following code to check if a game unit is a player or an enemy . These are the only two categories . I could delete the isEnemy method and run all checks for enemy as if ( ! isPlayer ) , but I personally feel that if ( isEnemy ) makes the intent of the code clearer . Are there any established coding styles t... | public boolean isPlayer ( Unit unit ) { return unit == player ; } public boolean isEnemy ( Unit unit ) { for ( Unit e : enemies ) { if ( unit.equals ( e ) ) return true ; } return false ; } | Is redundant code acceptable if it improves readability ? |
Java | I 'm totally lost on why that wo n't work : Is this some weird Eclipse error message ( it 's not able to cope with Lamdas either , so maybe Mars is n't entirely Java 8 ready , yet ) ? I can fix it by letting SpecialTestImpl implement Test directly ( which yields a warning , because it 's unnecessary ) or overriding the... | interface Test { default void doMagic ( ) { System.out.println ( `` Abracadabra '' ) ; } } class TestImpl implements Test { } class SpecialTestImpl extends TestImpl { public void doMagic ( ) { Test.super.doMagic ( ) ; // Error : No enclosing instance of the type Test is accessible in scope } } | Using The Default Method Of Grandparent Interface |
Java | I have a Spring Boot application using javax.validation annotations and I 'm trying to return friendly JSON error messages pointing to the offending field , yet converting from the available `` Java-object '' path to either JSONPath or JSON Pointer is something I 'm not finding a way to do.SSCO sample : Output : As you... | import com.fasterxml.jackson.annotation.JsonProperty ; import com.fasterxml.jackson.core.JsonProcessingException ; import com.fasterxml.jackson.databind.ObjectMapper ; import com.fasterxml.jackson.databind.PropertyNamingStrategy ; import javax.validation.Valid ; import javax.validation.Validation ; import javax.validat... | From Spring BindingResult to field JSONPath/JSON Pointer , with Jackson |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.