ArrayLists are similar to arrays but they will automatically increase the arrays capacity if you try to add a element to a already full arrayList. There are two important variables for arraylists: capacity and size. Capacity is the length of the current arraylist while size is the number of elements in the arraylist. A arrayList will always hold a object. So if you want the arrayList to hold numbers you would use the Integer or Double object types. But you can add a primitive datatype to the list so long as that value is of the wrapper class that the arrayList has as its objectType. So like with ArrayList<Double> it will take 5.0 but it will not take 5 because 5 is a int not a double.
So you declare it in a field like:
private/public ArrayList<objectType> listName;
You declare it in a method or constructor like:
ArrayList<objectType> listName = new ArrayList<objectType>();
You have to use the entire ArrayList<objectType> whenever you are declaring variables, parameters, return values and when making one. Also the default capacity of a ArrayList is 10, which can be changed when declaring it by putting a whole number into the parenthesis.
The indices like Arrays start at zero and in order to get the size you use listName.size(), which as you can tell by the parenthesis is a method. A arraylist may use for each loops and when using methods that change the size of a array you have to be careful that you don’t accidentally skip any elements since if you delete a element the size will automatically decrement. Also a arrayList holds references to objects, and it can hold objects that are equal to each other and several references to the same object. Which means that the object can change after its been added to a Arraylist and the same object can belong to different arraylists.
A link to related topics is below:
One thought on “ArrayLists”
Comments are closed.