[2019 oracle code one] collections corner cases

Collections Corner Cases

Speaker: Stuart Marks @StuartMarks #CollectionsCornerCases

For more blog posts, see The Oracle Code One table of contents



General

  • Covers things in collections framework a long time. Not well known
  • Good mix of PowerPoint and JShell

JShelll

  • If don’t assign an expression to a variable goes in $1, $2, etc
  • /var $1 – prints type of variable (yes the slash is intentional, it is a JShell command.)
  • /open abc.jshell – “imports” file

View Collections

  • Don’t contain their own elements. Instead the elements are stored elsewhere
  • ex: Arrays.asList(array) – creates list backed by array. If change list, the array gets changed to and vice versa.
  • map.keySet(), map.values() and map.entrySet(). If change these three collections, underlying map changes too.
  • Map.Entry – has setValue() method. Can call setValue() on on entry set to change underlying map

Performance/Clarity

  • values() is O(n) on a Map
  • Creating a temporary HashSet for the values makes in O(1)
  • retailAll() – set intersection
  • Don’t always need streams. [My logic is if you wouldn’t have needed a loop, you don’t need streams]

Sorted Collections & Comparators

  • Interfaces: SortedSet, SortedMap, NavigableSet, NavigableMap
  • Implementations: TreeSet, TreeMap, ConcurrentSkipListSet, ConcurrentSkipListMap
  • Ordering provided by Comparator. Could be natural order or Comparable. May or may not be consistent with equals.
  • HashSet and Set.of() – iteration order undefined. For SortedSet, iteration order is well defined – sorted order
  • Comparator rules
    • <0, 0, >0 for less than, equal and greater than
    • Must provide a total ordering. Any two values must return result
    • reflexive, transitive, etc
  • Spent a while on set vs list (unique elements) – don’t forget what type you are working with
  • HashSet – doesn’t allow duplicates using equals()
  • TreeSet – doesn’t allow duplicates where compare(a,b) ==0
  • String class has built in comparator: String.CASE_INSENSITIVE_ORDER. Inconsistent with equals(). So using case insensitive order with a TreeSet and adding ‘a’ and “A’, doesn’t add ‘A’ to list. Also tree.contains(“A”) returns true if “a” in set. If have HashSet with ‘A’ and TreeSet with ‘a’, tree.equals(hash) returns true but hash.equals(tree) returns false.

My take

I learned something new under 5 minutes in. (keySet()/values() and entrySet() are backed.). I was also pleasantly surprised to learn new shell commands. The rest was good too :).

Also, I was reminded that I hate Map.of(). I fell for misreading them because I didn’t parse properly as alternating keys and values.

Leave a Reply

Your email address will not be published.