java.util)
Collection interface
The Java interface java.util.Collection includes the following:
add(o) |
Add object o to the collection |
contains(o) |
Returns true if this collection contains an element that
equals o
|
isEmpty() |
Returns true if this collection contains no elements |
iterator |
Returns an iterator over the elements in this collection |
remove(o) |
Removes an element that equals o from this collection if
such an element exists
|
size() |
Returns the number of elements in this collection |
Set interfaceSet interface inherits from Collection
but changes the semantics of certain methods, e.g.
add(o) |
Add object o to the set if it is not already present |
List interfaceList interface inherits from Collection
but changes the semantics of certain methods and declares additional
methods, e.g.:
add(i, o) |
Inserts object o at position i |
add(o) |
Appends object o to end of list |
get(i) |
Returns element at position i |
indexOf(o) |
Returns the index of the first occurrence of o |
remove(i) |
Removes & returns the element at the ith position |
remove(o) |
Removes the first occurrence of object o |
set(i, o) |
Replaces the element at the ith position
by o and returns the replaced element
|
Map interfaceMap interface includes the following (plus isEmpty()
and size()):
containsKey(k) |
Returns true if this map contains a mapping for
key k
|
containsValue(v) |
Returns true if there is a mapping to value
v
|
get(k) |
Returns the value to which key k is mapped |
keySet() |
Returns a Set containing all the keys in this map |
put(k, v) |
Adds a mapping from k to v |
remove(k) |
Removes the mapping for key k from this map |
values() |
Returns a Collection of all the values in this map |
(More than one answer may be plausible in some cases)
Once you've decided which Java interface to use, you choose an implementation (or implement a new one of your own)
| Interface | Implementations | |
|---|---|---|
Set |
HashSet& its subclasses |
A hash table |
List |
ArrayList |
Resizable array |
LinkedList |
Doubly linked list | |
Map |
HashMap& its subclasses |
Hash table |
SortedSet |
TreeSet |
Balanced binary tree |
SortedMap |
TreeMap |
Balanced binary tree |
(Where Java needs to test for equalkity of objects in these data
structures, it wil use your equals method. For the hash tables,
it will use your hashCode method)
for-loopiterator()
method (see the Collection interface)
hasNext
and next
List<LibraryBook> library = new LinkedList<LibraryBook>();
Iterator<LibraryBook> iter = library.iterator();
while (iter.hasNext()) {
LibraryBook b = iter.next();
// Do something with b
}
ArrayList, the rest of the code
remains unchanged because it too has an iterator
for-loopfor-loopfor (LibraryBook b : library) {
// Do something with b
}
for b in library:
# Do something with b
for-loops even work with Java arrays, e.g.
int[] numbers = {1, 3, 5, 7};
int total = 0;
for (int n : numbers) {
total = total + n;
}