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?
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.
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.
}
You'll need to give more context. Usually it makes more sense to obtain a lock while you perform some operations on a list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With