lang stringclasses 4
values | desc stringlengths 2 8.98k | code stringlengths 7 36.2k | title stringlengths 12 162 |
|---|---|---|---|
Java | Background : there is product listing page and i have to grab all the product name ( including out of stock product ) and then have to verify that all out of stock product are in the end.Problem : i have navigated all the page and stored the product names in an ArrayList . lets say list1 and contents are - Now i have a... | [ instant bcaa , vegan bcaa , complete bcaa energy™ , branched chain amino acid ( bcaa ) tablets 1000mg , endure™ , branched chain amino acids ( bcaa ) , instant leucine , leucine tablets 1000mg , complete intra-workout™ , leucine , bcaa jelly mix , complete hydration drink™ , informed bcaa™ , instant bcaa cocktail bun... | How to compare multiple items of an arraylist into another arraylist at specific position ? |
Java | I realize that there has been ample discussion of the relative merits of checked exceptions versus unchecked exceptions in Java , and it is not my intention to revisit the entire debate.Rather , I would like to ask a very specific question that came to mind as I was reading Joshua Bloch 's Effective Java , 2nd Edition ... | protected Object clone ( ) throws CloneNotSupportedException | unchecked exception that would have been better as checked |
Java | Here is the implementation of reverse in Long : I can understand line 1,2,3,4 , but not 5 ! How does it work ? I group the 64 bits to 8 groups , that is 1 is the first 8 bits , 2 is the second 8 bits , and so on.Then after line 4 , the sequence like 4,3,2,1,8,7,6,5and I think line 5 working as below before the | operat... | public static long reverse ( long i ) { // HD , Figure 7-1 i = ( i & 0x5555555555555555L ) < < 1 | ( i > > > 1 ) & 0x5555555555555555L ; //1 i = ( i & 0x3333333333333333L ) < < 2 | ( i > > > 2 ) & 0x3333333333333333L ; //2 i = ( i & 0x0f0f0f0f0f0f0f0fL ) < < 4 | ( i > > > 4 ) & 0x0f0f0f0f0f0f0f0fL ; //3 i = ( i & 0x00f... | How does ( i < < 48 ) | ( ( i & 0xffff0000L ) < < 16 ) | ( ( i > > > 16 ) & 0xffff0000L ) | ( i > > > 48 ) work ? |
Java | I am overriding equals and hashCode in a class that includes double fields . My first approach was to use the epsilon test in the equals method , and Double.hashCode ( double ) in hashCode , but that can result in equal objects having different hash codes ; here is a simplified example : I 've thought of several soluti... | public class DoubleHashTest2 { public static void main ( String [ ] args ) { double base1 = .9 ; double base2 = .7 ; Test test1 = new Test ( base1 - .1 ) ; Test test2 = new Test ( base2 + .1 ) ; System.out.println ( test1.equals ( test2 ) ) ; System.out.println ( test1.hashCode ( ) ) ; System.out.println ( test2.hashCo... | How to implement the equals/hashCode methods for classes that contain double fields |
Java | I was wondering , what does the -- > -- operator do in Java ? For example , if I have the following code : This always returns true.Thank you ! | int x = 3 ; int y = 3 ; if ( x -- > -- y ) { return true ; } | -- > -- operator in Java |
Java | I am trying to write regular expression in Java to evaluate two strings mentioned with ( ) separated by , I have written below codeIt works as expected and prints true in below cases But it is printing false when I send below It is strange because I am using same expression before and after , It returns true for ( t , ... | Example : ( test1 , test2 ) public static void main ( String [ ] a ) { String pattern = `` \\ ( [ a-zA-Z0-9 ] + , [ a-zA-Z0-9 ] +.\\ ) '' ; String test = `` ( test1 , test2 ) '' ; System.out.println ( test.matches ( pattern ) ) ; } String test = `` ( test1 , test2 ) '' ; String test = `` ( t , test2 ) '' ; String test ... | Regular expression is not working with single character |
Java | I am trying to register a class with array ( Spark Java with Kryo activated ) , log shows a clear message : I have written several combinations , but these do not work : I also tried to write a registration class without Class.forName but Java can not resolve the symbol InMemoryFileIndex $ SerializableBlockLocation : A... | Class is not registered : org.apache.spark.sql.execution.datasources.InMemoryFileIndex $ SerializableBlockLocation [ ] kryo.register ( Class.forName ( `` org.apache.spark.sql.execution.datasources.InMemoryFileIndex $ SerializableBlockLocation [ ] '' ) ) ; // ERROR kryo.register ( Class.forName ( `` org.apache.spark.sql... | Spark Kryo register for array class |
Java | I 'm trying to split a String in Java . The splits should occur in between two characters one of which is an alphabetic one ( a-z , A-Z ) and the other numeric ( 0-9 ) . For example : Output should be [ abc , 123 , def , 456 , ghi , 789 , jkl ] . Can someone help me out with a matching regular expression ? Thanks in ad... | String s = `` abc123def456ghi789jkl '' ; String [ ] parts = s.split ( regex ) ; System.out.println ( Arrays.deepToString ( parts ) ) ; | RegEx matching between characters |
Java | In Clojure I can look up a static member of a Java class ( e.g . a field holding a constant ) like this : How can I access the member when I only know it 's name at runtime ? An example would be looping over a sequence of field names and getting all the field values.I would like to do something like this ( this code is... | ClassName/CONSTANT_FIELD ( let [ c `` CONSTANT_FIELD '' ] ClassName/c ) | How can I dynamically look up a static class member in Clojure ? |
Java | I 'm using the current version of SWT to build my applications and I want to run it under Mac OS X ( Yosemite ) .My problem is now that I 'm not be able to capture clicks on the `` About '' , `` Preferences '' and `` Quit '' menu items which were automatically added to my application.I already searched a lot and found ... | import org.eclipse.swt . * ; import org.eclipse.swt.widgets . * ; public class Test { private Display display ; private Shell shell ; public Test ( Display display ) { this.display = display ; initUI ( ) ; } public void open ( ) { shell.open ( ) ; while ( ! shell.isDisposed ( ) ) { if ( ! display.readAndDispatch ( ) ) ... | Capture about , preferences and quit menu items |
Java | I have noticed in alot of people do in Java setters:1 ) Personally I do n't like this and I think it should be something like:2 ) Are there any reasons the first would be better ? Is n't 1 ) easier to make an error with . On a few occassions I have tracked bugs in code down to people doing : by mistake , maybe because ... | public void setX ( int x ) { this.x = x ; } public void setX ( int newX ) { x = newX ; } x = x ; | Java setters and `` this '' |
Java | I have had recently a small contest with one of my colleagues ( whom I very respect ) regarding a theoretical possibility to test whether some code is thread-safe or not.Let us suppose that we have a some `` black-box '' class FooUnknown taken from the 3rd party library , so we do n't have an access to its original sou... | @ ApplicationScopedpublic class FooService { private some.FooUnkown foo = new some.FooUnknown ( ) ; public void someStuff ( ) { // ... String result = foo.doSomeStuff ( ) ; // ... } } | Unit testing of potential concurrency problems |
Java | Let 's take this class as an example : and compare it to this : There is in my opinion no need for the accessors.Would this be considered bad OO design ? | public class Student { private String name ; private String id ; public Student ( String name , String id ) { this.name = name ; this.id = id ; } ... getters and setters for both fields public class Student { public final String name ; public final String id ; public Student ( String name , String id ) { this.name = na... | Should I use accessors for field values that will never change ? |
Java | This is the source code I have : And when I compile this , I get the bytecode . When I look at the bytecode with a Hexadecimal viewer I see part : which can be read as if the bytes are interpreted as characters . And when I do do disassemble this class I see : My question is , where is this String seen in the disassemb... | public class Koray { public static void main ( String [ ] args ) { System.out.println ( `` This is a sample program . `` ) ; } } 19 54 68 69 73 20 69 73 20 61 20 73 61 6D 70 6C 65 20 70 72 6F 67 72 61 6D 2E This is a sample program . javap -c Koray.class Compiled from `` Koray.java '' public class Koray { public Koray ... | When and Where is the String initialised/stored in Java source code ? |
Java | We are using JDO in one of our projects . This has been running for quite a while and naturally we need to change the model a bit.What is the best practice when migrating fields in entity classes in JDO ? If I delete an enum value there will be an exception if it 's already persisted when loading from the database , ho... | enum MyEnum { REGULAR , MYOLDTYPE // Delete this } @ PersistenceCapablepublic class Entity { @ Persistent MyEnum myEnumType ; @ Persistent String myString ; // Rename this } | Migrating fields in JDO |
Java | This is a bit of a contrived example to get across the situation I 'm encountering , but basically , I have an array of Objects that in reality contains arrays of integers , and I 'm trying to cast it as such . Here is a code snippet that simulates this situation : When I try to do this , I get the exception Exception ... | Object [ ] foo = new Object [ 3 ] ; foo [ 0 ] = new int [ ] { 1 , 2 , 3 } ; foo [ 1 ] = new int [ ] { 4 , 5 , 6 } ; foo [ 2 ] = new int [ ] { 7 , 8 , 9 } ; int [ ] [ ] bar = ( int [ ] [ ] ) foo ; | How can I cast an Object array to an array of arrays of integers |
Java | I have 3 EditText elements , and I want to jump from one field to the next if there are 4 characters in the input.I use a TextWatcher for this : The inputType for the EditText is `` textCapCharacters '' When doing a longpress on a key to get a number , like holding R to get a 4 , most devices will not add the letter , ... | getEditView ( R.id.edit_code1 ) .addTextChangedListener ( new TextWatcher ( ) { @ Override public void onTextChanged ( CharSequence s , int start , int before , int count ) { } @ Override public void beforeTextChanged ( CharSequence s , int start , int count , int after ) { } @ Override public void afterTextChanged ( E... | Count characters with TextWatcher fails on HTC longpress |
Java | I have to following setting : Ubuntu 12.04 , Mathematica 9 and IntelliJIDEA 12 . Every time I copy some text from Mathematica and paste it into IDEA , there are a lot of additional bytes at the end of the pasted text . What first appeared to be a bug in IDEA seems now rather be a bug in java itself . I have appended a ... | import java.awt . * ; import java.awt.datatransfer.Clipboard ; import java.awt.datatransfer.DataFlavor ; public class CopyPasteTest { public static void main ( String [ ] args ) { final String text ; try { final Clipboard systemClipboard = Toolkit.getDefaultToolkit ( ) .getSystemClipboard ( ) ; text = ( String ) system... | Java SystemClipboard contains additional bytes |
Java | The longest increasing subsequence is the well known problem and I have a solution with the patience algorithm.Problem is , my solution gives me the `` Best longest increasing sequence '' instead of the First longest increasing sequence that appears.The difference is that some of the members of the sequence are larger ... | public static void main ( String [ ] args ) throws java.lang.Exception { BufferedReader br = new BufferedReader ( new InputStreamReader ( System.in ) ) ; int inputInt ; int [ ] intArr ; try { String input = br.readLine ( ) .trim ( ) ; inputInt = Integer.parseInt ( input ) ; String inputArr = br.readLine ( ) .trim ( ) ;... | *First* Longest Increasing Subsequence |
Java | I am trying to solve pairing numbers ( a , b ) in an array such a way that a*2 > =b . Where a and b are numbers from input array.Examples : input : a [ ] = { 1,2,3,4,5 } output : 2 explanation : we can pair 1 with 3 2 with 4 or 5input : a [ ] = { 4,3,2,1,5 } output : 2 explanation : we can pair 1 with 3 2 with 4 or 5in... | public static int countPairs ( int [ ] a ) { Arrays.sort ( a ) ; return countPairs ( a , a.length,0 , a.length-1 ) ; } public static int countPairs ( int [ ] a , int n , int start , int end ) { if ( end == start ) { return 0 ; } if ( start > = n || end < 0 ) { return 0 ; } System.out.print ( `` matching start : `` +sta... | Pairing numbers ( a , b ) in an array such a way that a*2 > =b |
Java | I use the pattern quite a lot : This is indeed a great deal of boilerplate for something so simple . I was thinking of a generic object factory to do this with introspection , but this feels very evil ( special cases , inheritance , and speed issues ) . Guice could be used and the constructor skipped altogether , but t... | class Blah int a ; double b ; String c ; Date d ; public Blah ( int a , double b , String c , Date d ) { super ( ) ; // possibly this.a = a ; this.b = b ; this.c = c ; this.d = d ; } | Java constructors pattern |
Java | My code is basically allocation free , however the GC runs every 30 seconds or so when at 60fps . Checking the app with DDMS for allocation shows there is ALOT of SimpleListIterator being allocated . There is also some stuff being allocated because i use Exchanger . The SimpleListIterator comes from for each loops for ... | public class FastIterator { private static ThreadLocal < Holder > holders = new ThreadLocal < Holder > ( ) ; public static < T > Iterable < T > get ( ArrayList < T > list ) { Holder cont = holders.get ( ) ; if ( cont == null ) { cont = new Holder ( ) ; cont.collection = new DummyCollection < T > ( ) ; cont.it = new Ite... | Allocation free game |
Java | Spring Boot 2.1.8 , Spring Web 5.1.9 , Springfox Swagger 2.8.0 , Swagger Annotations/Models 1.5.14My RestController method signature looks like this : ids is documented as I expect - I can input multiple , separate values : However , _sort is always documented as a single string , no matter how I play around with diffe... | @ ApiOperation ( `` List statuses '' ) @ GetMapping ( produces = APPLICATION_JSON_VALUE ) public ListResult < Status > listStatuses ( @ ApiParam ( `` Filter given IDs '' ) @ RequestParam ( value = `` id '' , required = false , defaultValue = `` '' ) List < String > ids , @ ApiParam ( value = `` Sort by property value '... | How to document with Swagger a Spring MVC request param of type List < CustomObject > |
Java | The following code works when compiled with sourceCompatibility=1.7 or 1.6 , but fails after switching to 1.8 : Compilation output : Here 's the repo with failing code : https : //github.com/chalup/java8-wat . Just invoke ./gradlew clean build from project directory.I skimmed through JLS for Java 8 , but I have n't fou... | public class Java8Wat { interface Parcelable { } static class Bundle implements Parcelable { public void put ( Parcelable parcelable ) { } public void put ( Serializable serializable ) { } public < T extends Parcelable > T getParcelable ( ) { return null ; } } static { Bundle inBundle = new Bundle ( ) ; Bundle outBundl... | Why does this code fail with sourceCompatibility=1.8 |
Java | I am getting the following error while building my maven project.The structure of my project isI am using private repository to fetch all the relevant jars for my project.I have already tried deleting ~/.m2/repository folder but no luck . I have verified that there are no corrupt jars in my local repository plus this u... | [ INFO ] -- - jboss-as-maven-plugin:7.9.Final : deploy ( default-cli ) @ project-parent -- - [ WARNING ] Error injecting : org.jboss.as.plugin.deployment.Deployjava.lang.NoClassDefFoundError : org/jboss/as/controller/client/ModelControllerClient at java.lang.Class.getDeclaredConstructors0 ( Native Method ) at java.lang... | Error injecting : org.jboss.as.plugin.deployment.Deploy |
Java | I 'm trying to find separate the duplicates and non-duplicates in a List by adding them to a Set and List while using Stream.filter and Stream.mapAt the end of this , I expect distinct to be [ foo , bar , baz ] and extras to be [ foo , foo , bar ] , since there are 2 extra instances of foo and 1 of bar . However , they... | List < String > strings = Arrays.asList ( `` foo '' , `` bar '' , `` foo '' , `` baz '' , `` foo '' , `` bar '' ) ; Set < String > distinct = new HashSet < > ( ) ; List < String > extras = new ArrayList < > ( ) ; strings .stream ( ) .filter ( x - > ! distinct.add ( x ) ) .map ( extra - > extras.add ( extra ) ) ; .map (... | Lambda in Stream.map/filter not called |
Java | Before , I used to declare a wrapper annotation by hand , with an array , and then call it like so : Since I was making an array with the { ... } initializers , it was more than clear that the order was to be the same of the declaration when I accessed this method later via Reflection.However , when I use the new @ Rep... | @ Foos ( { @ Foo ( 0 ) , @ Foo ( 1 ) , @ Foo ( 2 ) } ) public void bar ( ) { } public @ interface Foos { Foo [ ] value ( ) ; } @ Repeatable ( Foos.class ) public @ interface Foo { int value ( ) ; } @ Foo ( 0 ) @ Foo ( 1 ) @ Foo ( 2 ) public void bar1 ( ) { } @ Foo ( 2 ) @ Deprecated @ Foo ( 5 ) @ Foo ( 10 ) public void... | Order of automatically wrapped @ Repeatable annotations |
Java | and the output isCan anybody elaborate on the difference beween 1380605909318 and 61341428160000 ? | public static void main ( String [ ] args ) throws ParseException { // create a date Date date = new Date ( ) ; long diff = date.getTime ( ) ; Date date1 = new Date ( 2013 , 10 , 1 , 11 , 6 ) ; long diff1 = date1.getTime ( ) ; System.out.println ( `` date is 1-10-2013 , `` + diff + `` have passed . `` ) ; System.out.pr... | java.util.Date class with different approach for same date gives different output |
Java | In my Project I have a Map.First I go to the Wifi router position , I scan the wifi List and select Operator2 and Mark it.Next I go to another position gather the Same Previous Operator2 details ( do n't ) , then I go another position repeat it again.I can able to First Time select the Wifi Operator.Next time I do n't ... | public class WifiReceiver extends BroadcastReceiver { private WifiManager wifiManager ; private PlanMapperActivity viewerActivity ; private Context newContext ; private String operator ; private String macAddress ; private int signalStrength ; private String wifiMode ; private int frequency ; private String htMode ; pr... | How to get selected same wifi operator from wifi List again and again in Android ? |
Java | While exploring for scjp questions , I came across this behaviour which I found strange.I have declared two classes Item and Bolt as follows : and tried to access the value of cost twiceThe output I get is 20 10.I ca n't understand how this happens . | class Item { int cost = 20 ; public int getCost ( ) { return cost ; } } class Bolt extends Item { int cost = 10 ; public int getCost ( ) { return cost ; } } public class Test { public static void main ( String [ ] args ) { Item obj = new Bolt ( ) ; System.out.println ( obj.cost ) ; System.out.println ( obj.getCost ( ) ... | Java Inheritance issue |
Java | So I am trying to solve the problem 1772 of the Caribbean online judge web page http : //coj.uci.cu/24h/problem.xhtml ? abb=1772 , the problem asks to find if a substring of a bigger string contains at least one palindrome inside it : e.g . Analyzing the sub-strings taken from the following string : `` baraabarbabartaa... | public static boolean hasPalindromeInside ( String str ) { int midpoint= ( int ) Math.ceil ( ( float ) str.length ( ) /2.0 ) ; int k = str.length ( ) -1 ; for ( int i = 0 ; i < midpoint ; i++ ) { char letterLeft = str.charAt ( i ) ; char secondLetterLeft=str.charAt ( i+1 ) ; char letterRight = str.charAt ( k ) ; char s... | 1772 of Caribbean online judge giving a time limit exceeded error . please help me find why is my algorithm taking so long |
Java | What 's wrong in this code ? I 'm trying to parse a date format that has 0 between years and months.This outputs Unparseable date : `` 201600101 '' . If I change ' 0 ' to anything but number [ e.g . ' X ' and format.parse ( `` 2016X0101 '' ) ] this will work . | import java.text.SimpleDateFormat ; class Main { public static void main ( String [ ] args ) { SimpleDateFormat format = new SimpleDateFormat ( `` yyyy ' 0'MMdd '' ) ; try { Date date = format.parse ( `` 201600101 '' ) ; System.out.println ( date ) ; } catch ( Exception ex ) { System.out.println ( ex.getMessage ( ) ) ;... | Unparseable date with extra number in Java |
Java | In short , does the JVM internally optimize the following code to behave as efficiently as the one below : If it does optimize , does it do so by caching the str.length ( ) value internally ? | public void test ( String str ) { int a = 0 ; for ( int i = 0 ; i < 10 ; i++ ) { a = a + str.length ( ) ; } } public void test ( String str ) { int len = str.length ( ) ; int a = 0 ; for ( int i = 0 ; i < 10 ; i++ ) { a = a + len ; } } | Does storing the str.length ( ) value in a variable before using it in a for loop have any performance improvements in Java ? |
Java | I am using Javaslang-2.1.0-alpha and its Javaslang-match equivalent to do some object decomposition . According to this by blog post by Daniel in the `` Match the Fancy way '' section : Should retrieve values matching the two wildcard patterns inside Address into street and number but the example does not even compile ... | Match ( person ) .of ( Case ( Person ( `` Carl '' , Address ( $ ( ) , $ ( ) ) ) , ( street , number ) - > ... ) ) Person person = new Person ( `` Carl '' , new Address ( `` Milkyway '' , 42 ) ) ; String result2 = Match ( person ) .of ( Case ( Person ( $ ( `` Carl '' ) , Address ( $ ( ) , $ ( ) ) ) , ( street , number )... | Javaslang object decomposition not working |
Java | In the context of static methods , i 'd like to narrow a type reference and invoke a more specific method for an object like this : So i 'd like to know if there 's a syntax allowing to call do ( Iterable ) rather that using some hack like this one : NOTE : I know it is n't possible to cast my iterable this wayand it s... | public static < T , L extends List < ? extends T > & RandomAccess > void do ( L list ) { // Do some stuff } public static < T > void do ( Iterable < ? extends T > iterable ) { if ( iterable instanceof List & & iterable instanceof RandomAccess ) // invoke do ( List & RandomAccess ) method else // do something else } pri... | Invoke method whose parameter is bounded by an intersection type |
Java | I have Scala-style enumHow do I:1 ) Call valueOf method to be able to get the value by its string representation ? 2 ) Call Java 's analog of ordinal : There are no such methods in SomeEnum , obviously . | object SomeObject { final object SomeEnum extends Enumeration { type SomeEnum = Value val val1 , val2 , val3 = Value } val possibleVal3 = SomeObject.SomeEnum.valueOf ( `` val3 '' ) val a = SomeObject.SomeEnum.val2a.ordinal | Working with enums in Scala |
Java | I encountered a rather strange behaviour of screenshotting my desktop application in LibGDX . I remade a small program to reproduce this `` bug '' which only renders a black background and a red rectangle . Those images are the results : The left one being a screenshot from window 's screen clipping tool , this is what... | @ Overridepublic void render ( ) { Gdx.gl.glClear ( GL20.GL_COLOR_BUFFER_BIT ) ; Gdx.gl.glActiveTexture ( GL20.GL_TEXTURE0 ) ; Gdx.gl.glEnable ( GL20.GL_BLEND ) ; Gdx.gl.glBlendFunc ( GL20.GL_SRC_ALPHA , GL20.GL_ONE_MINUS_SRC_ALPHA ) ; shape.begin ( ShapeType.Filled ) ; shape.setColor ( Color.BLACK ) ; shape.rect ( 0 ,... | LibGDX screenshot strange behaviour |
Java | I have a brute force solution to calculate all substrings in an input string in O ( n^2 ) time . Its takes long time when my input string is very long.How can we find all substrings possible in O ( n ) time ? I am only looking for count of all substrings where first and last character in substring is same . As you can ... | // I am calculating count of all substrings where first and last substring character are equalpublic class Solution { public static void main ( String [ ] args ) { String inputString = `` ababaca '' ; System.out.println ( findSubstringByBruteForcce ( inputString , inputString.length ( ) ) ) ; } private static long find... | Is there a trick/algorithm by which we can find all substrings possible in O ( n ) time |
Java | Here is my code : Now the issue is that , in the initializer blockif I add the this keyword before message , it works , but there is an error when missing this keyword.And the compiler says : Why are n't they the same ? | class StaticBlock { { println ( `` initializer block : `` + message ) ; } public StaticBlock ( String message ) { this.message = message ; } private String message ; } { println ( `` initializer block : `` + message ) ; } StaticBlockDemo.java:34 : illegal forward reference println ( `` initializer block : `` + message ... | what does `` this '' keyword mean in the initializer block ? |
Java | I have a Spring boot SOAP services with cxf , and my Consumers are passing me SSO token in http header.. I am able to retrieve the SSO token using JAX-WS handler . I am saving that SSO token into handler class level variable , and after control going through various classes it reaches to a point where I have to make a ... | @ Componentpublic class EndPointHandler implements SOAPHandler < SOAPMessageContext > { private List < String > ssoToken ; private Map < String , List < String > > headers ; @ Override public boolean handleMessage ( SOAPMessageContext context ) { Boolean isResponse = ( Boolean ) context.get ( SOAPMessageContext.MESSAGE... | Pass data from a SOAP handler to a webservice server Class |
Java | I 've seen this type of code a lot in projects , where the application wants a global data holder , so they use a static singleton that any thread can access.I hope it 's easy to see what 's going on . One can call GlobalData.getInstance ( ) .getData ( ) at any time on any thread . If two threads call setData ( ) with ... | public class GlobalData { // Data-related code . This could be anything ; I 've used a simple String . // private String someData ; public String getData ( ) { return someData ; } public void setData ( String data ) { someData = data ; } // Singleton code // private static GlobalData INSTANCE ; private GlobalData ( ) {... | What is the memory visibility of variables accessed in static singletons in Java ? |
Java | I have a strange Java generics ambiguity behaviour that I can not explain : Those 3 methods in class : compile fine.But those not ( ambiguity violation ) : ( ClassA , ClassB , ClassC are all completely independent interfaces ! ) | public static < E extends ClassA & ClassB > void method ( E val ) { } public static < E extends ClassC & ClassB & ClassA > void method ( E val ) { } public static < E extends ClassB > void method ( E val ) { } public static < E extends ClassA & ClassB > void method ( E val ) { } public static < E extends ClassB & Class... | Generics ambiguity with the & -operator and order |
Java | In my Spring boot app , I have the following two classes : and : JwtAuthenticationFilter depends on an AuthenticationManager bean through its setAuthenticationManager method , but that bean gets created in AppSecurityConfig which has JwtAuthenticationFilter autowired in . This whole thing creates a circular dependency ... | @ EnableWebSecuritypublic class AppSecurityConfig extends WebSecurityConfigurerAdapter { @ Autowired private JwtAuthenticationFilter jwtAuthenticationFilter ; @ Bean @ Override public AuthenticationManager authenticationManagerBean ( ) throws Exception { return super.authenticationManagerBean ( ) ; } @ Override protect... | AuthenticationProcessingFilter and WebSecurityConfigurerAdapter causing circular dependency |
Java | I was going through the source code of the java.util.HashMap class and noticed that the explicit no-arg constructor expects two constants : But when I looked at the DEFAULT_INITIAL_CAPACITY constant , I found that it was defined as follows : I 've never seen this type of construct used in any product I 've worked on , ... | /** * Constructs an empty < tt > HashMap < /tt > with the default initial capacity * ( 16 ) and the default load factor ( 0.75 ) . */public HashMap ( ) { this ( DEFAULT_INITIAL_CAPACITY , DEFAULT_LOAD_FACTOR ) ; } /** * The default initial capacity - MUST be a power of two . */static final int DEFAULT_INITIAL_CAPACITY ... | Defining Java Constants using Bit-Shift Notation |
Java | This question is related to `` Comparison method violates its general contract ! '' - TimSort and GridLayout and several other similar `` general contract violation '' questions . My question is particularly related to Ceekay 's answer at the bottom of the page about `` How to test the TimSort implementation '' . In my... | public class TickNumber implements Comparable < TickNumber > { protected String zone ; protected String track ; } public class GisTickNumber extends TickNumber implements Comparable < TickNumber > { private String suffix ; } | Java - How to unit test TimSort and `` general contract violation '' issues |
Java | I have a scenario where I can guarantee that Thread 1 will complete the add ( ) call before Thread 2 make the get ( ) call . Will Thread 2 always see the changes made by Thread 1 in this case ? Or would the internal ArrayList variables need to be marked as volatile ? Edit : For those who are curious about why I can gua... | Thread 1 : Call list.add ( ) Thread 1 : Exits list.add ( ) Thread 2 : Call list.get ( list.size ( ) -1 ) Event A1Event A2Event A3Event B List < EventA > eventAList = new ArrayList < > ( ) ; connection.addListenerForEventAs ( eventAList : :add ) ; connection.waitForEventB ( ) ; //Here I am doing operations on the eventA... | Java ArrayList - Are add ( ) calls from one thread always readable from another ? |
Java | There are two maps and I am trying to merge them into a single map ( finalResp ) . Solution - pre Java 8 - achieved like below : Using Java 8 , I am stuck at this : How can I check if a map 2 key is not present in map 1 and modify the values ? | Map < String , String [ ] > map1 = new HashMap < > ( ) ; Map < String , String > map2 = new HashMap < > ( ) ; HashMap < String , String > finalResp = new HashMap < String , String > ( ) ; for ( Map.Entry < String , String [ ] > entry : map1.entrySet ( ) ) { if ( map2.containsKey ( entry.getKey ( ) ) ) { String newValue... | Merging map and modifying value |
Java | If we have the following code : Is the p = null required in a finally block or all the associated streams are closed by default ? | Process p = null ; BufferedReader br = null ; try { p = Runtime.getRuntime ( ) .exec ( `` ps -ef '' ) ; br = new BufferedReader ( new InputStreamReader ( p.getInputStream ( ) ) ) ; //Do something with br } catch ( Exception e ) { //Handle catch block } finally { //Do we need to set p = null ; } | Do we need to set a process variable to null in a finally block ? |
Java | I 'm trying to determine how much stack memory each method consumes when running . To do the task , I 've devised this simple program that will just force a StackOverflowError , printing an integer telling me how many times m ( ) was called . I 've manually set the JVM 's stack size ( -Xss VM parameter ) to varying val... | public class Main { private static int i = 0 ; public static void main ( String [ ] args ) { try { m ( ) ; } catch ( StackOverflowError e ) { System.err.println ( i ) ; } } private static void m ( ) { ++i ; m ( ) ; } } stack i delta 128 1102 256 2723 1621 384 4367 1644 | Inferring a method 's stack memory use in Java |
Java | I would like to extend the set of reloadable directories on tomcat 7.0.59.When reloadable attribute within Context is set to true , tomcat monitors classes in : /WEB-INF/classes/ and /WEB-INF/lib . Set to true if you want Catalina to monitor classes in /WEB-INF/classes/ and /WEB-INF/lib for changes , and automatically ... | < Context reloadable= '' true '' path= '' /test '' docBase= '' /MY_MODULE/web/webroot '' > < Manager pathname= '' '' / > < WatchedResource > /MY_MODULE/classes < /WatchedResource > < /Context > | Extend the set of reloadable directories on tomcat |
Java | I have read a few explanations of section 16.3 `` Initialization Safety '' from JCIP and am still not clear . The section states that '' Further , any variables that can be reached through a final field of a properly constructed object ( such as the elements of a final array or the contents of a HashMap referenced by a... | public final class Container { private String name ; private int cupsWon ; private double netWorth ; public Container ( String name , int cupsWon , double netWorth ) { this.name = name ; this.cupsWon = cupsWon ; this.netWorth = netWorth ; } //NO Setters //Getters } final Container c = new Container ( `` Ted Dibiasi '' ... | Visibility Guarantee |
Java | In ebay Order API - initiateCheckoutSession ( guest checkout ) , adding credit card information returns error . I am testing in sandbox environment.API : https : //api.sandbox.ebay.com/buy/order/v1/guest_checkout_session/initiateRequest Body : Response : API works fine if credit card details are not in request . Could ... | { `` creditCard '' : { `` accountHolderName '' : `` Frank Smith '' , `` cardNumber '' : `` 5100000001598174 '' , `` cvvNumber '' : `` 012 '' , `` expireMonth '' : 10 , `` expireYear '' : 2019 , `` brand '' : `` MASTERCARD '' , `` billingAddress '' : { `` firstName '' : `` Frank '' , `` lastName '' : `` Smith '' , `` ad... | eBay Order API throwing error in sandbox environment |
Java | Let 's assume I 've two threads t1 and t2 which are trying to access incX ( ) Here is my following code : Here 's my output : As in incX ( ) method I 've synchronized x = ++x , so the changes made to thread t1 should be visible to thread t2 , right ? So my output should be : I know ++x is not an atomic operation but it... | class Test implements Runnable { private int x = 0 ; public void incX ( ) { synchronized ( this ) { x = ++x ; } System.out.println ( `` x is : `` +x+ '' `` +Thread.currentThread ( ) .getName ( ) ) ; } public void run ( ) { incX ( ) ; } public static void main ( String [ ] args ) { Thread t1 = new Thread ( new Test ( ) ... | Why variable is not visible to other thread in synchronization ? |
Java | I have a rather simple question . I ca n't find an answer by searching though.Is there a difference in these two code-fragments ? And what is the difference ? Fragment1 : Fragment2 : Fragment1 specifies explicitly , that the parameter value must be either of type T or a subtype of type T.Fragment2 specifies , that the ... | public class BinaryTree < T extends Comparable < ? super T > > { ... public < E extends T > void add ( E value ) { ... } public < E extends T > void add ( E value , Node node ) { ... } ... } public class BinaryTree < T extends Comparable < ? super T > > { ... public void add ( T value ) { ... } public void add ( T valu... | Parameterized methods in generic class type |
Java | I 'm writing a program where I 'm supposed to make a method that calculates if the passed number is odd . For this method , I also need to check that passed number is > 0 , and if not , return false.I am also supposed to make a second method with two parameters ( start and end , which represents a range of numbers ) an... | public static boolean isOdd ( int number ) { boolean status = false ; if ( number < 0 ) { status = false ; } else if ( number % 2 ! = 0 ) { status = true ; } return status ; } public static int sumOdd ( int start , int end ) { int sum = 0 ; if ( ( end < start ) || ( start < 0 ) || ( end < 0 ) ) { return -1 ; } for ( in... | Sum odd numbers program |
Java | I have an application that is multithreaded and working OK . However it 's hitting lock contention issues ( checked by snapshotting the java stack and seeing whats waiting ) .Each thread consumes objects off a list and either rejects each or places it into a Bin.The Bins are initially null as each can be expensive ( an... | public void addToBin ( Bin [ ] bins , Item item ) { Bin bin ; int bin_index = item.bin_index synchronized ( bins ) { bin = bins [ bin_index ] ; if ( bin==null ) { bin = new Bin ( ) ; bins [ bin_index ] = bin ; } } synchronized ( bin ) { bin.add ( item ) ; } } public void addToBin ( Bin [ ] bins , Item item ) { int bin_... | Sharing array of bins between threads |
Java | I am attempting to create a simple Java script which will connect to Rally , fetch all of the defects and return the defect details including the discussion as a Java object . The problem here is that the Discussion is returned as what I believe is a collection because only a URL is given . I am stuck on how to return ... | import java.io.IOException ; import java.net.URI ; import java.net.URISyntaxException ; import com.google.gson.JsonArray ; import com.google.gson.JsonElement ; import com.google.gson.JsonObject ; import com.google.gson.JsonParser ; import com.rallydev.rest.RallyRestApi ; import com.rallydev.rest.request.GetRequest ; im... | Extracting Rally Defect Discussion using the Java Rally Rest API |
Java | I made a simple GridBagLayout which adds buttons in the cells ( 0,0 ) , ( 1,0 ) , and ( 0,1 ) .I was happy to see the resultant UI : I want to add a JButton in a cell that is not connected to the existing cells . I want it to be separated by an empty space . When I try this , the new JButton is lumped in next to the ot... | JPanel panelMain = new JPanel ( new GridBagLayout ( ) ) ; GridBagConstraints c = new GridBagConstraints ( ) ; c.gridx = 0 ; c.gridy = 0 ; panelMain.add ( new JButton ( `` 0,0 '' ) , c ) ; c.gridx = 1 ; c.gridy = 0 ; panelMain.add ( new JButton ( `` 1,0 '' ) , c ) ; c.gridx = 0 ; c.gridy = 1 ; panelMain.add ( new JButto... | Does GridBagLayout require placeholder panels for empty cells ? |
Java | I have a libGDX game project for Android , and I want to execute a Groovy script in it.To do so , I am examining this example code : https : //github.com/melix/grooidshell-exampleThey managed to execute Groovy embed in Java on Android . Particularly GrooidShell.java ( https : //github.com/melix/grooidshell-example/blob... | public GrooidShell ( File tmpDir , ClassLoader parent ) { public class AndroidLauncher extends AndroidApplication { @ Override protected void onCreate ( Bundle savedInstanceState ) { super.onCreate ( savedInstanceState ) ; AndroidApplicationConfiguration config = new AndroidApplicationConfiguration ( ) ; initialize ( n... | Getting a directory file and the ClassLoader for a libGDX Android game |
Java | Im using the following codeSo that list will only accept Strings to be added , how can I add into one list more types of variables like ints and strings together likeAdding into the text list some rectangle values likerectangle name , rectangle width , rectangle height So later I can access them in a loop | List < String > text = new ArrayList < String > ( ) ; text.add ( `` Hello '' ) ; | Java list items |
Java | Consider this case : Is there a syntax to reference the instance of the anonymous inner class represented by SomeInterface at the commented code ? For SomeClass you can do SomeClass.this Is there an equivalent to get the implementation of SomeInterface ? If not , of course you can just define a final local variable in ... | public class SomeClass { public void someMethod ( ) { new SomeInterface ( ) { public void someOtherMethod ( ) { new SomeOtherInterface ( ) { new someThirdMethod ( ) { //My question is about code located here . } } ; } } ; } } | Is there a syntax to get the reference to an anonymous inner class from a further anonymous inner class ? |
Java | EDIT : I really appreciate everyone 's input . I gained something from all the responses and learned a good deal about OOD.I am making a simple virtual tabletop war game . To represent units on the battlefield I have the following simple class hierarchy : An abstract class Unit , and two derived classes , Troop and Veh... | public Troop getTroop ( String uniqueID ) { Unit potentialTroop = get ( uniqueID ) ; if ( potentialTroop instanceof Vehicle ) { throw new InternalError ( ) ; } return ( Troop ) potentialTroop ; } public Vehicle getVehicle ( String uniqueID ) { Unit potentialVehicle = get ( uniqueID ) ; if ( potentialVehicle instanceof ... | Java - My Code is clearly going against common OOD paradigms , but not sure how to improve it |
Java | I am trying to create a map using groupingBy ( ... ) function in lambda . Now the problem I am facing is I am unable to convert list to map for particular conditionCode : Expected functionality : I need to collect a map whose key is key value like keys from 0 to 120 and values will increase likeWhat I am trying ( idea ... | List < Integer > list = IntStream .range ( 0,120 ) .mapToObj ( Integer : :new ) .collect ( Collectors.toList ( ) ) ; [ ] [ 0 ] [ 0 , 1 ] [ 0 , 1 , 2 ] [ 0 , 1 , 2 , 3 ] [ 0 , 1 , 2 , 3 , 4 ] [ 0 , 1 , 2 , 3 , 4 , 5 ] [ 0 , 1 , 2 , 3 , 4 , 5 , 6 ] [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 ] [ 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 ] [... | Convert list to map using lambda but for limited length |
Java | I saw following question and tried to find an answer for that.My answer to above question is : I think my answer is O ( N^2 ) which is not acceptable based on Question . Is there a solution based on O ( N ) ? | Question : Given a sequence of positive integers A and an integer T , return whether there is a *continuous sequence* of A that sums up to exactly TExample [ 23 , 5 , 4 , 7 , 2 , 11 ] , 20 . Return True because 7 + 2 + 11 = 20 [ 1 , 3 , 5 , 23 , 2 ] , 8 . Return True because 3 + 5 = 8 [ 1 , 3 , 5 , 23 , 2 ] , 7 Return ... | How to iterate over array of integers to find a sequence based on an O ( N ) solution ? |
Java | Im trying to understand how class generics work and this bit just doesnt make sense to me.So for instance if I have the following classes : and then I try Should n't the go method accept A or any sub class of A ? ? thanks : ) | class A < E > { void go ( E e ) { } } class B extends A { } A < ? extends A > a1 = new A < A > ( ) ; A < ? extends A > a2 = new A < B > ( ) ; a1.go ( new A ( ) ) ; // i get a compiler errora2.go ( new B ( ) ) ; // i get a compiler error | Understanding the use of generics in java |
Java | How can I maintain an ArrayList of unique arrays ? For instance , if I have the following arrays : According to my logic I am considering unique combinations . So in the case above a = b = c because they all contain `` 1 '' , `` 2 '' , `` 3 '' . Ideally I am wondering if there is a data structure in Java that recognize... | int [ ] a = { 1,2,3 } ; int [ ] b = { 2,1,3 } ; int [ ] c = { 2,1,3 } ; Set < int [ ] > result = new LinkedHashSet < > ( ) ; int [ ] x = { 1,2,3 } ; int [ ] z = { 2,1,3 } ; int [ ] m = { 2,1,3 } ; result.add ( x ) ; result.add ( z ) ; result.add ( m ) ; for ( int [ ] arr : result ) { printArray ( arr ) ; } 1 2 32 1 32 ... | Maintain an ArrayList of unique arrays in java |
Java | I 'm working through some sample code and then this appeared : What 's < > used for ? And why is just T inside these ? This seems to be very random for me . However , how can I use it in a longer perspective of making programs ? Thanks and tell me if I need to add more details ! | public abstract class RandomPool < T > extends Pool { //Class ... } | Java - What 's < > used and what 's its name ? |
Java | I am encountering a strange problem with Hibernate . There are two database tables that stores active and resolved tickets . In Java there is a super class ( Ticket ) and entity subclasses ( ActiveTicket and ResolvedTicket ) .Now when a ticket is resolved it is moved to the ResolvedTicket table.Now I have a custom find... | public Ticket findByID ( Long id ) { Ticket t = findByID ( ActiveTicket.class , id ) ; if ( null == t ) { t = findByID ( ResolvedTicket.class , id ) ; } return t ; } public < C > C findByID ( Class < C > class , PK id ) { return ( C ) getHibernateTemplate ( ) .get ( class , id ) ; } | HibernateTemplate Get method returns an object with null values |
Java | I have to use a variable which will never be changed in method which will be frequently used in many threads . Which of these variants are more efficient ? Variant 1 : Variant 2 : Variant 3 : | public class Test { private static int myVar ; public Test ( int myVar ) { this.myVar=myVar ; } public void frequentlyUsedMultiThreadMethod ( ) { //read myVar } } public class Test { public void frequentlyUsedMultiThreadMethod ( int myVar ) { //read myVar } } public class Test { private final int myVar ; public Test ( ... | What is faster passing arguments or using static variable in Java ? |
Java | I wanted to create a very restrictive security manager , so I extended SecurityManager and overridden all the custom checkXXX methods.But then I found out that my security manager is useless , because anyone can just : So I have to add : Are there any more surprises ? Any other things I have to do to make my SecurityMa... | System.setSecurityManager ( null ) ; @ Override public void checkPermission ( Permission perm ) { if ( perm.getName ( ) .equals ( `` setSecurityManager '' ) ) { throw new SecurityException ( `` You shall have no other security manager but me ! `` ) ; } } | SecurityManager surprises |
Java | Hibernate UnUniqueify a column in table ( Solved ) I want a field set to be non-unique on itself but to be unique in combination with the other field , I got this table with two columns ( composite primary keys ) ; id ( primary key ) and object_proxy_id ( primary key ) , this is exactly what I need but hibernate sets t... | | -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| tbl_object_proxy || -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- || Id ( pk ) | object_proxy_id ( pk ) || -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -|| 1 | 150 -- || 1 | 149 |= must be able to be DUPLICATE which is not the case right now.| 2 | 150 -- || 2 | 151 || -... | Hibernate UnUniqueify a column in table |
Java | I have a simple class which does some calculations in its own thread and reports the results to the listener.At any time , the user can call setListener ( null ) if he does n't want any events for a certain time period . So , in the run ( ) function , I create a copy of the listener , so I ca n't run into a NullPointer... | class Calculator extends Thread { protected Listener listener ; public void setListener ( Listener l ) { listener = l ; } public void run ( ) { while ( running ) { ... do something ... Listener l = listener ; if ( l ! = null ) { l.onEvent ( ... ) ; } } } } | java - do I have to declare my shared listener member variable as volatile ? |
Java | Ok just for sake knowledge , I tried below cases ( Assume that Class A and B are in same package ) ClassA ClassB executing above ClassB it will produce output of B now after below change in classBClassB If I compile and run in terminal it gives me output A that was totally surprising as it should had given NoSuchMethod... | public class ClassA { public static void main ( String [ ] args ) { System.out.println ( `` A '' ) ; } } public class ClassB extends ClassA { public static void main ( String [ ] args ) { System.out.println ( `` B '' ) ; } } public class ClassB extends ClassA { //blank body } | why Exception or Error not generated when no main method found ? |
Java | i am implementing Floyd–Warshall algorithm with c++ , c # and java . in each language i use sequential and parallel implementation after testing the result was : ( Elapsed time is only for main Function and Reading Files , Inti of Variable and ... are not measured . ) download sources here SourceCodesc++IDE : NetbeansC... | # define n 1000 /* Then number of nodes */double dist [ n ] [ n ] ; void floyd_warshall ( int NumOfThreads ) { int i , j , k ; omp_set_num_threads ( NumOfThreads ) ; for ( k = 0 ; k < n ; ++k ) # pragma omp parallel for private ( i , j ) for ( i = 0 ; i < n ; ++i ) for ( j = 0 ; j < n ; ++j ) if ( ( dist [ i ] [ k ] * ... | Comparing c # , c++ and java performance ( Strange behavior of c # ) |
Java | I 'm running tasks periodically and to provide flexibility for the intervals , the next timeout is calculated at the end of each task , converted to milliseconds from Instant.now ( ) , and scheduled using ScheduledExecutorService # schedule.This code is generally working fine ( blue curve on the left ) , but other days... | // Log time in GMT+2 , other times are in GMT// The following lines are written following system startup ( all times are correct ) 08 juin 00:08:49.993 [ main ] WARN com.pgscada.webdyn.Webdyn - Scheduling next webdyn service time . Currently 2018-06-07T22:08:49.993Z , last connection null08 juin 00:08:50.586 [ main ] I... | ScheduledExecutorService tasks are running later than expected |
Java | I 'm seeing what appears to be contradictory behavior out of WorldWind 's Sphere-Line intersection logic . I create a Sphere and Line and they intersect but then the intersection returns null ( scan code for comment : // *** This is where it gets whacky ) . Here is what 's going on visually ( the line is gray it 's the... | public class WWTest extends ApplicationTemplate { public static class VisualizationFrame extends ApplicationTemplate.AppFrame { public VisualizationFrame ( ) { super ( new Dimension ( 1200 , 1024 ) ) ; final Globe globe = getWwd ( ) .getModel ( ) .getGlobe ( ) ; //Create a sphere at 0,0 on the surface of the Earth wtih... | WorldWind Sphere Line Intersection Bug ? |
Java | I have a situation where I have to change java constant.I have below code working If I run above , I get following output : But if I change FLAG variable to int i.e.It does not work . The output is : Is there any other way to make it work with Primitive Type int . | import java.lang.reflect.Field ; import java.lang.reflect.Modifier ; public class Main { public static final Integer FLAG = 44 ; static void setFinalStatic ( Class < ? > clazz , String fieldName , Object newValue ) throws NoSuchFieldException , IllegalAccessException { Field field = clazz.getDeclaredField ( fieldName )... | Changing static variable works Primitive Wrapper but not with Primitive type |
Java | I ca n't understand why iterating multiple time over a same array with Stream apiresult in such a performance ! see the code below.for sure JVM optimizes the code but i do n't know how this happening ? ? It is amazing ! do you have any clue why this happening ? -- I 'm testing on Ubuntu 14.04/ / Oracle jdk / intel cpu ... | public class WhyIsDifferent { public static void main ( String [ ] args ) { int [ ] values = getArray ( ) ; Iterate ( values , 598 , 600 ) ; // 70 ms Iterate ( values , 200 , 202 ) ; // 0 ms Iterate ( values , 700 , 702 ) ; // 0 ms Iterate ( values , 300 , 310 ) ; // 1 ms } public static void Iterate ( int [ ] values ,... | Puzzled with Java8 Stream performance |
Java | I use AsyncHttpClient library for async non blocking requests.My case : write data to a file as it is received over the network.For download file from remote host and save to file I used default ResponseBodyPartFactory.EAGER and AsynchronousFileChannel so as not to block the netty thread as data arrives . But as my mea... | public static class AsyncChannelWriter { private final CompletableFuture < Integer > startPosition ; private final AsynchronousFileChannel channel ; public AsyncChannelWriter ( AsynchronousFileChannel channel ) throws IOException { this.channel = channel ; this.startPosition = CompletableFuture.completedFuture ( ( int ... | Java AsyncHttpClient : broken file while writing from LazyResponseBodyPart to AsynchronousFileChannel |
Java | I 'm looking for guidance for a problem logically equivalent to the following : The above construction gives the correct result but always waits for taskA to completeeven if the result is already known since taskB has completed.Is there a better construction which will allow a value to be returnedif either of the threa... | public boolean parallelOR ( ) { ExecutorService executor = Executors.newFixedThreadPool ( 2 ) ; Future < Boolean > taskA = executor.submit ( new SlowTaskA ( ) ) ; Future < Boolean > taskB = executor.submit ( new SlowTaskB ( ) ) ; return taskA.get ( ) || taskB.get ( ) ; // This is not what I want // Exception handling o... | How to perform short-circuit evaluation in Java on two parallel threads that return boolean values ? |
Java | This code seems to work in Java , violating everything I thought I knew about the language : x now has the value 7 . Of course , one ca n't just write int x = 7.4 , so this behavior seems strange and inconsistent to me . Why did the developers of Java choose such a behavior ? The question that mine was marked as a dupl... | int x = 0 ; x += 7.4 ; | Int can be incremented by a double value |
Java | We are running a setup locally where we start two instances of an Axon application . The following properties are set in application.yml : So both nodes have a single thread and they should each process a segment . They both connect to AxonServer . How do the two instances coordinate segment claims ? If I start both of... | axon : eventhandling : processors : SomeProcessorName : initialSegmentCount : 2 threadCount : 1 mode : TRACKING | Axon - Duplicate segment claim/unclaimed segments for multiple nodes and multiple databases |
Java | The task : Given a 2D array m containing whole non negative numbers , we will define a `` path '' as a collection of neighboring cells ( diagonal steps do not count as neighbor ) starting at row == 0 & & col == 0 and ending with row == m.length - 1 & & col == m [ 0 ] .length - 1.The cost of a `` path '' is the sum of t... | public class Main { public static void main ( String [ ] args ) { int arr [ ] [ ] = { { 1 , 1 , 1 } , { 1 , 1 , 1 } , { 1 , 1 , 1 } } ; printPathWeights ( arr ) ; } public static void printPathWeights ( int [ ] [ ] m ) { System.out.println ( printPathWeights ( m , 0 , 0 , new int [ m.length ] [ m [ 0 ] .length ] , 0 ) ... | Recursive headache |
Java | This is part of my code snippetI need to send the `` variableListString '' to the SAS server through IOM bridge . Java SAS API does n't give explicit ways to do it . Using CORBA and JDBC is the best way to do it ? ? Give me a hint how to do it . Is there any alternative method to do it ? ? | WorkspaceConnector connector = null ; WorkspaceFactory workspaceFactory = null ; String variableListString = null ; Properties sasServerProperties = new Properties ( ) ; sasServerProperties.put ( `` host '' , host ) ; sasServerProperties.put ( `` port '' , port ) ; sasServerProperties.put ( `` userName '' , userName ) ... | Insert variables into SAS using JAVA ( IOM Bridge ) . Should i use CORBA stubs and JDBC or is there any other alternative ? |
Java | Given the following two class definitions : Consider the following type declaration : This compiles fine in JDK-8u45 , but if we examine the specification for capture conversion , it appears ( to me ) that this declaration should result in a compile time error.In particular , the upper bound of the new type variable ca... | class C1 < T extends C1 < T > > { } class C2 < U > extends C1 < C2 < U > > { } C1 < ? extends C2 < String > > c ; | Capture conversion issue in Java , WRT reconciliation of JLS and actual JDK behaviour |
Java | Here 's a simple class that illustrates my problem : f1 , referring to App : :m1 , and being bound to a1 in f1 's call to apply , works perfectly fine - the compiler is happy and the call can be made through f1.apply just fine . f2 , referring to App : :m2 , does n't work.I 'd like to be able to define a method referen... | package com.example ; import java.util.function . * ; public class App { public static void main ( String [ ] args ) { App a1 = new App ( ) ; BiFunction < App , Long , Long > f1 = App : :m1 ; BiFunction < App , Long , Void > f2 = App : :m2 ; f1.apply ( a1 , 6L ) ; f2.apply ( a1 , 6L ) ; } private long m1 ( long x ) { r... | Java 8 - how do I declare a method reference to an unbound non-static method that returns void |
Java | Here is what I need to do : write an algorithm that will split a given integer into sums and products but each following number must be bigger than the previous one , i.e : A basic partition integer algo is not going to work since it returns numbers in a different order.I 'm not asking for a final code , I 'm just aski... | 6 = 1+5 ; 6 = 1+2+3 ; 6 = 1*2+4 ; 6 = 2+4 ; 6 = 2*3 ; | Integer partition into sums and products |
Java | I want to process a flow of client requests . Each request has its special type . First I need to initialize some data for that type , and after this I can start processing the requests . When the client type comes for the first time , I just initialize the corresponding data . After this all the following requests of ... | public class Test { private static Map < Integer , Object > clientTypesInitiated = new ConcurrentHashMap < Integer , Object > ( ) ; /* to process client request we need to create corresponding client type data . on the first signal we create that data , on the second - we process the request*/ void onClientRequestRecei... | Is this code a thread-safe one ? |
Java | I ran across this puzzle today . Obviously , this is n't correct style , but I 'm still curious as to why no output is coming out . The above has no output when run . But , when we add in brackets for the if-statement , suddenly the logic behaves as I expect . This outputs `` SHOULD OUTPUT THIS x < = 9 and z > = 7 '' .... | int x = 9 ; int y = 8 ; int z = 7 ; if ( x > 9 ) if ( y > 8 ) System.out.println ( `` x > 9 and y > 8 '' ) ; else if ( z > = 7 ) System.out.println ( `` SHOULD OUTPUT THIS x < = 9 and z > = 7 '' ) ; else System.out.println ( `` x < = 9 and z < 7 '' ) ; int x = 9 ; int y = 8 ; int z = 7 ; if ( x > 9 ) { if ( y > 8 ) Sys... | Why is my if statement behaving this way ? |
Java | I am trying some performance benchmark regarding String Pool . However , the outcome is not expected.I made 3 static methodsperform0 ( ) method ... creates a new object every time perform1 ( ) method ... String literal `` Test '' perform2 ( ) method ... String constant expression `` Te '' + '' st '' My expectation was ... | new String ( ) : 141677000 ns `` Test '' : 1148000 ns `` Te '' + '' st '' : 1059000 nsnew String ( ) : 141253000 ns '' Test '' : 1177000 ns '' Te '' + '' st '' : 1089000 nsnew String ( ) : 142307000 ns '' Test '' : 1878000 ns '' Te '' + '' st '' : 1082000 nsnew String ( ) : 142127000 ns '' Test '' : 1155000 ns '' Te ''... | String Pool : `` Te '' + '' st '' faster than `` Test '' ? |
Java | The code of the mediaplayer ( which starts under the comment : //Code of the mediaplayer begins ) is every time called when I click a button . After some time when I click the button , the sound is not played anymore.It is like : I click for 10 times and it is returning the sound when I click again it stops and does no... | public class QuizActivity extends AppCompatActivity { private ActionBarDrawerToggle mToggle ; private QuestionLibrary mQuestionLibrary = new QuestionLibrary ( ) ; private TextView mScoreView ; private TextView mQuestionView ; private Button mButtonChoice1 ; private Button mButtonChoice2 ; private Button mButtonChoice3 ... | Sound is stopping after a period of time |
Java | What is the proper way to produce and consume the streams ( IO ) of external process from Java ? As far as I know , java end input streams ( process output ) should be consumed in threads parallel to producing the process input due the possibly limited buffer size.But I 'm not sure if I eventually need to synchronize w... | public class Application { private static final StringBuffer output = new StringBuffer ( ) ; private static final StringBuffer errOutput = new StringBuffer ( ) ; private static final CountDownLatch latch = new CountDownLatch ( 2 ) ; public static void main ( String [ ] args ) throws IOException , InterruptedException {... | Java exec method , how to handle streams correctly |
Java | Have a look at this simple example of Java generics : It gets an error compiling , claiming that the types are incompatible , yet claiming that the two variables are the same type : If I change the first line of length ( ) to List < T > l = ( List < T > ) ( Object ) this.l ; , it works . Why ? | class List < T > { T head ; List < T > next ; } class A < T > { List < T > l ; public < T > int length ( ) { List < T > l = this.l ; int c = 1 ; while ( l.next ! = null ) { c++ ; l = l.next ; } return c ; } public static void main ( String [ ] args ) { A < Integer > a = new A < Integer > ( ) ; a.l = new List < Integer ... | List < T > is not equal to List < T > ? |
Java | I am thinking to use @ Nonnull annotation provided in javax.annotaiton.Nonnull which has retention policy as runtime . With this annotation I want to ensure that null is never returned by this function . I would like to put the annotation on interface so that no future implementations breaks existing code as followsNow... | public interface X { @ Nonnull public List < A > func ( ) ; } public class XImpl implements X { @ Override @ Nonnull public List < A > func ( ) { //code } } public class XImpl implements X { @ Override public List < A > func ( ) { //code } } | Is it required to use annotation on implementation when already specified at interface |
Java | I have following java sample class : It is producing a compiler warning : Type safety : Unchecked cast from capture # 1-of ? extends Object to TI can perfectly obtain the exact T object , if I just do : Which it knows perfectly is of Type T.Why I am not able to create a new instance of that class ? How could I fix it ?... | public class TestClass { public static < T > void method ( List < T > objects ) throws Exception { for ( int i = 0 ; i < objects.size ( ) ; i++ ) { // Create new object of the same class T obj = ( T ) objects.get ( i ) .getClass ( ) .newInstance ( ) ; } } } T obj = objects.get ( i ) ; | How to create new object of Generic Type T from a parametrized List < T > |
Java | The Java class I am trying to subclass has a method like : I ca n't figure out how to override that method . The Java class I am subclassing from does not use generics . In Scala I tried : But the compiler gives me the error message that it overrides nothing..The heart of the problem is that Scala expects type paramete... | public abstract void foo ( Map var1 ) ; override def foo ( var1 : java.util.Map [ Int , Int ] ) { } | In Scala , how to override a method that takes a java.util.Map |
Java | I have existing codebase that sometimes uses ArrayList or LinkedList and I need to find a way to log whenever add or remove is called to track what has been either added or removed.What is the best way to make sure I have logging in place ? So for example.andNot sure if I can intercept add method to achieve this or cre... | ArrayList < Integer > list = new ArrayList < Integer > ( ) ; list.add ( 123 ) ; LinkedList < Integer > anotherNewList = new LinkedList < Integer > ( ) ; anotherNewList.add ( 333 ) ; | How to log List interface method for existing code |
Java | I have a synchronized method that appears to be 'using ' the synchronization for significantly longer than it should . It looks something like ; The call looks like ; Where generateParameter ( ) is known to be a very expensive ( takes a long time ) call . My thinking is that the mutex on the myMethod class is blocked d... | public static synchronized void myMethod ( MyParameter p ) { //body ( not expensive ) } myMethod ( generateParameter ( ) ) ; | Java synchronized method with expensive parameters |
Java | While practicing Reflection I came to know about SelfComparable Interface in Collections classWhat does this interface use for ? | interface java.util.Collections $ SelfComparable | What does self comparable interface do in Collections Class ? |
Java | The description of Local.getCountry ( ) says : Returns the country/region code for this locale , which should either be the empty string , an uppercase ISO 3166 2-letter code , or a UN M.49 3-digit code.I wonder when is an ISO 3166 2-letter code returned and when a UN M.49 3-digit code ? Example : | Locale locale = new Locale ( `` de '' , `` AT '' ) ; Log.i ( TAG , `` country code : `` + locale.getCountry ( ) ) ; //returns `` AT '' which is an ISO 3166 2-letter code | When does Local.getCountry ( ) return a UN M.49 3-digit code instead of an ISO 3166 2-letter code ? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.