02 Collections
02 Collections
02 Collections
index 0 1 2 3 4 5 6 7 8 9
length = 10
value 12 49 -2 26 5 17 -6 84 72 3
2
Array declaration
type[] name = new type[length];
Length explicitly provided. All elements' values initially 0.
int[] numbers = new int[5];
index 0 1 2 3 4
value 0 0 0 0 0
3
Accessing elements; length
name[index] // access
name[index] = value; // modify
name.length
• Legal indexes: between 0 and the array's length - 1.
numbers[3] = 88;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
}
System.out.println(numbers[-1]); // exception
System.out.println(numbers[7]); // exception
index 0 1 2 3 4 5 6
value 12 49 -2 88 5 17 -6
4
Limitations of arrays
• Arrays are useful, but they have many flaws and limitations:
size cannot be changed after the array has been constructed
no built-in way to print the array
no built-in way to insert/remove an element
no search feature
no sort feature
no easy duplicate detection/removal
inconsistent syntax with other objects (length vs. length() vs. size())
...
5
Collections
• collection: An object that stores data (objects) inside it.
the objects of data stored are called elements
typical operations: add, remove, clear, contains (search), size
some collections maintain an ordering; some allow duplicates
data structure: underlying implementation of a collection's behavior
• most collections are based on an array or a set of linked node objects
6
Java collection framework
7
Abstract data types (ADTs)
• abstract data type (ADT): A specification of a collection of data and
the operations that can be performed on it.
Describes what a collection does, not how it does it.
8
Constructing a collection
Interface<Type> name = new Class<Type>();
9
Why use ADTs?
• Q: Why would we want more than one kind of list, queue, etc.?
(e.g. Why do we need both ArrayList and LinkedList?)
11
List methods
constructor() creates a new empty list,
constructor(list) or a set based on the elements of another list
add(value) appends value at end of list
add(index, value) inserts given value just before the given index,
shifting subsequent values to the right
clear() removes all elements of the list
indexOf(value) returns first index where given value is found in list
(-1 if not found)
get(index) returns the value at given index
remove(index) removes/returns value at given index, shifting
subsequent values to the left
set(index, value) replaces value at given index with given value
size() returns the number of elements in list
toString() returns a string representation of the list
such as "[3, 42, -7, 15]"
12
List methods 2
addAll(list) adds all elements from the given list to this list
addAll(index, (at the end of the list, or inserts them at the given index)
list)
contains(value) returns true if given value is found somewhere in this list
containsAll(list) returns true if this list contains every element from given list
equals(list) returns true if given other list contains the same elements
iterator() returns an object used to examine the contents of the list
listIterator()
lastIndexOf(value returns last index value is found in list (-1 if not found)
)
remove(value) finds and removes the given value from this list
removeAll(list) removes any elements found in the given list from this list
retainAll(list) removes any elements not found in given list from this list
subList(from, to) returns the sub-portion of the list between
indexes from (inclusive) and to (exclusive)
toArray() returns the elements in this list as an array
13
List implementation
• ArrayList is built using an internal "unfilled" array and a size
field to remember how many elements have been added
index 0 1 2 3 4 5 6 7 8 9
value 42 -3 17 0 0 0 0 0 0 0
size 3
14
Stacks and queues
• stack: Retrieves elements in the reverse of the order they were added.
• queue: Retrieves elements in the same order they were added.
front back
top 3 remove, peek add
1 2 3
2
queue
bottom 1
stack
15
Class Stack
Stack<E>() constructs a new stack with elements of type E
push(value places given value on top of stack
)
pop() removes top value from stack and returns it;
throws EmptyStackException if stack is empty
peek() returns top value from stack without removing it;
throws EmptyStackException if stack is empty
size() returns number of elements in stack
isEmpty() returns true if stack has no elements
Stack<Integer> s = new Stack<Integer>();
s.push(42);
s.push(-3);
s.push(17); // bottom [42, -3, 17] top
System.out.println(s.pop()); // 17
16
Interface Queue
add(value places given value at back of queue
)
remove() removes value from front of queue and returns it;
throws a NoSuchElementException if queue is empty
peek() returns front value from queue without removing it;
returns null if queue is empty
size() returns number of elements in queue
isEmpty() returns true if queue has no elements
Queue<Integer> q = new LinkedList<Integer>();
q.add(42);
q.add(-3);
q.add(17); // front [42, -3, 17] back
System.out.println(q.remove()); // 42
18
Stack/Queue
implementation
• Stacks are almost always implemented using an array (why?)
index 0 1 2 3 4 5 6 7 8 9
value 42 -3 17 0 0 0 0 0 0 0
size 3
• Queues are built using a doubly-linked list with a front and back
reference, or using an array with front and back indexes (why?)
prev data next prev data next prev data next
42 42 42
front
back
size 3
19
Sets
• set: A collection of unique values (no duplicates allowed)
that can perform the following operations efficiently:
add, remove, search (contains)
"the"
"if" "of"
set.contains("to") "to"
"down" "from" true
"by" "she"
set.contains("be") "you" false
"in"
"why" "him"
set
20
Set implementation
• in Java, sets are represented by Set interface in java.util
21
Set methods
List<String> list = new ArrayList<String>();
...
Set<Integer> set = new TreeSet<Integer>(); // empty
Set<String> set2 = new HashSet<String>(list);
22
Set operations
addAll(collection) adds all elements from the given collection to this set
containsAll(coll) returns true if this set contains every element from given set
equals(set) returns true if given other set contains the same elements
iterator() returns an object used to examine set's contents (seen later)
removeAll(coll) removes all elements in the given collection from this set
retainAll(coll) removes elements not found in given collection from this set
toArray() returns an array of the elements in this set
23
Sets and ordering
• HashSet : elements are stored in an unpredictable order
Set<String> names = new HashSet<String>();
names.add("Jake");
names.add("Robert");
names.add("Marisa");
names.add("Kasey");
System.out.println(names);
// [Kasey, Robert, Jake, Marisa]
• TreeSet : elements are stored in their "natural" sorted order
Set<String> names = new TreeSet<String>();
...
// [Jake, Kasey, Marisa, Robert]
25
The "for each" loop (7.1)
for (type name : collection) {
statements;
}
55
29 87
-3 42 60 91
27