I have the following code:  // Creates ArrayList with integers 0-9 ArrayList&lt;Integer&gt; intKeys = new ArrayList&lt;Integer&gt;(); for (int x = 0; x &lt; 10; x++) {     intKeys.add(x); }  // Creates iterator with integers 0-9 Iterator&lt;Integer&gt; allKeys = intKeys.iterator();  // Loops 10 times, each time obtaining a key to remove from the ArrayList for (int x = 0; x &lt; 10; x++) {     Integer key = allKeys.next();     intKeys.remove(key); }   I understand that ConcurrentModificationException is thrown if an element of a collection is removed while the collection is being looped over, such as:  for (String key : someCollection) {     someCollection.remove(key);     }   but right now I'm looping over nothing - just an arbitrary number of times. Furthermore, the error line is interestingly Integer key = allKeys.next(); What could be the cause of this exception?
78
We all know you can't do the following because of ConcurrentModificationException:  for (Object i : l) {     if (condition(i)) {         l.remove(i);     } }   But this apparently works sometimes, but not always. Here's some specific code:  public static void main(String[] args) {     Collection&lt;Integer&gt; l = new ArrayList&lt;&gt;();      for (int i = 0; i &lt; 10; ++i) {         l.add(4);         l.add(5);         l.add(6);     }      for (int i : l) {         if (i == 5) {             l.remove(i);         }     }      System.out.println(l); }   This, of course, results in:  Exception in thread "main" java.util.ConcurrentModificationException   Even though multiple threads aren't doing it. Anyway.  What's the best solution to this problem? How can I remove an item from the collection in a loop without throwing this exception?  I'm also using an arbitrary Collection here, not necessarily an ArrayList, so you can't rely on get.
58176
I was looking at C# collection initializers and found the implementation to be very pragmatic but also very unlike anything else in C#  I am able to create code like this:  using System; using System.Collections;  class Program {     static void Main()     {         Test test = new Test { 1, 2, 3 };     } }  class Test : IEnumerable {     public IEnumerator GetEnumerator()     {         throw new NotImplementedException();     }      public void Add(int i) { } }   Since I have satisfied the minimum requirements for the compiler (implemented IEnumerable and a public void Add) this works but obviously has no value.  I was wondering what prevented the C# team from creating a more strict set of requirements?  In other words why, in order for this syntax to compile, does the compiler not require that the type implement ICollection?  That seems more in the spirit of other C# features.
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));         }      }
67149
I'm trying to create an array of arrays that will be using repeated data, something like below:  int[] list1 = new int[4] { 1, 2, 3, 4 }; int[] list2 = new int[4] { 5, 6, 7, 8 }; int[] list3 = new int[4] { 1, 3, 2, 1 }; int[] list4 = new int[4] { 5, 4, 3, 2 };  int[,] lists = new int[4, 4] {  list1 ,  list2 ,  list3 ,  list4  };   I can't get it to work and so I'm wondering if I'm approaching this wrong.   What I'm attempting to do is create some sort of method to create a long list of the values so I can process them in a specific order, repeatedly. Something like,  int[,] lists = new int[90,4] { list1, list1, list3, list1, list2, (and so on)};  for (int i = 0; i &lt; 90; ++i) {    doStuff(lists[i]); }   and have the arrays passed to doStuff() in order. Am I going about this entirely wrong, or am I missing something for creating the array of arrays?
22169
What is the concept of erasure in generics in Java?
634
I want to clear a element from a vector using the erase method. But the problem here is that the element is not guaranteed to occur only once in the vector. It may be present multiple times and I need to clear all of them. My code is something like this:  void erase(std::vector&lt;int&gt;&amp; myNumbers_in, int number_in) {     std::vector&lt;int&gt;::iterator iter = myNumbers_in.begin();     std::vector&lt;int&gt;::iterator endIter = myNumbers_in.end();     for(; iter != endIter; ++iter)     {         if(*iter == number_in)         {             myNumbers_in.erase(iter);         }     } }  int main(int argc, char* argv[]) {     std::vector&lt;int&gt; myNmbers;     for(int i = 0; i &lt; 2; ++i)     {         myNmbers.push_back(i);         myNmbers.push_back(i);     }      erase(myNmbers, 1);      return 0; }   This code obviously crashes because I am changing the end of the vector while iterating through it. What is the best way to achieve this? I.e. is there any way to do this without iterating through the vector multiple times or creating one more copy of the vector?
14775
There is a case where a map will be constructed, and once it is initialized, it will never be modified again.  It will however, be accessed (via get(key) only) from multiple threads.  Is it safe to use a java.util.HashMap in this way?  (Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice.  Hence, this question is not "Which one should I use?" nor is it a performance question.  Rather, the question is "Would it be safe?")
9770
I'm sure you all know the behaviour I mean - code such as:  Thread thread = new Thread(); int activeCount = thread.activeCount();   provokes a compiler warning.  Why isn't it an error?  EDIT:  To be clear: question has nothing to do with Threads.  I realise Thread examples are often given when discussing this because of the potential to really mess things up with them.  But really the problem is that such usage is always nonsense and you can't (competently) write such a call and mean it.  Any example of this type of method call would be barmy.  Here's another:  String hello = "hello"; String number123AsString = hello.valueOf(123);   Which makes it look as if each String instance comes with a "String valueOf(int i)" method.
99253
I like how Java has a Map where you can define the types of each entry in the map, for example &lt;String, Integer&gt;.   What I'm looking for is a type of collection where each element in the collection is a pair of values.  Each value in the pair can have its own type (like the String and Integer example above), which is defined at declaration time.    The collection will maintain its given order and will not treat one of the values as a unique key (as in a map).    Essentially I want to be able to define an ARRAY of type &lt;String,Integer&gt; or any other 2 types.    I realize that I can make a class with nothing but the 2 variables in it, but that seems overly verbose.    I also realize that I could use a 2D array, but because of the different types I need to use, I'd have to make them arrays of OBJECT, and then I'd have to cast all the time.    I only need to store pairs in the collection, so I only need two values per entry.  Does something like this exist without going the class route?  Thanks!
33779
I came across some very strange behaviour when working with a Map with Decimal keys today. It seems like the Decimal type can't handle Integer assignments properly, but allows them nonetheless. I've written some example code demonstrating the problem:  Map&lt;Decimal, String&gt; m = new Map&lt;Decimal, String&gt;(); m.put(1234, 'Integer key');  m.put(1234.0, 'Decimal key'); m.put(1234.5, 'Decimal Unique key');  System.debug(m.get(1234));      // =&gt; Integer key, why was this not overwritten if 1234 == 1234.0? System.debug(m.get(1234.0));    // =&gt; Decimal key System.debug(m.get(1234.5));    // =&gt; Decimal Unique key  System.debug(m);        //Order of insertion matters, newest value does not override existing one but is not shown on map printout... for(Decimal d : m.keySet()){     System.debug(d);    //...unless you print it out yourself, because this loop shows all the keys }  //Sanity check System.debug(1234 == 1234.0); //True  //Digging deeper Decimal fake_d = 1234; Decimal real_d = 1234.0; Integer real_i = 1234; //Integer fake_i = 1234.0; //Illegal assignment, typechecking only works one way, it seems  //More sanity checks System.debug(fake_d == real_d); //True (Except when used in a Map, apparently) System.debug(fake_d == real_i); //True  System.debug(m.get(real_i)); // =&gt; Integer key System.debug(m.get(fake_d)); // =&gt; Integer key, even with fake_d explicitely declared as a Decimal type, it still pretends to be an Integer. System.debug(m.get(real_d)); // =&gt; Decimal key   I found this behaviour when I tried to fetch a value from a map using a Decimal sObject field, only to find that the keys I used to populate the Map (coming from a different Decimal field) were interpreted as Integers since they had no real decimal digits.  Maybe using Decimals as Map keys is not supported for some reason? Is it expected behaviour for 1234 and 1234.0 being distinct values in this case or is this an oversight in the Map implementation?
4045
What is the most efficient way to write the old-school:  StringBuilder sb = new StringBuilder(); if (strings.Count &gt; 0) {     foreach (string s in strings)     {         sb.Append(s + ", ");     }     sb.Remove(sb.Length - 2, 2); } return sb.ToString();   ...in LINQ?
3046
Assuming I have an ArrayList  ArrayList&lt;MyClass&gt; myList;   And I want to call toArray, is there a performance reason to use  MyClass[] arr = myList.toArray(new MyClass[myList.size()]);   over  MyClass[] arr = myList.toArray(new MyClass[0]);   ?  I prefer the second style, since it's less verbose, and I assumed that the compiler will make sure the empty array doesn't really get created, but I've been wondering if that's true.  Of course, in 99% of the cases it doesn't make a difference one way or the other, but I'd like to keep a consistent style between my normal code and my optimized inner loops...
118792
The following code  using System.Threading;  class Test {     volatile int counter = 0;     public void Increment()     {         Interlocked.Increment(ref counter);     } }   Raises the following compiler warning:  "A reference to a volatile field will not be treated as volatile"   Am I doing something wrong here to raise this warning? Why does the compiler me warn about this?
12184
I'm trying to get an understanding of what the the java keyword this actually does. I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
13177
I have a questionable coding practice.   When I need to iterate through a small list of items whose count limit is under 32000, I use Int16 for my i variable type instead of Integer. I do this because I assume using the Int16 is more efficient than a full blown Integer.   Am I wrong? Is there no effective performance difference between using an Int16 vs an Integer? Should I stop using Int16 and just stick with Integer for all my counting/iteration needs?
69477
I have a scenario where I have multiple threads adding to a queue and multiple threads reading from the same queue. If the queue reaches a specific size all threads that are filling the queue will be blocked on add until an item is removed from the queue.  The solution below is what I am using right now and my question is: How can this be improved?  Is there an object that already enables this behavior in the BCL that I should be using?  internal class BlockingCollection&lt;T&gt; : CollectionBase, IEnumerable {     //todo: might be worth changing this into a proper QUEUE      private AutoResetEvent _FullEvent = new AutoResetEvent(false);      internal T this[int i]     {         get { return (T) List[i]; }     }      private int _MaxSize;     internal int MaxSize     {         get { return _MaxSize; }         set         {             _MaxSize = value;             checkSize();         }     }      internal BlockingCollection(int maxSize)     {         MaxSize = maxSize;     }      internal void Add(T item)     {         Trace.WriteLine(string.Format("BlockingCollection add waiting: {0}", Thread.CurrentThread.ManagedThreadId));          _FullEvent.WaitOne();          List.Add(item);          Trace.WriteLine(string.Format("BlockingCollection item added: {0}", Thread.CurrentThread.ManagedThreadId));          checkSize();     }      internal void Remove(T item)     {         lock (List)         {             List.Remove(item);         }          Trace.WriteLine(string.Format("BlockingCollection item removed: {0}", Thread.CurrentThread.ManagedThreadId));     }      protected override void OnRemoveComplete(int index, object value)     {         checkSize();         base.OnRemoveComplete(index, value);     }      internal new IEnumerator GetEnumerator()     {         return List.GetEnumerator();     }      private void checkSize()     {         if (Count &lt; MaxSize)         {             Trace.WriteLine(string.Format("BlockingCollection FullEvent set: {0}", Thread.CurrentThread.ManagedThreadId));             _FullEvent.Set();         }         else         {             Trace.WriteLine(string.Format("BlockingCollection FullEvent reset: {0}", Thread.CurrentThread.ManagedThreadId));             _FullEvent.Reset();         }     } }
110097
I often make a collection field unmodifiable before returning it from a getter method:  private List&lt;X&gt; _xs; .... List&lt;X&gt; getXs(){   return Collections.unmodifiableList(_xs); }   But I can't think of a convenient way of doing that if the X above is itself a List:  private List&lt;List&lt;Y&gt;&gt; _yLists; ..... List&lt;List&lt;Y&gt;&gt; getYLists() {   return Collections.unmodifiableList(_yLists); }   The problem in the above is of course that though the client cannot modify the List of lists, it can add/delete Y objects from the embedded lists.  Any thoughts?