This book is now obsolete Please use CSAwesome instead.
9.9. Declaring Lists¶
To declare a list use
List<Type> name Change the Type to be whatever type of objects you want to store in the list like
String to hold strings as shown in the code below. You don’t have to specify a
<Type>, since it will default to
Object, but it is good practice to specify it to restrict what you allow in your list.
You should declare the variable to be of type
List rather than
ArrayList so that you can change what type of class you want to use to implement the list interface in the future without having to change your declarations. There are actually several classes in Java that implement the
List interface, but you only need to know the
ArrayList class for the AP CSA course.
In the code below we are declaring a variable called
nameList that can refer to a list of strings, but currently doesn’t refer to any list yet (is set to
9.10. Creating Lists¶
Declaring a list doesn’t actually create a list. It only creates a variable that can refer to a list. To actually create a list use
new ArrayList<Type>(). If you leave off the
<Type> it will default to
When you first create a new list it is empty, meaning that it doesn’t contain any items yet. You can get the number of items in a list using the
size() method. Notice that an empty list has a size of 0. Also notice that you can’t get the size of a list that is currently set to
null on line 9. You will get a
NullPointerException instead, which means that you tried to do something on an object reference that was
null meaning that it doesn’t reference an object.
You use the
length field to get the number of items in an array. But, with an
ArrayList you use the
size() method to get the number of items in the list. The number of items in an empty list is 0. You can’t get the size of a list that is set to
null. You will get a
You can also create lists of integer values. However, you have to use
Integer as the type.
Integer objects can hold an
You can also declare a list and create it in the same statement as shown below.