Java Reference
In-Depth Information
ArrayList
and
Vector
classes work the same way, except that the methods in the
Vector
class are
synchronized, whereas methods in
ArrayList
are not. If your object list is accessed and modified by multiple threads
simultaneously, use the
Vector
class, which will be slower but thread safe. Otherwise, you should use the
ArrayList
class. For the rest of the discussion, I will refer to
ArrayList
only. However, the discussion applies to
Vector
as well.
The big difference between arrays and the
ArrayList
class is that the later works with only objects, not with
primitive data types. The
ArrayList
class is a generic class and it takes the type of its elements as the type parameter.
If you want to work with primitive values, you need to declare an
ArrayList
of one of the wrapper classes. For
example, use
ArrayList<Integer>
to work with
int
elements.
The following code fragment illustrates the use of the
ArrayList
class:
import java.util.ArrayList;
// Create an ArrayList of Integer
ArrayList<Integer> ids = new ArrayList<>();
// Get the size of array list
int total = ids.size(); // total will be zero at this point
// Print the details of array list
System.out.println("ArrayList size is " + total);
System.out.println("ArrayList elements are " + ids);
// Add three ids 10, 20, 30 to the array list.
ids.add(new Integer(10)); // Adding an Integer object.
ids.add(20); // Adding an int. Autoboxing is at play.
ids.add(30); // Adding an int. Autoboxing is at play.
// Get the size of the array list
total = ids.size(); // total will be 3
// Print the details of array list
System.out.println("ArrayList size is " + total);
System.out.println("ArrayList elements are " + ids);
// Clear all elements from array list
ids.clear();
// Get the size of the array list
total = ids.size(); // total will be 0
// Print the details of array list
System.out.println("ArrayList size is " + total);
System.out.println("ArrayList elements are " + ids);
ArrayList size is 0
ArrayList elements are []
ArrayList size is 3
ArrayList elements are [10, 20, 30]
ArrayList size is 0
ArrayList elements are []