arraylists
ArrayListsIn Java, an arraylist implements a list using an array. Specifically, it implements the java.util.List interface into an array.
Unlike arrays, arraylists can only store objects and not primitive data types. However, autoboxing for primitive data types is built in after Java 5. The other main difference between arraylists and arrays is that arraylists' size will accommodate the data stored.
Declaration of arraylist of type E where E is an object:
ArrayList<E>() // default capacity of 10
Declaration of arraylist of type E and initial capacity x:
ArrayList<E>(int x)
Here are some common ArrayList methods:
ArrayList<E> arrList = new ArrayList<E>();
arrList.get(int x); // returns the value at index x
arrList.set(int x, E value); // sets the value at index x to value
arrList.remove(int x); // removes the value from index x and shifts all values right of the index one index left
returns value at index x
arrList.add(E value); // adds value to the end of the ArrayList
arrList.add(int x, E value); adds value to index x and shifts all values right of the index one index right
arrList.indexOf(E value); // returns int x where x is the index of the first occurence of value
arrList.size(); // returns int x where x is the size of the ArrayList
Note that the remove and add methods will shift the other elements in the ArrayList.
Make sure to use the correct syntax when dealing with ArrayLists, as the syntax is different from arrays! For example, size() is not an attribute but a method unlike length for arrays.
Since ArrayLists store lists of objects, watch out for when to use == versus .equals().