This is a real beginner question (I'm still learning the Java basics).  I can (sort of) understand why methods would return a List&lt;String&gt; rather than an ArrayList&lt;String&gt;, or why they would accept a List parameter rather than an ArrayList. If it makes no difference to the method (i.e., if no special methods from ArrayList are required), this would make the method more flexible, and easier to use for callers. The same thing goes for other collection types, like Set or Map.  What I don't understand: it appears to be common practice to create local variables like this:  List&lt;String&gt; list = new ArrayList&lt;String&gt;();   While this form is less frequent:  ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;();   What's the advantage here?  All I can see is a minor disadvantage: a separate "import" line for java.util.List has to be added. Technically, "import java.util.*" could be used, but I don't see that very often either, probably because the "import" lines are added automatically by some IDE.
685
I have seen this mentioned a few times and I am not clear on what it means. When and why would you do this?   I know what interfaces do, but the fact I am not clear on this makes me think I am missing out on using them correctly.   Is it just so if you were to do:  IInterface classRef = new ObjectWhatever()   You could use any class that implements IInterface? When would you need to do that? The only thing I can think of is if you have a method and you are unsure of what object will be passed except for it implementing IInterface. I cannot think how often you would need to do that.   Also, how could you write a method that takes in an object that implements an interface? Is that possible?
40820
I have few methods that returns different Generic Lists.   Exists in .net any class static method or whatever to convert any list into a datatable? The only thing that i can imagine is use Reflection to do this.  IF i have this:  List&lt;Whatever&gt; whatever = new List&lt;Whatever&gt;();   (This next code doesn't work of course, but i would like to have the possibility of:  DataTable dt = (DataTable) whatever;
80088
When referencing class variables, why do people prepend it with this? I'm not talking about the case when this is used to disambiguate from method parameters, but rather when it seems unnecessary.  Example:  public class Person {             private String name;      public String toString() {         return this.name;     } }   In toString, why not just reference name as name?  return name;   What does this.name buy?   a stackoverflow question whose code has this pre-pending.
23909
Looking for reviewers to suggest optimization and improvements, and to evaluate coding practices.  final class Variables {     private final int x;     private final int y;      Variables(int x2, int y2) {         this.x = x2;         this.y = y2;     }      public int getX() {         return x;     }      public int getY() {         return y;     }      @Override public String toString()  {          return "x = " + x + " y = " + y;     } }  public final class FindMissing {      private FindMissing() {};      /**  * Takes an input a sorted array with two variables that repeat in the  * range. Remaining variable are consecutive. and returns two variables that repeats  *   * eg: for a range of 1,2,3,4, a valid input is [1, 4], [1, 3] etc.  *   * @param a : the sorted array.  */ /*  * Why is start needed ?  * If start is not given then if a1 is empty how do we know if missing numbers were  * [1, 2] or [4, 5] ??.   */ public static Variables sortedConsecutiveTwoMissing (int[] a, int startOfRange) {     if (a == null) throw new NullPointerException("a1 cannot be null. ");      int low = startOfRange;     // calculating the highest value of the range. it needs to be 2 more than length since all elememts are consecutive.     int high = startOfRange + (a.length - 1) + 2;      int i = 0;     boolean foundX = false;     int x = 0;       while (i &lt; a.length) {         if (a[i] != low) {             if (foundX) {                 return new Variables(x, low);             } else {                 x = low;                 foundX = true;             }         } else {             i++;         }         low++;     }      return new Variables(x, high);  }  public static void main(String[] args) {         // unsortedConsecutiveTwoMissing         int[] a6 = {1, 4};         System.out.println("Expected 2 and 3, Actual " + sortedConsecutiveTwoMissing(a6, 1));         // unsortedConsecutiveTwoMissing         int[] a7 = {-4, -1};         System.out.println("Expected -3 and -2, Actual " + sortedConsecutiveTwoMissing(a7, -4));         int[] a8 = {-4, -3, -2, -1};         System.out.println("Expected 0 and 1, Actual " + sortedConsecutiveTwoMissing(a8, -4));         int[] a9 = {5};         System.out.println("Expected 4 and 6, Actual " + sortedConsecutiveTwoMissing(a9, 4));         }      }
111890
I am a complete JSP beginner.  I am trying to use a java.util.List in a JSP page.  What do I need to do to use classes other than ones in java.lang?
282
Conditions: do not modify the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version. Is there a simpler way than: List&lt;String&gt; newList = new ArrayList&lt;String&gt;(); newList.addAll(listOne); newList.addAll(listTwo);
44787
If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library.  I have always used Lists for 1d arrays.  What is the reason or circumstance where I would want to use the array module instead?  Is it for performance and memory optimization, or am I missing something obvious?
80428
I have a class like this:  public class myClass {   public List&lt;myOtherClass&gt; anewlist = new List&lt;myOtherClass&gt;;    public void addToList(myOtherClass tmp)   {     anewList.Add(tmp);   }  }   So I call "addToList" a hundred times, each adding a unique item to the list.  I've tested my items to show that before I run the "addToList" method, they are unique.  I even put a line in to test "tmp" to make sure it was what I was expecting.  However, when I do this (lets say myClass object is called tmpClass):  int i = tmpClass.anewList.Count(); for (int j = 0; j&lt;i; j++) {    //write out each member of the list based on index j... }   I get the same exact item, and it's the last one that was written into my list.  It's as if when I add, I'm overwriting the entire list with the last item I've added.    Help?  This makes no sense. I've also tried List.Insert, where I'm always inserting at the end or at index 0.  Still no dice.  Yes, I'm doubly source my indexing is correct and when I do my test I'm indexing through each of the elements.  :)  UPDATE: Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {         Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output... I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena    Okay, I tried this and still had the same problem:  foreach(myOtherClass tmpC in tmpClass.anewList) {     Console.WriteLine(tmpC.theStringInMyClass.ToString()); }   and still for each of the 100 items, I got the same string output...  I'm sure I'm doing something completely stupid, but I don't know what yet. I'm still 100% sure that the right string is getting passed in to begin with.  -Adeena
17166
I have a list of integers, List&lt;Integer&gt; and I'd like to convert all the integer objects into Strings, thus finishing up with a new List&lt;String&gt;.  Naturally, I could create a new List&lt;String&gt; and loop through the list calling String.valueOf() for each integer, but I was wondering if there was a better (read: more automatic) way of doing it?
20509
I have a small code example I want to include in the Javadoc comment for a method.    /**  * -- ex: looping through List of Map objects --  * &lt;code&gt;  * for (int i = 0; i &lt; list.size(); i++) {  *      Map map = (Map)list.get(i);  *      System.out.println(map.get("wordID"));  *      System.out.println(map.get("word"));  * }  * &lt;/code&gt;  *   * @param query - select statement  * @return List of Map objects  */   The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.    -- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }  Parameters query - - select statement  Returns: List of Map objects    I guess I am wrong in assuming the code tag would handle line breaks.  What is the best way to format code examples in Javadoc comments ?
83735
private void activateRecords(long[] stuff) {     ...     api.activateRecords(Arrays.asList(specIdsToActivate));   }   Shouldn't this call to Arrays.asList return a list of Longs?  Instead it is returning a List&lt;long[]&gt;  public static &lt;T&gt; List&lt;T&gt; asList(T... a)   The method signature is consistent with the results, the varargs throws the entire array into the list.  It's the same as new ArrayList(); list.add(myArray)  And yes, I know it's meant to be used like this: Arrays.asList(T t1, T t2, T t3)  I guess what I'm getting at, is instead of the varargs form, why can't I just have my old asList method (at least I think this is how it used to work) that would take the contents and put them individually into a list?  Any other clean way of doing this?
16158
Consider this example (typical in OOP books):    I have an Animal class, where each Animal can have many friends. And subclasses like Dog, Duck, Mouse etc which add specific behavior like bark(), quack() etc.  Here's the Animal class:  public class Animal {     private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;();      public void addFriend(String name, Animal animal){         friends.put(name,animal);     }      public Animal callFriend(String name){         return friends.get(name);     } }   And here's some code snippet with lots of typecasting:  Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck());  ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack();   Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say      jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack();   Here's some initial code with return type conveyed to the method as a parameter that's never used.   public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){     return (T)friends.get(name);         }   Is there a way to figure out the return type at runtime without the extra parameter using instanceof? Or at least by passing a class of the type instead of a dummy instance. I understand generics are for compile time type-checking, but is there a workaround for this?
1992
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:  public String appendWithDelimiter( String original, String addition, String delimiter ) {     if ( original.equals( "" ) ) {         return addition;     } else {         return original + delimiter + addition;     } }  String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );   I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.  In Ruby, I can do something like this instead, which feels much more elegant:  parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(",");   But since Java lacks a join command, I couldn't figure out anything equivalent.  So, what's the best way to do this in Java?
22625
MyClass[] array; List&lt;MyClass&gt; list;   What are the scenarios when one is preferable over the other? And why?
76755
I have a bit of code where I've written a SOQL query that returns a list of SObject records, however I need a Set&lt;Id&gt; structure to pass to another method that I don't have control of (and thus can't change the method signature of).  How can I turn my returned List&lt;SObject&gt; into a Set&lt;Id&gt;? Is the best option just a for loop?
48229
what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?  The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:  public class Test {      String s;      private String hey() {         return s;     }      public String getS(){         String sm = this.hey();         // here I could just write hey(); without this         return sm;     } }
560
It seems that a List object cannot be stored in a List variable in C#, and can't even be explicitly cast that way.  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = sl;   results in Cannot implicitly convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  And then...  List&lt;string&gt; sl = new List&lt;string&gt;(); List&lt;object&gt; ol; ol = (List&lt;object&gt;)sl;   results in Cannot convert type System.Collections.Generic.List&lt;string&gt; to System.Collections.Generic.List&lt;object&gt;  Of course, you can do it by pulling everything out of the string list and putting it back in one at a time, but it is a rather convoluted solution.