Java Puzzlers

Java Puzzlers (YouTube Video)

Interesting Java issues. Example (first one):

public class ShortSet {
  public static void main(String args[]) {
    Set<Short> s = new HashSet<Short>();
    for (short i = 0; i < 100; i++) {
      s.add(i);
      s.remove(i - 1);
    }
    System.out.println(s.size());
  }
}

What will it print?

  1. 1
  2. 100
  3. throws exception
  4. non of the above

Solution?

100.

Why?

i-1 will be an Integer, remove allows Object, the Integer is not in the Short-Set, so nothing is removed.