Presuming the method below is in a public class and it's invocations are included in a main method of the same class, what will be printed to the console?

public static void test(Collection<Integer> c) {
   c.add(3);
   c.add(2);
   c.add(1);
   c.add(2);
   c.remove(3);
   System.out.println(c);
}
...
   test(new ArrayList<Integer>());
   test(new LinkedHashSet<Integer>());
   test(new TreeSet<Integer>());
Explanation
The c.remove() method removes the Collection entry by value, not by index, as per method definition in the Collection interface - Collection.remove(Object o). Hence the c.remove(3); line would remove the first occurrence of an object equivalent to Integer(3).
An ArrayList is an unsorted Collection which allows duplicates, hence the output will be [2, 1, 2]
A LinkedHashSet is an unsorted Collection which does not allow duplicates, hence the output will be [2, 1].
A TreeSet is a sorted collection, which does not allow duplicates. The elements in a TreeSet are sorted in ascending order (unless a custom comparator is specified), hence the output will be [1, 2].

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback