Saturday, August 2, 2014

Arrays

  1. 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.
  2. If one declares and initializes an array using two separate lines of code, the keyword new is used to initialize the values.
  3. There are several methods to iterate through an ArrayList.
  4. We will discuss here about ListIterator method here.
  5. 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...
  public static void main(String[] args) {
          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