Introduction
Syntax
- ls.add(E element); //Adds an element
- ls.remove(E element); //Removes an element
- for(E element : ls){} //Iterates over each element
- ls.toArray(new String[ls.length]); //Converts a List of Strings to an array of Strings
- ls.get(int index); //Returns the element at the specified index.
- ls.set(int index, E element); //Replaces the element at a specified position .
- ls.isEmpty(); //Returns true if the array contains no elements, otherwise it returns false.
- ls.indexOf(Object o); //Returns the index of the first location of the specified element o, or, if it is not present, returns -1.
- ls.lastIndexOf(Object o); //Returns the index of the last location of the specified element o, or, if it is not present, returns -1.
- ls.size(); //Returns the number of elements in the List.
A list is an object which stores a an ordered collection of values. "Ordered" means the values are stored in a particular order--one item comes first, one comes second, and so on. The individual values are commonly called "elements". Java lists typically provide these features:
- Lists may contain zero or more elements.
- Lists may contain duplicate values. In other words, an element can be inserted into a list more than once.
- Lists store their elements in a particular order, meaning one element comes first, one comes next, and so on.
- Each element has an index indicating its position within the list. The first element has index 0, the next has index 1, and so on.
- Lists permit inserting elements at the beginning, at the end, or at any index within the list.
- Testing whether a list contains a particular value generally means examining each element in the list. This means that the time to perform this check is O(n), proportional to the size of the list.
Adding a value to a list at some point other than the end will move all of the following elements "down" or "to the right". In other words, adding an element at index n moves the element which used to be at index n to index n+1, and so on. For example:
List<String> list = new ArrayList<>();
list.add("world");
System.out.println(list.indexOf("world")); // Prints "0"
// Inserting a new value at index 0 moves "world" to index 1
list.add(0, "Hello");
System.out.println(list.indexOf("world")); // Prints "1"
System.out.println(list.indexOf("Hello")); // Prints "0"