lang
stringclasses
4 values
desc
stringlengths
2
8.98k
code
stringlengths
7
36.2k
title
stringlengths
12
162
Java
I have this types : I have a method that returns a List < T > where T is PrecisionControlGraphic or AccuracyControlGraphic depending on type parameter : The code below works properly : I 'd like to know why this other one does n't : Thanks .
abstract class ControlGraphic { // ... } class PrecisionControlGraphic extends ControlGraphic { // ... } class AccuracyControlGraphic extends ControlGraphic { // ... } private < T extends ControlGraphic > List < T > getGraphics ( ) { List < T > graphics = new LinkedList < T > ( ) ; for ( ControlGraphic graphic : getGra...
Method type-parameterized does n't work in for loop
Java
Suppose we have a class A , and a class B , which inherits from class A.Let 's say we have : The following casting : will give us run-time error.However , if we use wildcard and define the following set : we have no problem to do the casting : Why casting a collection of a wildcard is allowed , while casting a collecti...
Set < A > setOfAs = new HashSet < > ( ) ; ( ( Set < B > ) setOfAs ) Set < ? extends A > setOfAs = new HashSet < > ( ) ; ( ( Set < B > ) setOfAs )
Java : why is casting possible on wildcard collections ?
Java
I have this code which I want to refactor using a functional style , using Java 8 . I would like to remove the mutable object currentRequest and still return the filtered request . The aim is to pass a request to the filter.doFilter method , and take the output and pass it back into the filter.doFilter method , and con...
HttpRequest currentRequest = httpRequest ; for ( Filter filter : filters ) { currentRequest = filter.doFilter ( currentRequest ) ; } HttpRequest filteredRequest1 = filters.get ( 0 ) .doFilter ( currentRequest ) ; HttpRequest filteredRequest2 = filters.get ( 1 ) .doFilter ( filteredRequest1 ) ; HttpRequest filteredReque...
JAVA 8 pass return value back into same method x number of times
Java
Please read the 2 comments in the following code.Is this possible ? Is there a keyword to access the main class object from a function inside the object ?
public class Field extends LinearLayout { public void init ( ) { setOnFocusChangeListener ( new OnFocusChangeListener ( ) { @ Override public void onFocusChange ( View v , boolean hasFocus ) { // I want to access the main object 'Field ' here ( not the class , the object ) } } ) ; // to be clear the object referred as ...
How can I access the main class object from a function inside the class in Java ?
Java
I am using the GWT library . There is a base class called Widget that all Widgets inherit from . Some Widgets implement certain interfaces ( for example HasText ) , others do not . Sometimes I wish to guarantee that something being passed as an argument to a function is of a certain class AND implements a certain inter...
public void fx ( I_AM_A_Widget_AND_IMPLEMENT_INTERFACE_HasText x ) { //do stuff with x , which is guaranteed to be a Widget AND implement HasText }
Can I guarantee typing on an argument 's class AND interface ?
Java
I was learning string concepts , so wrote a code , expected a different output but got something very unexpected . when I execute the above code i get the output as : if i 've done something wrong please let me know.Since strings are immutable , which implies we should get the output of the `` Str1 Modified '' as `` HE...
class stringmute { public static void main ( String [ ] args ) { String s1= '' Hello `` ; //string one . System.out.println ( `` Str1 : '' +s1 ) ; String s2= s1+ '' world '' ; //New String . System.out.println ( `` Str2= '' +s2 ) ; s1=s1+ '' World ! ! `` ; //This should produce only Hello right ? System.out.println ( `...
java strings inmutable but the code does n't shows that
Java
I have a text view with icon rendered in the TextView . It has an image . I have set on the left of the text . But I need to set the icon as a circular shape.How can I design this in java ? My code which set on the left side.How can I design the circular image for the above textview drawableleft image .
textview.setCompoundDrawablesWithIntrinsicBounds ( image , 0 , 0 , 0 ) ; < TextView android : id= '' @ +id/text '' android : layout_width= '' wrap_content '' android : layout_height= '' wrap_content '' android : layout_gravity= '' fill_vertical '' android : ellipsize= '' end '' android : layout_marginTop= '' 5dp '' and...
How to design drawable left icon as circular ( added using setCompoundDrawablesWithIntrinsicBounds ) in Textview using java code ( not xml )
Java
If I have a method that takes a single-method interface as an argument , I can call it like this : But if I have to call foo millions of times in a tight loop , I might prefer to avoid creating a new instance of the anonymous class every time through the loop : Now if I replace the anonymous class with a lambda express...
foo ( new Bar ( ) { @ Override public String baz ( String qux ) { return modify ( qux ) + transmogrify ( qux ) ; } } final Bar bar = new Bar ( ) { @ Override public String baz ( String qux ) { return modify ( qux ) + transmogrify ( qux ) ; } } ; while ( ... ) { foo ( bar ) ; } while ( ... ) { foo ( qux - > modify ( qux...
Lambda expression and equivalent anonymous class
Java
I 'm pretty new to java streams and am trying to determine how to find the max from each list , in a list of lists , and end with a single list that contains the max from each sublist.I can accomplish this by using a for loop and stream like so : I 've looked into the flatMap api , but then I 'll only end up with a sin...
// databaseRecordsLists is a List < List < DatabaseRecord > > List < DatabaseRecord > mostRecentRecords = new ArrayList < > ( ) ; for ( List < DatabaseRecord > databaseRecords : databaseRecordsLists ) { mostRecentRecords.add ( databaseRecords.stream ( ) .max ( Comparator.comparing ( DatabaseRecord : :getTimestamp ) ) ....
Find Max of Multiple Lists
Java
In Android i create an abstract class that extends View ( an Android class to which i have no access ) .The abstract class overrides the Views however i added the final keyword here.The point is , i create an abstract method that the subclasses are supposed to use instead of the onDraw . So i prevent the onDraw from be...
@ Overrideprotected final void onDraw ( Canvas canvas ) { if ( conditions ) return ; // child classes should only draw if this class gives the ok subDraw ( canvas ) ; } protected abstract void subDraw ( Canvas canvas ) ;
Is it `` ok '' to add the final keyword to an inherited/overridden method ?
Java
Given this stacktrace : And this try-catch : I can not modify the code for SpecificException nor the method that wraps this exception into a RuntimeException.Is there a better way to catch only SpecificException ?
java.lang.RuntimeException : ... Caused by : com.mypackage.SpecificException try { ts.init ( ) ; } catch ( RuntimeException e ) { if ( e.getCause ( ) instanceof SpecificException ) { //do something } else { throw e ; } }
Is there a better way to catch only specific cause ( s ) of an exception ?
Java
I 've looked around and so far have n't seen any way of having both a lower and upper bound on the same wildcard type in java . I 'm not sure if it is possible and am leaning towards it being a current limitation of wildcards in java.An example of what I 'm looking for is below.Looking at the WildcardType.java class fo...
public class A { } public class B extends A { } public class C extends B { } public class D extends C { } public static void main ( String [ ] args ) { List < A > a = Arrays.asList ( new A ( ) ) ; List < B > b = Arrays.asList ( new B ( ) ) ; List < C > c = Arrays.asList ( new C ( ) ) ; List < D > d = Arrays.asList ( ne...
Lower and Upper Bound for Java Wildcard Type
Java
Consider the following code : Printed : It seems that around this hour Calendar jumps from hour 2 to hour 4 ( not necessarily a problem in general if it corresponds to DST change ) .I am using AdoptOpenJDK 1.8.0_242 , but I 've also checked on HotSpot 1.8.0_181 - the same issue.Why does Calendar report a different hour...
ZoneId zoneId = ZoneId.of ( `` America/Los_Angeles '' ) ; long currMillis = 2530778400000L ; Instant curr = Instant.ofEpochMilli ( currMillis ) ; LocalDateTime dt = LocalDateTime.ofInstant ( curr , zoneId ) ; //the local one just for completenessZonedDateTime zdt = ZonedDateTime.ofInstant ( curr , zoneId ) ; Calendar c...
Why do ZonedDateTime and Calendar disagree on the hour in year 2050 ?
Java
I 'm doing some self-study over the summer , and I came across this problem I 'm unsure of , and I was wondering if anyone could help out . I 'm unsure of the last number , but I included my previous answers if anyone would be willing to check those as well . This is not homework for any class , I just want to make sur...
1. void m ( Object o , long x , long y ) 2. void m ( String s , int x , long y ) 3. void m ( Object o , int x , long y ) 4. void m ( String s , long x , int y ) Object o ; String v ; int a ; long b ; m ( v , a , b ) ; Calls 2 , because it is the most specific.m ( v , a , a ) ; Not legal , because 2 and 4 could both be ...
Legal calls and determination of overloaded functions in Java
Java
I 'm using removeIf to remove certain objects from a list if their name or code is null : Is there a way I can get the actual items t that have been removed here ? Maybe a list of the removed items , or better yet , a stream of the removed items ? Thanks
tables.removeIf ( t - > ( ( t.getName ( ) == null ) || ( t.getCode ( ) == null ) ) ) ;
How to stream the removed items in java removeIf ?
Java
Strings are added to the array , to determine whether the list is ordered by increasing the length of the string . If not , print the index of the first element that violates such ordering.Everything works correctly if the strings in the array are different , for example , enterAnswer : index ( wa ) 3 output.but if it ...
11313476Neutralwa 12312345123 public class Solution { public static void main ( String [ ] args ) throws IOException { Scanner scan = new Scanner ( System.in ) ; ArrayList < String > list = new ArrayList < > ( ) ; for ( int i = 0 ; i < 4 ; i++ ) { list.add ( scan.nextLine ( ) ) ; } int count = 0 ; for ( int i = 0 ; i <...
can not determinate index in array
Java
I have this code : But if most significant bit of code is equal to 1 ( from 9 to F ) a comes negative value . All other variables works fine.Why this happen ?
int code = 0x92011202 ; int a = ( code & 0xF0000000 ) > > 28 ; int b = ( code & 0x0F000000 ) > > 24 ; // .. int n = ( code & 0x0000000F ) ;
And bitwise operation gets negative value
Java
So is it valid to check for class equality in this way : Probably the answer is yes because Class class does not override equals ( ) so it looks like Object.equals ( ) applies for Class equality . But , I would be interested if this is documented somewhere else . Thanks .
if ( object.getClass ( ) == anotherObject.getClass ( ) ) { }
Are instances of Class class guaranteed to be singletons per classloader ?
Java
Following is my simplified graph implementationAnd I am writing code to find if 2 nodes are connected in a directed graph . I am getting compilation errorI am getting error at line start.getchildren
import java.util.ArrayList ; import java.util.List ; public class TreeNode < E extends Comparable < E > > { private E data ; private List < TreeNode < E > > children ; public TreeNode ( E value ) { data = value ; children = new ArrayList < > ( ) ; } public E getData ( ) { return data ; } public void setData ( E data ) ...
can not convert list to list error in java generics
Java
So We know that a local variable has to be initialized in order to be used in if-else-if construct.As an example , the following code will not compile.But , if you change else if ( price < =11 ) to else or initialize the local variable String model to some random value , the code will compile successfully.My question i...
public class Test { public static void main ( String ... args ) { double price= 11 ; String model ; if ( price > 10 ) { model = '' smartphone '' ; } else if ( price < =11 ) { model= '' not smart phone '' ; } System.out.println ( model ) ; } }
Why does a local variable get initiated in if-else constructs but not in if-else-if constructs ?
Java
I noticed that if I write something like : Android Studio ( and probably IntelliJ too ) shows the suggestion `` Can be replaced with method reference '' .Instead , if I writeAndroid Studio does n't say anything . But in both cases I can use method references : and , respectively.Are these two forms functionally differe...
View view = getView ( ) ; foo ( error - > view.showError ( error ) ) ; foo ( error - > getView ( ) .showError ( error ) ) ; foo ( view : :showError ) foo ( getView ( ) : :showError )
Method reference of an object in variable vs. returned by method
Java
I have some JSON schemas which exist in a hierarchy : A extends B extends C. I am generating Java classes from these using jsonschema2pojo and they get generated into a matching class hierarchy.Because of the way I am generating the classes , I do n't have fine-grained control of which annotations can be applied to whi...
{ `` propertyOfA '' : `` razz '' , `` propertyOfA '' : `` jazz '' , `` propertyOfA '' : `` baz '' , `` propertyOfB '' : `` bar '' , `` propertyOfC '' : `` foo '' } { `` propertyOfC '' : `` foo '' , `` propertyOfB '' : `` bar '' , `` propertyOfA '' : `` razz '' , `` propertyOfA '' : `` jazz '' , `` propertyOfA '' : `` b...
How can I configure Jackson to serialize base classes first ?
Java
I have never come across such expression in Java . It is not even a switch caseDo you have any idea what this does ?
//no code above to make it look like a switch case or loop abc : { // do some stuff break abc ; }
What does statement `` abc : { .. } '' mean ?
Java
I want to switch keys of map and a map inside it : I 've tried using streams , but ca n't create the inside map or how to access key and value from the original inside map separately.//So far I 've tried :
Map < X , Map < Y , Z > - > Map < Y , Map < X , Z > originalMap.entrySet ( ) .stream ( ) .collect ( Collectors.toMap ( Map.Entry : :getValue , Map.Entry : :getKey ) ) ;
Map < X , Map < Y , Z > to Map < Y , Map < X , Z >
Java
This question can be stupid , but I just want to know , is there any difference ?
class A { // common code private int field ; public void setField ( int field ) { this.field = field ; } //way 1 public A ( int field ) { this.field = field ; } //way 2 public A ( int field ) { setField ( field ) ; } }
Which way of setting fields value is better and why ?
Java
I wrote the following code : Why did I get this warning ? The declation of the inner type B does n't contain type parameter , therefore it 's not a generic type . Moreover , the specification gives us the following : A class is generic if it declares one or more type variablesThe class B does n't declare the type varia...
public class Test < T > { public void method ( ) { B b = new B ( ) ; } public class B { } } //Some method in some class contains the following lines Test < Integer > t = null ; Test.B b = t.new B ( ) ; //warning Test.B is a raw type
Understanding inner generic classes
Java
In the following scenario , the boolean 'done ' gets set to true which should end the program . Instead the program just keeps going on even though the while ( ! done ) is no longer a valid scenario thus it should have halted . Now if I were to add in a Thread sleep even with zero sleep time , the program terminates as...
public class Sample { private static boolean done ; public static void main ( String [ ] args ) throws InterruptedException { done = false ; new Thread ( ( ) - > { System.out.println ( `` Running ... '' ) ; int count = 0 ; while ( ! done ) { count++ ; try { Thread.sleep ( 0 ) ; // program only ends if I add this line ....
Program not terminating after loop completion
Java
I am remaking minesweeper for practice , and wrote this bit of code to avoid IndexOutOfBounds errors . Is there a way of avoiding this so I do n't have to explicitly write out an if statement every possible error ? I thought of making each array 2 indexes larger , and just ignoring the first and last index . Am I missi...
if ( row > 0 & & col > 0 ) ray [ row - 1 ] [ col - 1 ] += 1 ; if ( row > 0 ) ray [ row - 1 ] [ col ] += 1 ; if ( row > 0 & & col < height - 1 ) ray [ row - 1 ] [ col + 1 ] += 1 ; if ( col > 0 ) ray [ row ] [ col - 1 ] += 1 ; if ( col < height - 1 ) ray [ row ] [ col + 1 ] += 1 ; if ( row < width - 1 & & col > 0 ) ray [...
Is there any way of avoiding this block of code ?
Java
I 'm teaching myself algorithms and I 'm sorry if my title is incorrect ! I do n't understand how to implement this in Java.I do n't know how to implement the following parts in Java .
if x = 0 : return ( q , r ) = ( 0,0 ) ( q , r ) = divide ( ⌊x/2⌋ , y ) q=2·q , r=2·rif x is odd : r=r+1 if r≥y : r=r−y , q=q+1 return ( q , r ) ( q , r ) = ( 0,0 ) ( q , r ) =divide ( ⌊x/2⌋ , y ) return ( q , r )
Learning Algorithms on myself , how do you implement tuples in java ?
Java
I 'm having problems making a copy of an object to use and change values for that copy , instead it changes the values for both of my objects . Code for the object.And code for the function that I 've been trying to get to workSo when I try to insert the value 1 in the new object the old one still changes .
public class Board { private int [ ] [ ] board ; public Board ( ) { board = new int [ 9 ] [ 9 ] ; } public Board ( int [ ] [ ] layout ) { board = layout ; } public int [ ] [ ] getBoard ( ) { return board ; } public int getBoardValue ( int y , int x ) { return board [ y ] [ x ] ; } public void insertValue ( int v , int ...
Ca n't copy my object and change values
Java
I 'm reading ArrayList implementation and ca n't understand one thing in this method : I do n't understand what this oldData array is used for : To me it seems like there is absolutely no sense in this local variable inside ensureCapacity method .
public void ensureCapacity ( int minCapacity ) { modCount++ ; int oldCapacity = elementData.length ; if ( minCapacity > oldCapacity ) { Object oldData [ ] = elementData ; int newCapacity = ( oldCapacity * 3 ) /2 + 1 ; if ( newCapacity < minCapacity ) newCapacity = minCapacity ; // minCapacity is usually close to size ,...
oldData in ArrayList implementation
Java
I 'm working on an old project , which uses Java . It is based on Java 7 . But it 's now all Kotlin classes for new code.In our gradle it is stillJust curious , is there a need to upgrade to Java 8 , if moving forward I 'll be writing in Kotlin ? From https : //developer.android.com/studio/write/java8-support , it look...
compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 targetCompatibility JavaVersion.VERSION_1_7 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 }
Do I need to upgrade to Java 8 for my Android Studio if I 'm just writing in Kotlin ?
Java
I have an assignment to write an Enum `` Weekdays '' which constants are with more than one parameters.Does the Enum type has a short way to iterate over its values by their property ( 1,2,3,4,5,6,7 - from my code ) or I have to write another data type where to store the requested data ? That 's my code : The problem i...
public enum Weekdays { MON ( `` Monday '' , `` Mon '' ,1 ) , TUE ( `` Tuesday '' , '' Tue '' ,2 ) , WED ( `` Wednesday '' , '' Wed '' ,3 ) , THU ( `` Thursday '' , '' Thu '' ,4 ) , FRI ( `` Friday '' , `` Fri '' ,5 ) , SAT ( `` Saturday '' , '' Sat '' ,6 ) , SUN ( `` Sunday '' , '' Sun '' ,7 ) ; private String fullName...
How to iterate over an enum by its int value ?
Java
There is a Class Role , having data member as String roleName . I have to sort a list of Role.While sorting I need to check NPE and trim roleName also . So I usedI can suppress the null pointer exception but ca n't use trim.Using this I ca n't avoid NPE .
roleList.sort ( Comparator.comparing ( Role : :getRoleName , Comparator.nullsLast ( Comparator.naturalOrder ( ) ) ) ) ; roleList.sort ( ( x , y ) - > x.getRole ( ) .trim ( ) .compareTo ( y.getRole ( ) .trim ( ) ) ) ;
How to use trim and avoid NPE by using collections.sort ?
Java
I have searched all problems like this but I could n't find the solution.nametext and occtext are extremely small.I tried new JTextField ( 20 ) , and string version , I tried setPreferredSize as above class , and also I tried setColumn but none of them works .
public class FormPanel extends JPanel { private JLabel namelabel ; private JLabel occlabel ; private JTextField nametext ; private JTextField occtext ; private JButton okButton ; public FormPanel ( ) { Dimension dim = getPreferredSize ( ) ; dim.width = 250 ; setPreferredSize ( dim ) ; namelabel = new JLabel ( `` Name :...
java unreasonable jtextfield sizing issue
Java
Given the following methods:1 ) Is the only difference in the above methods readability or is there a micro-optimization `` benefit '' in methodTwo ( ) ? 2 ) Should the defining of local variables in a narrow scope be shunned and avoided when possible ? ( I can see methodTwo becoming unreadable if several calculations ...
public int methodOne ( ) { int total = local_int_one + local_int_two ; return total ; } public int methodTwo ( ) { return local_int_one + local_int_two ; }
Local variables : Programming Practices
Java
I am trying to run a for loop inside an infinite while loop . The code does n't run as intended when there 's no print statement , but when there is a print statement , it runs fine . Here is the code : This is just a small example taken from a much bigger loop . How can I fix this ?
class Test implements Runnable { public static int varint = 0 ; public static void main ( String args [ ] ) { Thread x = new Thread ( new Test ( ) ) ; int i ; x.start ( ) ; while ( true ) { System.out.println ( `` Hello World '' ) ; //If this is n't included , //the exit statement is n't executed for ( i=0 ; i < varint...
Java : For loop in while loop not running unless println statement included
Java
Count number of content using stream With Java 8 and Streams I want the count of the Content elements which is of contentType equal to the video.To count topic I tried this :
class Subject { private String id ; private String name ; private List < Unit > units ; } class Unit { private String id ; private String name ; private List < Topic > topics ; } class Topic { private String id ; private String name ; private List < Content > contents ; } class Content { private String id ; private Str...
Count number of nested elements using stream api java
Java
I 'm learning about the design patterns and I encountered a problem which I cant resolve . I 'm writing a client/server script . The administrator client send a task with its task data in json format , and the server should instantiate an object accordingly to the recieved task type , and fill its constructor with corr...
public class StartProcessing implements ITask { private final IProcessor dataProcessor ; public StartProcessing ( IProcessor dataProcessor ) { this.dataProcessor = dataProcessor ; } @ Override public void ProcessTask ( ) { this.dataProcessor.StartProcess ( ) ; } } public class StartQueueFiller implements ITask { privat...
Java what design pattern should I use for object instantiation if I have different constructor but same interface ?
Java
I am developing an eclipse plugin which depends on Eclipse platform 4.2 ( Juno ) and can not be installed on older versions of eclipse.When the user tries to install my plugin ( via update site ) on an old eclipse , the Eclipse installer stops him and shows the following message : Not many people can understand from th...
Can not complete the install because one or more required items could not be found.Software being installed : Feature 1.0.3 ( com.test.feature.feature.group 1.0.3 ) Missing requirement : Test 1.0.3 ( com.test 1.0.3 ) requires 'bundle org.eclipse.core.runtime 3.8.0 ' but it could not be foundCannot satisfy dependency : ...
Eclipse Plugin Development : Is there a way to control installer messages about missing dependencies of my plugin ?
Java
In my casting class , teacher taught us an interesting fact as follows.We got an errorAnd then we changed the code as followsWe got the correct output . As for the reason , he told that when we modify a variable final the variable is stored in the smallest data type possible . In this case was a byte . That 's the reas...
class Casting { public static void main ( String args [ ] ) { int i = 10 ; byte b = i ; System.out.println ( b ) ; } } java:5 : possible loss of precision class Casting1 { public static void main ( String args [ ] ) { final int i = 10 ; byte b = i ; System.out.println ( 10 ) ; } } 10 class A { void m ( int i ) { System...
final casting concept does n't apply for overloading
Java
I need to find out when I 'm really close to the OutOfMemoryError so I can flush results to file and call runtime.gc ( ) ; . My code is something like this : Is there a better way to do this ? Can someone give me a hand please ? EDITI understood that I am playing with fire this way so I reasoned to a more solid and sim...
Runtime runtime = Runtime.getRuntime ( ) ; ... if ( ( 1.0 * runtime.totalMemory ( ) / runtime.maxMemory ( ) ) > 0.9 ) { ... flush results to file ... runtime.gc ( ) ; }
How to determine in java when I 'm near to the OutOfMemoryError ?
Java
In some cases the following program actually stops ( because of Thread 2 ) , when it should n't . Why is that happening ? Thread 1 : Basically locks global and does a while loop.Thread 2 : Attempts to get a lock on global and it it succeeds , proceeds to stop the program.BUT~ Thread 1 is started first , so technically ...
static Integer global = 30 ; public static synchronized void setVar ( int x , String from ) { System.out.println ( global + `` `` + x + `` - `` + from ) ; global = x ; } public static void main ( String [ ] args ) { Thread thr1 = new Thread ( new Runnable ( ) { @ Override public void run ( ) { synchronized ( global ) {...
Threading and synchronization issues
Java
I 've got an object as belowA list of these Models is being returned via the data layer.Now I want to create a Map < String , List < Model > > with the key being the `` key '' field in the Modelclass.There are multiple duplicate `` key '' s with different data values.I have the below existing solution but need a simple...
public class Model { private String key ; private String data1 ; private String data2 ; private String data3 ; // getters } List < Model > models = modelRepo.getAllModels ( ) ; Set < String > keys = models.stream ( ) .map ( Model : :getKey ) .collect ( Collectors.toSet ( ) ) ; Map < String , List < Model > > result = n...
Get Map < String , List < Object > > from List < Object > where the key is one of the fields of the objects
Java
Based on the MS graph documentation , I saw that i can update a driveItem ( file ) and put it in a specific sharepoint drive . The application is running as a daemon application ( without user login ) .For this I use this entry point : I try to code using a main class and passing existing parameters . To update a docum...
PUT /drives/ { drive-id } /items/ { item-id } /content UpdateDocumentResponseModel updatedDocument = fileGraphs.updateDocument ( token , DRIVELIBID , DOCUMENTID , INPUTPATH , DOCUPDATE ) ; public UpdateDocumentResponseModel updateDocument ( String accessToken , String driveLibId , String documentId , String inpuPath , ...
Microsoft graph : Updating a document with a Put request Java
Java
In Java Collection classes , I have noticed very often codes like below What does head = ( h + 1 ) & ( elements.length - 1 ) ; do ? Why is & operator used here and what purpose does it serve.My Question is not how & works , but what 's its use here.Can anyone explain it ?
//ArrayDeque public E pollFirst ( ) { int h = head ; @ SuppressWarnings ( `` unchecked '' ) E result = ( E ) elements [ h ] ; // Element is null if deque empty if ( result == null ) return null ; elements [ h ] = null ; // Must null out slot head = ( h + 1 ) & ( elements.length - 1 ) ; return result ; }
How does & bit operator work here ?
Java
I ran this test with -Xmx256M to determine the max object size that I can create on heapand got 171M . Is there a way to calculate this size ?
for ( int m = 128 ; ; m++ ) { try { byte [ ] a = new byte [ m * 1024 * 1024 ] ; } catch ( OutOfMemoryError e ) { System.out.println ( m + `` M '' ) ; break ; } }
How to calculate the max object size if max heap size is known ?
Java
I have the following code which builds and works fine under JDK8 : And : This code fails to compile under JDK11 with the following error : Could somebody please explain what it 's unhappy about and how to fix it ?
@ FunctionalInterfacepublic interface ThrowingFunction < T , R , E extends Throwable > { R apply ( T t ) throws E ; static < T , R , E extends Throwable > Function < T , R > unchecked ( ThrowingFunction < T , R , E > function ) { return t - > { try { return function.apply ( t ) ; } catch ( Throwable e ) { throw new Run...
Weird java.lang.InstantiationException and java.lang.NoSuchMethodException after upgrading from JDK8 to JDK11
Java
I have a simple webapp that acquires connection from tomcat JDBC datasource . To track the connection usage , I 'm planning to implement logging while opening and closing connection . The logging supposed to print something like this.My open and close methods are like this.Here I 'm using connection.toString ( ) as the...
20151230143623.947 [ Thread-3 ] INFO [ DataSourceManager:19 ] Opened connection identified by id : BlahBlahBlah120151230143623.947 [ Thread-3 ] INFO [ DataSourceManager:19 ] Closed connection identified by id : BlahBlahBlah1 Connection openConnection ( String JNDILookupName ) throws Exception { Connection connection = ...
How to uniquely name an object
Java
I am working on a format parser in Java and have some trouble with that.The format is stored so that users can change it to their likings.format : ' [ prefix ] [ name ] [ suffix ] : [ msg ] 'To put my values in the format I use String.replace ( ) in Java.This will result in the output Hello username World : Test messag...
format = getFormatTemplate ( ) ; // ' [ prefix ] [ name ] [ suffix ] : [ msg ] 'format = format.replace ( `` [ prefix ] '' , prefix ) ; // prefix = `` Hello '' ; format = format.replace ( `` [ name ] '' , name ) ; // name = `` username '' ; format = format.replace ( `` [ suffix ] '' , suffix ) ; // suffix = `` World ''...
Parse user-defined format in Java
Java
I got a warning message on Object Casting while compiling my code . I have no idea how to fix it with my current knowledge ... .Let 's say I have a Generic Object MyGenericObj < T > it is extends from a non-Generic Object MyObjHere is a sample code : Could you please let me know what 's the proper way of doing this ? A...
MyObj obj1 = new MyGenericObj < Integer > ( ) ; if ( obj1 instanceof MyGenericObj ) { //I was trying to check if it 's instance of MyGenericObj < Integer > //but my IDE saying this is wrong syntax ... . MyGenericObj < Integer > obj2 = ( MyGenericObj < Integer > ) obj1 ; //This line of code will cause a warning message ...
What 's the proper way to check the object type for Generic object ?
Java
After submitting a COMPSs application I have received the following error message and the application is not executed.I am using COMPSs 1.3.Why is this happenning ?
MPI_CMD=mpirun -timestamp-output -n 1 -H s00r0/apps/COMPSs/1.3/Runtime/scripts/user/runcompss -- project=/tmp/1668183.tmpdir/project_1458303603.xml -- resources=/tmp/1668183.tmpdir/resources_1458303603.xml -- uuid=2ed20e6a-9f02-49ff-a71c-e071ce35dacc/apps/FILESPACE/pycompssfile arg1 arg2 : -n 1 -H s00r0/apps/COMPSs/1.3...
COMPSs - Nodes already filled error
Java
I 'm familiar with standard comparisons using the Comparable interface , although today I 'm having some trouble when I want to compare several different variables.I basically want to implement a compareTo method that yields the result -1 only when the following if statement is true : Although , I 'm not sure if this i...
if ( o.maxX > minX & & o.maxY > minY & & o.minZ < maxZ ) public int compareTo ( IsoSprite o ) { if ( o.maxX > minX & & o.maxY > minY & & o.minZ < maxZ ) { return -1 ; } else if ( o.maxX < minX & & o.maxY < minY & & o.minZ > maxZ ) { return 1 ; } return 0 ; } public int compareTo ( IsoSprite o ) { if ( o.maxX > minX & &...
Using comparable to compare different variables
Java
As I understand it from several tutorials , RuntimeExceptions are actually not supposed to be caught , because they shall reveal inappropiate usage of methods , especially APIs , correct ? Furthermore , one might assume that the program is not able to recover from RuntimeExceptions.Now , I experienced a case where I mi...
firstDecimalChar = formattedValue.charAt ( dotPosition + 1 ) ;
Handling RuntimeExceptions in certain circumstances valid ?
Java
SO an IPv4 array is passed to this method , and if valid , creates a deep copy of the array in the instance variable `` parts '' is all I have so far . What could I be missing ? EDIT : made one simple change : toAnd a JUnit test works UNTIL What is causing it to stop there ?
/** * If the ip address from the array passed ( data ) is valid , * makes a deep copy of the array passed in the instance variable parts . * For example , if data = { 192,168,0,1 } , parts should become { 192,168,0,1 } * by copying each item of data into corresponding item in parts . * If the ip address passed is inval...
How to create deep copy of array passed , if the array is valid ?
Java
We can get away with this in .NET : ... but in Java , the same code will result in a compilation error.That 's interesting , given that even if the type information is gone at runtime , one would expect the information about the number of type parameter to still be there.If this limitation is related to type erasure , ...
interface I < A > { } interface I < A , B > { }
Why does n't Java allow overloads based on type parameters ?
Java
I am reading Network Programming in Java by Elliotte and in the chapter on Threads he gave this piece of code as an example of a computation that can be ran in a different threadTo use this thread , he gave an approach which he referred to as the solution novices might use . The solution most novices adopt is to make t...
import java.io . * ; import java.security . * ; public class ReturnDigest extends Thread { private String filename ; private byte [ ] digest ; public ReturnDigest ( String filename ) { this.filename = filename ; } @ Overridepublic void run ( ) { try { FileInputStream in = new FileInputStream ( filename ) ; MessageDiges...
Questions about Threads and Callbacks in Java
Java
While writing my code for a computer dating assignment in which we see the compatibility of an array of four objects , my code printed strangely . ( Eclipse did n't give me an error/warning at first ) .Code : When I tried to print things out , they appeared like this : Fit between Elizabeth Bennett and Elizabeth Bennet...
System.out.print ( `` Fit between `` + profile1.getTitle ( ) + `` and `` + profile2.getTitle ( ) + `` : \n `` + + '\t ' + profile1.fitValue ( profile2 ) + '\n ' ) ; System.out.print ( `` Fit between `` + profile1.getTitle ( ) + `` and `` + profile2.getTitle ( ) + `` : \n `` + '\t ' + profile1.fitValue ( profile2 ) + '\...
Java : Is `` 9 '' appearing in my run an Eclipse bug ?
Java
Usually , if I know beforehand all the keys of a map , I instantiate it like this : Is there any way to do this directly without needing to iterate through the list ? Something to the effect of : My first thought was to edit the map 's keyset directly , but the operation is not supported . Is there other way I 'm overl...
List < String > someKeyList = getSomeList ( ) ; Map < String , Object > someMap = new HashMap < String , Object > ( someKeyList.size ( ) ) ; for ( String key : someKeyList ) { someMap.put ( key , null ) ; } new HashMap < String , Object > ( someKeyList )
Is it possible to instantiate a Map with a list of keys ?
Java
In Java 8 the close ( ) method for InflaterInputStream is as shown belowusesDefaultInflater is a boolean that is only true if the constructor below is usedAny other constructor such as this one below results in this boolean being set to falseAs a result , unless you use the default constructor the end ( ) method is not...
public void close ( ) throws IOException { if ( ! closed ) { if ( usesDefaultInflater ) inf.end ( ) ; in.close ( ) ; closed = true ; } } public InflaterInputStream ( InputStream in ) { this ( in , new Inflater ( ) ) ; usesDefaultInflater = true ; } new InflaterInputStream ( decryptInputStream , new Inflater ( ) , 4096 ...
Why does Java 's InflaterInputStream ( and other similar classes ) only conditionally call end on it 's internal Inflater
Java
I have a function which maps a class object to an instance of this class.Basically : I can define this function within a method but when trying to put this in a member variable , the compiler complains because the type T is unknown.So , T is not specific to the enclosing object . It might differ from call to call . Wha...
Function < Class < T > , T > fun ; public class A { public < T > T get ( Class < T > clazz ) { ... } } public class B { < T > Function < Class < T > , T > fun ; public < T > T get ( Class < T > clazz ) { return fun.apply ( clazz ) ; } } public class B { Function < Class < ? > , ? > fun ; public < T > void setFun ( Func...
Function with generic type as member variable
Java
It 's been a while since I touched generics in Java , I have this : In truth , MyGenericType requires a generic parameter , since it is defined like this : I declared x with pre-emptive type-erasure of MyGenericType because I did n't want to make an empty marker interface just for the sake of grouping things . Will thi...
Map < List < MyGenericType > , Set < List < MyGenericType > > > x = new HashMap < > ( ) ; public class MyGenericType < X > { }
In Java , can one get away with using `` raw unparameterised class '' -es instead of using dummy interfaces ?
Java
I have a class with a type parameter.And I thought I can add some method for conveniency so I did.And I just realized that I can do this.Are those two sets of methods are equivalent ? Which way ( or style ) is prefer ?
class MyObject < IdType > { @ Setter @ Getter private IdType id ; } < T extends MyObject < ? super IdType > > void copyIdTo ( T object ) { object.setId ( getId ( ) ) ; } < T extends MyObject < ? extends IdType > > void copyIdFrom ( T object ) { object.copyIdTo ( this ) ; } void copyIdTo ( MyObject < ? super IdType > ob...
Can explicit type parameters redundant ?
Java
I am building a simple spring boot blog app . This app has two entities user and post . The user table holds user data and has the primary key as Id and the post table holds content information with user information as a foreign key `` postedBy '' which refers to the id of user table . One User can have many posts.Base...
@ Entity @ Tablepublic class User { @ Id @ GeneratedValue ( generator= '' system-uuid '' ) @ GenericGenerator ( name= '' system-uuid '' , strategy = `` uuid '' ) private String id ; private String name ; private String email ; } @ Entity @ Tablepublic class Post { @ Id @ GeneratedValue ( generator= '' system-uuid '' ) ...
Spring boot entity many to one mappping in embaded object
Java
I 've ran into a problem handling file names in javax.mail and some of those aspects need to be configured by session properties and some by system properties . Many classes of javax.mail seem to store the properties they work on in static fields , like in the following example for MimeBodyPart : From my understanding ...
private static final boolean encodeFileName =PropUtil.getBooleanSystemProperty ( `` mail.mime.encodefilename '' , false ) ;
Why do classes in javax.mail store system properties in static fields ?
Java
Suppose there is a string s=abcdI want the 5th string consisting of a , b , c , d , which is adbc . But I also get all the answers beyond it which I do n't need . So how can I stop this method after its 5th execution ? Secondly is there any site where I can read about permutation , combination and probability for calcu...
import java.util.Arrays ; import java.util.Scanner ; class Test { long times ; int n=1 ; public static void main ( String [ ] args ) { Test tm=new Test ( ) ; Scanner in=new Scanner ( System.in ) ; int t=Integer.parseInt ( in.nextLine ( ) ) ; while ( t ! =0 ) { String s=in.nextLine ( ) ; char ch [ ] =s.toCharArray ( ) ;...
5th string needed from combination
Java
I 'm wondering why floating point numbers in Java can represent exact value when they are initialized as literals , but they are approximate when they represent result of some calculation.For example : why the result is : and not : When there is no exact binary representation of 0.3.I know the BigDecimal class , but I ...
double num1 = 0.3 ; double num2 = 0.1 + 0.2 ; System.out.println ( num1 ) ; System.out.println ( num2 ) ; 0.30.30000000000000004 0.300000000000000040.30000000000000004
Floating point precision in literals vs calculations
Java
I 'm puzzled by what I had to do to get this code to work . It seems as if the compiler optimized away a type conversion that I needed , or there 's something else I do n't understand here.I have various objects that are stored in the database that implement the interface Foo . I have an object , bar , which holds data...
Class getFooClass ( ) Long getFooId ( ) public < T > T get ( Class < T > clazz , Serializable id ) ; get ( bar.getFooClass ( ) , bar.getFooId ( ) ) ; get ( bar.getFooClass ( ) , bar.hasLongId ( ) ? bar.getFooId ( ) : bar.getFooId ( ) .intValue ( ) ) ; get ( bar.getFooClass ( ) , bar.hasLongId ( ) ? bar.getFooId ( ) : n...
Compiler dropping my type conversion ?
Java
Learning JAVA , i was trying to test the upper limit of while loop which goes on incrementing an int.Please see the program below : I am aware that 32 bits range is from -2,147,483,648 to 2,147,483,647 , so on the basis of that , i was expecting output as 2,147,483,647 but instead i am getting : I even tried but still ...
public class Test { public static int a ( ) { int a = 10 ; while ( a > 9 ) ++a ; return a ; } public static void main ( String [ ] argc ) { Test t = new Test ( ) ; int k = t.a ( ) ; System.out.println ( `` k = `` + ( 1 * k ) ) ; } } k = -2147483648 System.out.println ( `` k = `` + ( 1 * k/2 ) ) ; k = -1073741824
Unexpected output for int type
Java
Consider the following example , which is not compiled : If I replacewithThe code will be compiled.So the question is how do I write collect ( ) with supplier and accumulator ( I need it ) to be able to call a stream ( ) after it ?
List < Integer > list = Arrays.asList ( 1 , 2 , -3 , 8 ) ; list.stream ( ) .filter ( x - > x > 0 ) .collect ( ArrayList : :new , ArrayList : :add , ArrayList : :addAll ) .stream ( ) // Stream < Object > .map ( x - > x * 2 ) .forEach ( System.out : :println ) ; .collect ( ArrayList : :new , ArrayList : :add , ArrayList ...
Why I 'm getting Stream < Object > when I call stream ( ) after collect ( ) ?
Java
I know that Lists in Java are Invariant.So the second statement below gives a compilation error as expectedHowever , all of these work fineSo my question is how does the last statement above compile ? I understand that Arrays.asList ( ) accepts the type from its caller , but I thought Arrays.asList ( 1,2,3 ) whould res...
List < Integer > integers = Arrays.asList ( 1 , 2 , 3 ) ; List < Number > numbers = integers ; List < Integer > numbers1 = Arrays.asList ( 1 , 2 , 3 ) ; List < ? extends Number > numbers2 = Arrays.asList ( 1 , 2 , 3 ) ; List < Number > numbers3 = Arrays.asList ( 1 , 2 , 3 ) ;
Does Java List behave as a covariant type during initialisation ?
Java
I am trying to make use of lambdas in Java but ca n't understand how it works at all . I created @ FunctionalInterface like this : now in my code I use the lambda as here : Next , I want to make use of my function passing it into the constructor of another class and use it like this : Why I need to use it the valueOf (...
@ FunctionalInterfacepublic interface MyFunctionalInterface { String getString ( String s ) ; } MyFunctionalInterface function = ( f ) - > { Date d = new Date ( ) ; return d.toString ( ) + `` `` + person.name + `` used fnc str '' ; } ; public SampleClass ( MyFunctionalInterface function ) { String tmp = `` The person i...
Lambdas in FunctionalInterfaces in Java
Java
In Java 8 we can mark separate dimensions of array with annotations ( see section 10.2 in JLS 8 ) .For example , Then we can parse such declarations with Java Reflection to implement some specific logic.Do you know any practical applications of this feature in real Java frameworks or Java libraries ?
int @ a [ ] a ; int @ a [ ] @ b [ ] a ; void someMethod ( int @ a [ ] @ b ... y ) { }
Mark separate dimensions of an Array with Annotations
Java
In this code I have a panel in the GridBagLayout which contains a JLabel and a JTextField . I would like to be able to automatically re-size the text field dependent on the amount of data entered in it . For example when the string `` How do I re-size this component automatically when the edge of it is reached ? '' is ...
import java.awt . * ; import javax.swing . * ; public class Simple { JFrame simpleWindow = new JFrame ( `` Simple MCVE '' ) ; JPanel simplePanel = new JPanel ( ) ; JLabel lblSimple ; JTextField txtSimple ; public void numberConvertGUI ( ) { simpleWindow.setBounds ( 10 , 10 , 420 , 80 ) ; simpleWindow.setMinimumSize ( n...
Automatically re-sizing a component within a GridBagLayout
Java
I put together a microbenchmark that seemed to show that the following types of calls took roughly the same amount of time across many iterations after warmup.Has anyone found evidence that these different types of calls in the aggregate will have different performance characteristics ? My findings are they do n't , bu...
static.method ( arg ) ; static.finalAnonInnerClassInstance.apply ( arg ) ; static.modifiedNonFinalAnonInnerClassInstance.apply ( arg ) ;
Java call type performance
Java
I expect there is no error about above code , however I get compile error when I return Child.class .
public interface Parent { } public class Child implements Parent { } public < T extends Parent > Class < T > getClass ( ) { return Child.class ; // compile error , add cast to Class < T > }
Java Compile error when return Generic Class type
Java
I have this confusing code : When `` compiled '' and run the program displays `` double array '' why arrays precede Object ? Is there any other constructor situation where such confusing behavior will occur ?
public class Confusing { private Confusing ( Object o ) { System.out.println ( `` Object '' ) ; } private Confusing ( double [ ] dArray ) { System.out.println ( `` double array '' ) ; } public static void main ( String [ ] args ) { new Confusing ( null ) ; } }
why constructors with array as parameter precede constructors with Object in parameter [ java ] ?
Java
I am having a hard time understanding why the error below happens . If # 1 is ok , why is # 2 not ?
public interface IFoobar < DATA extends IFoobar > { void bigFun ( ) ; } class FoobarImpl < DATA extends IFoobar > implements IFoobar < DATA > { public void bigFun ( ) { DATA d = null ; IFoobar < DATA > node = d ; // # 1 ok d = node ; // # 2 error } }
Why is this self-referential Generics assignment illegal ?
Java
Given piece of code gives me compile time error.i do n't get it why i ca n't add string in list.but the code means that we can add the String class object and it 's derived class object in the liststill i am getting the error why
List < ? extends String > list = new Arraylist < String > ( ) ; list.add ( `` foo '' ) ;
compile time error while using wildcard in List
Java
Problem : I have two interfaces ( here GenCarry and Gen ) : It works when I ignore the 'rawtypes ' Warning , but trying to complete them I do n't get too far : Question : How would an interface like that look if complete - or is that even possible ? Is there a better approach to `` generalize '' an interface like that ...
public interface GenCarry < T extends Gen > { GenCarry < T > setGen ( T gen ) ; } public interface Gen < T extends GenCarry > { void applyOn ( T carry ) ; } GenCarry < T extends Gen < GenCarry < T > > > Gen < C extends GenCarry < Gen < C > > > - > error : not a valid substitute for the bounded parameter .
Codependent/circular generics loop
Java
So , as a disclaimer , I am extremely new to programming and am probably missing something obvious . Now , I am trying to create two methods named withdraw ( ) and deposit ( ) that will allow me to change the value of the field currentBalance , however , every time I try to change the value of currentBalance with my tw...
class TradingService { public class Trader { //This field stores the trader 's name private String traderName ; //This field stores the trader 's current balance private double currentBalance ; //A constructor to create a Trader public Trader ( String traderName ) { this.traderName = traderName ; } //This method gets r...
Having Trouble with Changing the Value of a Field in Java
Java
I was making a program ( A Piglatin sort of ... ) , in which I unintentionally missed a variable in the statement : It should actually have been String a = `` R '' +text+ ' a ' ; . The compiler produced an error . But , when I made it : The program compiled.I am wondering why putting a space made the difference even th...
String a = `` R '' ++ ' a ' ; String a = `` R '' + + ' a ' ;
Java : space makes a difference in compilation ?
Java
I was reviewing one of the Oracle trails on Java generics , entitled `` Effects of Type Erasure and Bridge Methods '' , and I could not convince myself of an explanation given . Curious , I tested the code locally and I could not even reproduce the behavior which the trail explains . Here is the relevant code : The Ora...
public class Node < T > { public T data ; public Node ( T data ) { this.data = data ; } public void setData ( T data ) { System.out.println ( `` Node.setData '' ) ; this.data = data ; } } public class MyNode extends Node < Integer > { public MyNode ( Integer data ) { super ( data ) ; } public void setData ( Integer dat...
Potential issue with one of Oracle 's trails on Java generics
Java
I 'm reading LinkedBlockingQueue code now , but i have a question , maybe it 's simple , but i ca n't find answer , really need help.I noticed the Node.next is not volatile , like this : So , how does the enqueue of a new node ( Node.next ) become visible to the dequeue via another thread ?
static class Node < E > { E item ; LinkedBlockingQueue.Node < E > next ; Node ( E var1 ) { this.item = var1 ; } } private void enqueue ( Node < E > node ) { // assert putLock.isHeldByCurrentThread ( ) ; // assert last.next == null ; last = last.next = node ; } private E dequeue ( ) { // assert takeLock.isHeldByCurrentT...
LinkedBlockingQueue node 's next is not volatile
Java
Is there a checkstyle rule that will catch something like this : result is double ( so clearly fractions are desired ) yet the right-hand side would do integer division ( rounding down ) .Does something like this exist ?
double result = someInt / someOtherInt ;
Checkstyle rule for suspicious integer division ?
Java
If the size of map is 1 then its key should be returned . If it 's size is greater than 1 then iterate over the values in map and the key of that one should be returned which has a max value for a certain property . Below is my code snippet . I want to achieve the same with Java 8 streams api .
public MessageType getOrgReversalTargetMti ( Map < MessageType , List < TVO > > map ) { MessageType targetMessageType = null ; if ( 1 == map.size ( ) ) { targetMessageType = map.keySet ( ) .iterator ( ) .next ( ) ; } else { long maxNumber = 0 ; for ( final MessageType messageType : map.keySet ( ) ) { List < TVO > list ...
Method to return key of a map after computation on its values by Java 8
Java
i am have been learning lambda and streams lately and have kind of been thrown into the deep end really early.I currently have an array list of books , a user types in a word and if the word equals the books author or title , the books toString ( all attributes of the book nicely formatted ) is called and returned . Ve...
public String getBookByTitleOrAuthor ( String titleOrAuthor ) { books.stream ( ) .filter ( BookPredicate.matchTitleOrAuthor ( titleOrAuthor ) ) .filter ( returnedBook - > returnedBook.getBookStatus ( ) ! = Book.bookStatus.Damaged & & returnedBook.getBookStatus ( ) ! = Book.bookStatus.Deleted ) .forEach ( returnedBook -...
Using Lambda and Streams in For each and returning result
Java
i 've got the class P4 in the default package ( i know using the default package is bad practice , but merely `` for example '' for now ) : and class P2 in package tempFrom the access control mechanism , i 'd expect P4 -- having extended P2 , should be able to see the protected member of its super class even from outsi...
import temp.P2 ; public class P4 extends P2 { public void someMethod ( ) { P2 p2 = new P2 ( ) ; // p2.p2default ( ) ; // ERROR as expected p2.p2public ( ) ; p2.p2protected ( ) ; // ERROR as not expected } } package temp ; public class P2 { protected void p2protected ( ) { ... } public void p2public ( ) { ... } void p2d...
Access control -- protected members from outside the package
Java
Essentially , what I want to do is take a 3D array of strings and have each 1D array in it display quantity for repeated values . For instance , if I had an array of Strings like this : it would become : How could I do this , and what is it I am doing wrong ?
public static String [ ] [ ] [ ] cleanUp ( String [ ] [ ] [ ] array ) { for ( int f = 0 ; f < array.length ; f++ ) { for ( int g = 0 ; g < array [ f ] .length ; g++ ) { int position = 0 ; //boolean flag = false ; int count = 0 ; for ( int h = 0 ; h < array [ f ] [ g ] .length ; h++ ) { if ( array [ f ] [ g ] [ h ] .equ...
Merging together identical values in an array
Java
For example if i display in a TextView the text `` Uploading '' now i want it to display the text as `` Uploading ... '' and the 3 points to be delete and show again like it 's processing doing something and not just static text.I have this in the MainActivity onTouch event : This line : Instead displaying only static ...
@ Override public boolean onTouchEvent ( MotionEvent event ) { float eventX = event.getX ( ) ; float eventY = event.getY ( ) ; float lastdownx = 0 ; float lastdowny = 0 ; switch ( event.getAction ( ) ) { case MotionEvent.ACTION_DOWN : lastdownx = eventX ; lastdowny = eventY ; Thread t = new Thread ( new Runnable ( ) { ...
How can i make a text in android-studio to be animated ?
Java
I have the following code : and my code is the following : The code is failing , as it seems that the 1st verify sees that there were 2 calls to javaCompiler.writeJavaAndCompile ( ) . It is failing to realize that there was only one call of type ContractCompilationUnit type.What 's the standard procedure to avoid this ...
verify ( javaCompiler , times ( 1 ) ) .writeJavaAndCompile ( any ( ContractCompilationUnit.class ) , eq ( outputDirectory ) ) ; verify ( javaCompiler , times ( 1 ) ) .writeJavaAndCompile ( any ( ParamCompilationUnit.class ) , eq ( outputDirectory ) ) ; javaCompiler.writeJavaAndCompile ( new ContractCompilationUnit ( ) ...
any ( MyClass.class ) that actually matches only classes of the type of the passed class ?
Java
We want to migrate all our apache-httpclient-4.x code to java-http-client code to reduce dependencies . While migrating them , i ran into the following issue under java 11 : How to set the socket timeout in Java HTTP Client ? With apache-httpclient-4.x we can set the connection timeout and the socket timeout like this ...
DefaultHttpClient httpClient = new DefaultHttpClient ( ) ; int timeout = 5 ; // secondsHttpParams httpParams = httpClient.getParams ( ) ; httpParams.setParameter ( CoreConnectionPNames.CONNECTION_TIMEOUT , timeout * 1000 ) ; httpParams.setParameter ( CoreConnectionPNames.SO_TIMEOUT , timeout * 1000 ) ; HttpClient httpC...
How to set socket timeout in Java HTTP Client
Java
I have a class with a probably unnecessarily cumbersome name , that contains a lot of static methods I use elsewhere.Rather than fill my code with a lot ofI would rather haveHowever , this gets the warningI know there are multiple solutions here . Use better class names . Make it not static . Ignore it because it 's ju...
VeryUnnecessarilyLongCumbersomeName.doThingFoo ( ) ; VeryUnnecessarilyLongCumbersomeName.doThingBar ( ) ; VeryUnnecessarilyLongCumbersomeName.doThingEgg ( ) ; VeryUnnecessarilyLongCumbersomeName.doThingSpam ( ) ; VeryUnnecessarilyLongCumbersomeName thing = new VeryUnnecessarilyLongCumbersomeName ( ) ; thing.doThingFoo ...
`` should be accessed in a static way ''
Java
Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed ?
try ( BasicDataSource ds = BasicDataSourceFactory.createDataSource ( dsProperties ) ) { // still necessary for Connection to close if inside // try-with-resources ? try ( Connection conn = ds.getConnection ( ) ) { String sql = `` SELECT * FROM users '' ; try ( PreparedStatement stmt = conn.prepareStatement ( sql ) ) { ...
Is it mandatory to put inner try-with-resources or everything inside one of the try-with-resources will be autoclosed ?
Java
I saw the following recently on this site : To my surprise , this compiles and runs fine . I have also tried adding entries to the map so there is actually something to downcast and fail doing so , this worked fine as well . How can a TreeMap entry be cast to HashMap.Entry ? These two are n't even on the same branch of...
for ( HashMap.Entry < Object , Object > e : new TreeMap < > ( ) .entrySet ( ) ) System.out.println ( e ) ; for ( TreeMap.Entry < Object , Object > e : new HashMap < > ( ) .entrySet ( ) ) System.out.println ( e ) ;
Confusing type relationship
Java
I have this construction : I have many of them , & I want to optimize code using functional interface.Okay . I write something like this : Then , I wait that this code shall work : But IDEA write : void is not compatible with VoidPlease , tell me , what to do .
if ( Objects.isNull ( user.getMartialStatus ( ) ) ) { user.setMartialStatus ( MartialStatus.MARRIED ) ; } public static < T > void processIfNull ( T o , Supplier < Void > s ) { if ( Objects.isNull ( o ) ) { s.get ( ) ; } } processIfNull ( user.getMartialStatus ( ) , ( ) - > user.setMartialStatus ( MartialStatus.MARRIED...
How to use functional interface returning void ?
Java
Assuming that all properties are not long or double , does reading a volatile reference to an object guarantee atomic reads of the latest values of its properties ? Here 's a concrete example.Thread A may write to Foo 's Bar property any time . Thread B can only read Foo 's Bar property . If thread B accesses the Bar p...
public class Foo { private int bar ; public int getBar ( ) { return this.bar ; } public void setBar ( int bar ) { this.bar = bar ; } } public class Baz { private volatile Foo foo ; }
Does reading a volatile reference to an object guarantee atomic reads of the latest values of its properties ?
Java
I have an interfaceand I want to use this interface to create a new generic interface based on this type : The former gives a warning that the type T is hidden . The following give a compiler error : How can I express BWidgetObject < T > as type parameter for BDataList ?
public interface BWidgetObject < T > { } public interface BDataList < BWidgetObject > { } public interface BDataList < BWidgetObject < T > > { }
Generic Type of a Generic Type in Java ?
Java
I 'm trying to download selenium web driver using eclipse and I am on the final step and successfully imported web driver , however , when I attempt to do the same for firefox I do n't get the import option . Any Suggestions ? Is there anything wrong with the code below ? Code :
package webdriver_project ; import org.openqa.selenium.WebDriver ; public class webdriver_module_1 { public static void main ( String [ ] args ) { WebDriver driver = new firefoxDriver ( ) ; } }
selenium installation hurdle `` importfirefoxdriver ''
Java
Why is there no warning for the below code ? I expected the RHS to have an unchecked warning.While this code has a warning : Also , for below case there is no warning : Does this mean that unchecked warnings came with generics ? There were no such warnings before introduction of generics in Java ?
public void some ( Object a ) { Map < ? , ? > map = ** ( Map < ? , ? > ) a** ; //converting unknown object to map } public void some ( Object a ) { Map < Object , Object > map = ** ( Map < Object , Object > ) a** ; //converting unknown object to Map < Object , Object > } String str = ( String ) request.getAttribute ( `...
Why there is no warning while casting from object to unbounded wildcard collection ?