ArrayLists allows for elements to be added and removed from an array after it is made. In a normal array, a new one has to be made every time
import java.util.ArrayList; // import the ArrayList class
ArrayList<String> Colors = new ArrayList<String>(); // Create an ArrayList object
add(int index, element) : adds an element to the list
Colors.add("red");
Colors.add("orange");
Colors.add("yellow");
addAll(int index, Collection collection) : adds all the elements in a list to another
ArrayList<String> shades = new ArrayList<String>();
shades.add("black");
shades.add("white");
Colors.addAll(shades);
System.out.println("colors: " + Colors + "\n");
System.out.println("shades: " + shades);
size() : outputs the size of a list (number of elements)
System.out.println("The number of colors in Colors[] is currently " + Colors.size());
clear() : clears everything in a list, reference list is stored
shades.clear();
System.out.println("shades: " + shades);
remove(int index), removes the element from a list with that specific index, shifts the rest of the elements to the left and decreases their index by 1
Colors.remove(0);
System.out.println("colors: " + Colors);
remove(element) : remove the element with a specific name
Colors.add("green");
// removes orange item
Colors.remove("orange");
System.out.println("colors: " + Colors);
get(int index) : obtains the element of that index
System.out.println("The first item listed is " + Colors.get(0));
set(int index, element) : replaces what is in that index with the new element
// replace the first term (index of 0)
Colors.set(0, "purple");
System.out.println("colors: " + Colors);
IndexOf(element) : returns the index of that element
System.out.println("The index for black is " + Colors.indexOf("black"));
lastIndexOf(element) : returns last occurrence of an object if not present in list
System.out.println("The index for yellow is " + Colors.lastIndexOf("yellow"));
equals(element) : true or false if two objects (lists) are equal to one another
if (Colors.equals(shades) == true) {
System.out.println("all the colors are in shades");
}
else {
System.out.println("the colors include non black/white shades");
}
hashCode() : returns the hashcode of a list
System.out.println("The hashcode for this list is " + Colors.hashCode());
isEmpty() : true or false if the list is empty (has no elements within)
System.out.println("Colors empty is " + shades.isEmpty());
contains(element) : returns true if the list contains the element
System.out.println("Colors contains blue is " + Colors.contains("blue"));
containsAll(Collection collection) : returns yes if the list contains all the elements of the other list
shades.add("pink");
shades.add("blue");
if (Colors.containsAll(shades) == true) {
System.out.println("colors contains all shades");
}
else {
System.out.println("colors does not contain all shades");
}
sort(Comparator comp) : sorts elements
Collections.sort(Colors);
System.out.println("Sorted colors " + Colors);