Data Types and Exceptions in Java
Jim White
Java Developer
List
interface, sub-interface of Collection
List
ArrayList
- a resizable, indexed (like arrays), ordered list of objectsLinkedList
- objects connected by links to the next and previous objects.new
and use generics to specify content type.add(object)
.get(index)
ArrayList
has zero-based index.set(index, object)
.remove(index)
.clear()
.size()
import java.util.ArrayList; ... ArrayList<String> animals = new ArrayList<String>();
animals.add("horse"); animals.add("cow"); animals.add("horse"); // Duplicates allowed
String c = animals.get(1); // c="cow" animals.set(1, "chicken");
// Removes the first horse animals.remove(0); // Removes all objects animals.clear();
animals.size();
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(new Integer(5));
list.add(6); // 6 is automatically wrapped by Integer then added
Object
as the parameterized typeArrayList<Object> list = new ArrayList<Object>(); // Allow any object
list.add(new Integer(5)); // Add an Integer
list.add(6); // Add an Integer using autoboxing
list.add("Hello"); // Add a String
List
ArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
for (String animal : animals) { // fore-each to loop through all in the ArrayList
System.out.println(animal);
}
horse
cow
chicken
List
instance (like ArrayList
) can be displayed with println
ArrayList<String> animals = new ArrayList<String>();
animals.add("horse");
animals.add("cow");
animals.add("chicken");
System.out.println(animals); // Display all the elements in the ArrayList
ArrayList<Object> list = new ArrayList<Object>();
list.add(5);
list.add("Hello");
System.out.println(list); // Display all the elements in the ArrayList
[horse, cow, chicken]
[5, Hello]
LinkedList
are constructed like ArrayList
instancesLinkedList
have the same methods as ArrayList
import java.util.LinkedList;
...
LinkedList<String> cars // Create a new ...
= new LinkedList<String>(); // ... LinkedList
cars.add("Ford"); // Add an object to the list
cars.add("Mercedes");
String c = cars.get(1);
cars.set(1, "Toyota"); // Replace an object
System.out.println(cars); // Display the list
cars.remove(0); // Remove an object
cars.clear(); // Remove all objects
cars.size(); // Get the list length
[Ford, Toyota]
addFirst()
add to start of the listaddLast()
add to the end of the listremoveFirst()
remove from startremoveLast()
remove from endcars.addFirst("Fiat"); // Add to the beginning
cars.addLast("BMW"); // Add the the end
cars.removeFirst(); // Remove the first object
cars.removeLast(); // Remove the last object
ArrayList
and LinkedList
look the sameList
ArrayList
and LinkedList
(or any List
) are the sameList
type depends on useArrayList
considerations:list.get(11)
)LinkedList
considerations:list.get(11)
)Data Types and Exceptions in Java