- When combining an array declaration, allocation, and initialization in a single step, do not specify the size of the array. The size of the array is calculated by the number of values that are assigned to the array.
- If one declares and initializes an array using two separate lines of code, the keyword new is used to initialize the values.
- There are several methods to iterate through an ArrayList.
- We will discuss here about ListIterator method here.
- While declaring this method one needs to declare this after we have added,modified or deleted from the list else this throws up a java.util.ConcurrentModificationException. Example the code listed here throws a runtime exception mentioned above...
ArrayList<String> list=new ArrayList<String>();
ListIterator<String> it=list.listIterator();
list.add("hello");
list.add("test");
list.add("one");
list.add("two");
while(it.hasNext()){
String value=it.next();
System.out.println(value);
}
However if you re-write the code as below then it runs without any issue. A good rationale is provided in the http://examples.javacodegeeks.com/java-basics/exceptions/java-util-concurrentmodificationexception-how-to-handle-concurrent-modification-exception/
public static void main(String[] args) {
ArrayList<String> list=new ArrayList<String>();
list.add("hello");
list.add("test");
list.add("one");
list.add("two");
ListIterator<String> it=list.listIterator();
while(it.hasNext()){
String value=it.next();
System.out.println(value);
}
No comments:
Post a Comment