Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Couple of questions on ArrayList

Tags:

java

arraylist

Question1:

Does it make sense to specifiy the size of the ArrayList. I know how many elements is going to carry in my List, is it good to specify the size before hand or it does not even matter.

List<String> list = new ArrayList<String>(1);
list.add("Hello");

List<String> newList = new ArrayList<String>();
newList.add("Hello");

Question2:

The java.util.ConcurrentModificationException occurs when you manipulate (add,remove) a collection while iterating over the same collection. Does that mean there is a thread which is modifying the ArrayList and another Thread iterating the same object.

Question3

Can anyone tell me how i can lock a list?

like image 453
theJava Avatar asked Nov 10 '12 18:11

theJava


1 Answers

  1. It matters if you're adding a lot of items, as it means the collection won't need to keep copying its internal buffer as it goes along. With a small list it won't make much difference. Note that you're not specifying the size of the ArrayList - you're specifying its initial capacity:

    List<String> list = new ArrayList<String>(10000);
    System.out.println(list.size()); // 0
    

    You still need to add items to it to change the size - but you can add items up to its capacity before it needs to perform copying internally.

  2. No, there doesn't have to be an extra thread involved. It just means that you've modified the collection while you're iterating over it. That can very easily be in a single thread:

    for (String item : items) {
        items.add("Foo"); // The next iteration step will fail.
    }
    
  3. You'll need to give more context. Usually it makes more sense to obtain a lock while you perform some operations on a list.

like image 147
Jon Skeet Avatar answered Oct 12 '22 01:10

Jon Skeet