- Forward


The ArrayList Class in Java
An Introduction


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Review
Back SMYC Forward
  • An Array:
    • A fixed-size "group" of homogeneous objects each of which is identified by an integer index
  • Limitations of Arrays:
    • Fixed size
The java.util.ArrayList Class
Back SMYC Forward
  • Purpose:
    • A "growable" collection with an integer index
  • Important Methods:
    • void add(int index, E element)
    • void add(E element)
    • E get(int index)
    • E set(int index, E element)
    • E remove(int index)
    • int size()
Type-Safety and Collections
Back SMYC Forward
  • Elements in a Collection:
    • In Java, one can put Object objects in a collection
    • Effectively, this means that you can put any reference type in a collection
  • A Shortcoming of this Approach:
    • You are forced to cast the Object to the appropriate type when you retrieve it
    • You may cast it incorrectly and this mistake will only be caught at run-time
  • Overcoming this Shortcoming:
    • Use parameterized classes/interfaces
A Type-Safe ArrayList
Back SMYC Forward
  • The Raw ArrayList Class:
    • Contains Object objects
    • An Example:
      ArrayList a; a = new ArrayList();
  • Parameterizing an ArrayList java.util.ArrayList :
    • Contains objects of a specified type
    • An Example:
      ArrayList<String> a; a = new ArrayList<String>();
What About Primitive Types?
Back SMYC Forward
  • The Declarations:
    • ArrayList<Boolean>
    • ArrayList<Double>
    • ArrayList<Integer>
  • Why/How This Works:
    • This is a topic for another lecture
There's Always More to Learn
Back -