Slide navigation: Forward with space bar, → arrow key, or PgDn. Backwards with ← or PgUp.
public interface Queue<E> // a simplified form of the interface in the standard library { void add(E element); E remove(); int size(); }
public class CircularArrayQueue<E> implements Queue<E> public class LinkedListQueue<E> implements Queue<E> // not actual library classes
Queue<Customer> expressLane = new CircularArrayQueue<>(100);
Collection<E>
has methods:
boolean add(E element) Iterator<E> iterator() . . .
Iterator<E>
has methods:
E next(); boolean hasNext(); void remove(); default void forEachRemaining(Consumer<? super E> action);
Collection<String> c = . . .; Iterator<String> iter = c.iterator(); while (iter.hasNext()) { String element = iter.next(); do something with element }
for (String element : c) // works for any Iterable { do something with element }
Collection<E>
interface extends the Iterable<E>
interface.iterator.forEachRemaining(element -> do something with element);
remove
method removes the element that was just returned by next
:
Iterator<String> it = c.iterator(); it.next(); // skip over the first element it.remove(); // now remove it
remove
twice in a row without calling next
in between is an error.remove
behavior was chosen to make this loop possible:
while (it.hasNext()) if (it.next() fulfills some property) it.remove();
Collection
Methodsint size() boolean isEmpty() boolean contains(Object obj) boolean containsAll(Collection<?> c) boolean equals(Object other) boolean addAll(Collection<? extends E> from) boolean remove(Object obj) boolean removeAll(Collection<?> c) boolean removeIf(Predicate<? super E> filter) void clear() boolean retainAll(Collection<?> c) Object[] toArray() <T> T[] toArray(T[] arrayToFill)
Collection
holds elements, Map
holds key/value pairs.List
: Ordered collection.Set
: Unordered collection without duplicates.SortedSet
/SortedMap
: Traversed in sorted order.NavigableSet
/NavigableMap
: Additional methods for sorted sets/maps.List<E>
methods:
void add(int index, E element) void remove(int index) E get(int index) E set(int index, E element)
RandomAccess
tagging interface to distinguish between the two.ListIterator<E>
extends Iterator<E>
and provides methods:
void add(E element) E previous() . . .
ArrayList
|
An indexed sequence that grows and shrinks dynamically |
LinkedList
|
An ordered sequence that allows efficient insertion and removal at any location |
ArrayDeque
|
A double-ended queue that is implemented as a circular array |
HashSet
|
An unordered collection that rejects duplicates |
TreeSet
|
A sorted set |
EnumSet
|
A set of enumerated type values |
LinkedHashSet
|
A set that remembers the order in which elements were inserted |
PriorityQueue
|
A collection that allows efficient removal of the smallest element |
HashMap
|
A data structure that stores key/value associations |
TreeMap
|
A map in which the keys are sorted |
EnumMap
|
A map in which the keys belong to an enumerated type |
LinkedHashMap
|
A map that remembers the order in which entries were added |
WeakHashMap
|
A map with values that can be reclaimed by the garbage collector if they are not used elsewhere |
IdentityHashMap
|
A map with keys that are compared by == , not equals
|
List<String> list = . . .; ListIterator<String> iter1 = list.listIterator(); ListIterator<String> iter2 = list.listIterator(); iter1.next(); iter1.remove(); iter2.next(); // throws ConcurrentModificationException
ArrayList
is the other concrete implementation of the List
interface.List
variables:
List<String> names = new ArrayList<>();
List
value:
List<String> names = Arrays.asList("Peter", "Paul", "Mary");
List<Integer> piDigits = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9]; Set<Integer> primes = { 2, 7, 31, 127, 8191, 131071, 524287 };
List<Integer> piDigits = List.of(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5, 9); Set<Integer> primes = Set.of(2, 7, 31, 127, 8191, 131071, 524287);
List
and Set
interface.Arrays.asList
, but objects are immutable.Map<Integer, String> platonicSolids = { 4 : "tetrahedron", 6 : "cube", 8 : "octahedron", 12 : "dodecahedron", 20 : "icosahedron" };
Map<Integer, String> platonicSolids = Map.of(4, "tetrahedron", 6, "cube", 8, "octahedron", 12, "dodecahedron", 20, "icosahedron");or
import static java.util.Map.*; platonicSolids = ofEntries(entry(4, "tetrahedron"), entry(6, "cube"), ...);
Rectangle
? For Employee
?HashMap
hashes the keys, TreeMap
organizes them in sorted order.Map<String, Employee> staff = new HashMap<>(); // HashMap implements Map Employee harry = new Employee(. . .); staff.put("987-98-9996", harry);
String id = "987-98-9996"; Employee e = staff.get(id); // gets harry
get
method returns null
if the key is absent. Better approach:
Map<String, Integer> scores = . . .; int score = scores.getOrDefault(id, 0); // Gets 0 if the id is not present
map.remove(key)
removes a key.scores.forEach((k, v) -> System.out.println("key=" + k + ", value=" + v));
counts.put(word, counts.get(word) + 1);
word
wasn't present?
counts.put(word, counts.getOrDefault(word, 0) + 1);
counts.putIfAbsent(word, 0); counts.put(word, counts.get(word) + 1); // Now we know that get will succeed
counts.merge(word, 1, Integer::sum);
word
wasn't present, put 1. Otherwise, put the sum of 1 and the previous value.Set<K> keySet() Collection<V> values() Set<Map.Entry<K, V>> entrySet()
Set<String> keys = staff.keySet();
for (String k : keys) do something with k and staff.get(k)
for (Map.Entry<String, Employee> entry : staff.entrySet()) { String k = entry.getKey(); Employee v = entry.getValue(); do something with k, v }
staff.forEach((k, v) -> do something with k, v);
remove
on the key set removes the key and associated value from the map.select
tag:
options.put("Monday", 1); options.put("Tuesday", 2); options.put("Wednesday", 3); options.put("Thursday", 4); . . .
LinkedHashMap
.Collection<String> greetings = Collections.nCopies(100, "Hello");
Collection<String> greetings = Collections.singleton("Hello"); Set<String> deepThoughts = Collections.emptySet();
List<Employee> group2 = staff.subList(10, 20);
group2.clear(); // staff reduction
SortedSet<E> subSet(E from, E to) SortedSet<E> headSet(E to) SortedSet<E> tailSet(E from) SortedMap<K, V> subMap(K from, K to) SortedMap<K, V> headMap(K to) SortedMap<K, V> tailMap(K from)
Collections.unmodifiableCollection Collections.unmodifiableList Collections.unmodifiableSet Collections.unmodifiableSortedSet Collections.unmodifiableNavigableSet Collections.unmodifiableMap
List<String> safeStrings = Collections.checkedList(strings, String.class);
Collections.sort
sorts a list of Comparable
, or any list with a Comparator
instance.Collections.binarySearch
finds an element in a sorted list.Collections.min
and Collections.max
find the smallest and largest element.Collections.fill
fills a list with a specified element.Collections.shuffle
randomly shuffles a list.Collections.replaceAll(words, "C++", "Java"); words.replaceAll(String::toLowerCase); words.removeIf(w -> w.length() <= 3);
for (int i = 0; i < words.size(); i++) if (words.get(i).equals("C++")) words.set(i, "Java");
coll1.addAll(coll2); coll1.removeAll(coll2); coll1.retainAll(coll2);
addAll
is set union, retainAll
is set intersection, removeAll
is set difference.staffMap.keySet().removeAll(terminatedIDs); relocated.addAll(staff.subList(0, 10));
Arrays.asList
method:
String[] names = . . .; List<String> list = Arrays.asList(names); Set<String> set = new HashSet<>(Arrays.asList(names));
coll.toArray()
, but you only get a useless Object[]
array.Collection<String> coll = . . .; String[] names = coll.toArray(new String[0]);
String[] names = coll.toArray(new String[coll.size()]);
Vector
, Hashtable
are predecessors of ArrayList
, HashMap
.Enumeration
is a precessor of Iterator
.Properties
are used when specifying program configurations. They are similar to Map<String, String>
.Stack
is the classic stack structure. Just use an ArrayList
instead.BitSet
is a sequence of bits. It can be used to represent a set of integers. Operations include:
int bit = bucketOfBits.get(i); bucketOfBits.set(i); bucketOfBits.clear(i);