previous | start | next

ArrayList (more details)

ArrayList is a generic class. This means that the type of the elements to be stored in the ArrayList is a parameter - a type parameter - to be specified when an ArrayList instance is declared.

      ArrayList<Integer> intArr = new ArrayList<Integer>();
      ArrayList<String> strArr; = new ArrayList<String>();
   

Common mistake (but unfortunately, only a compiler warning):

      ArrayList lst = new ArrayList();  // No type specified for elements.
   

Error at line 11: The operator + is undefined for types int and Object

    1   public class RawTypeApp {
    2     public static void main(String[] args) {
    3       ArrayList lst = new ArrayList();
    4       for(int i = 0; i < 5; i++) {
    5         lst.add(i);
    6       }
    7       
    8       int sum = 0;
    9       
   10       for(int i = 0; i < lst.size(); i++) {
   11         sum = sum + lst.get(i);  // what type is lst.get(i)
   12       }
   13       System.out.printf("sum = %d\n", sum);
   14     }
   15   
   16   }


previous | start | next