collections

List<Integer> nums = new ArrayList<>();
nums.add(2);
nums.add(5);
nums.add(8);

System.out.println(nums.get(0));

Output:

2

List

ArrayList gives indexed access LinkedList gives fast insertion at the ends Vector is synchronized and usually the wrong default

nums.remove(0) removes by index, not by value That distinction has caused more than one production bug

Set

Set<String> set = new HashSet<>();
set.add("dog");
set.add("cat");
set.add("dog");
System.out.println(set.size());

Output:

2

A Set stores unique values HashSet is fast and unordered TreeSet keeps elements sorted

Map

Map<Integer, String> m = new HashMap<>();
m.put(5, "Five");
m.get(6);

Output:

null

get returns null when the key is absent Check with containsKey when null is a valid value

Queue

Deque<String> deque = new ArrayDeque<>();
deque.addFirst("Cat");
deque.addLast("Horse");
deque.peek();

ArrayDeque is the modern replacement for Stack Use it for both ends Use PriorityQueue when order is by priority, not arrival

Choosing

  • indexed access -> ArrayList
  • unique membership -> HashSet
  • key to value -> HashMap
  • both ends -> ArrayDeque
  • sorted keys -> TreeMap or TreeSet

Next

Generics in 06 generics

Posted