Creating an ArrayList Object
In this lesson, you'll learn how to create an ArrayList object in Java.
We'll cover the following...
Let’s practically use an ArrayList Object in our code. The ArrayList is a class in Java and to use a class’s functionality we have to instantiate it i.e. to construct its object.
To construct an object of a class we use a constructor. Before we jump to the constructor part let’s discuss a bit about the wrapper classes.
Wrapper classes
In Java, we cannot directly instantiate an ArrayList of the primitive data types like int, char, boolean. The reason for this is that primitive data types are not objects. For this purpose, Java has inbuilt wrapper classes which just wrap these
primitive data types in a class. Below given is the list of inbuilt wrapper classes:
| Primitive Data Type | Wrapper Class |
|---|---|
boolean |
Boolean |
byte |
Byte |
char |
Character |
double |
Double |
float |
Float |
int |
Integer |
long |
Long |
short |
Short |
Note:
Stringis not a primitive data type. These are objects instantiated from aStringbase class in Java, so they don’t need any wrapper class.
Generics in action
The above wrapper classes are passed to the ArrayList class as type parameters inside the pair of angle brackets <>. This is exactly the concept of Generics.
Syntactically we can generalize the declaration of an ArrayList as:
ArrayList<Type> name;
Instantiation
The ArrayList objects can be instantiated using the keyword new and the ArrayList class are three types of constructors which are discussed below:
Empty ArrayList
The following is the basic and the most used way to instantiate an ArrayList of Integer data type.