0

Why can't HashSet also be an answer for the following question? When I tested the code, both HashSet and TreeSet gave the same output, but the correct answer it seems is TreeSet. The code is below:

import java.util.*;

public class Example {
    public static void main(String[] args) {
        // insert code here
        set.add(new Integer(2));
        set.add(new Integer(1));
        System.out.println(set);
    }
}

Which code, inserted at line 4, guarantees that this program will output [1, 2]?

  1. Set set = new TreeSet();
  2. Set set = new HashSet();
  3. Set set = new SortedSet();
  4. List set = new SortedList();
  5. Set set = new LinkedHashSet();
5gon12eder
  • 24,280
  • 5
  • 45
  • 92
javaperson
  • 109
  • 1
  • 12

3 Answers3

2

HashSet is unordered, which specifically means that Java makes no guarantee about the order in which keys (and therefore values) are stored. On the other hand, TreeSet stores its elements in a natural order.

From the Javadoc for TreeSet:

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used. and If the objects can not be sorted in natural order than use compareTo() method to sort the elements of TreeSet object but hashmap is using equals() method to compare the elements.

Rahul
  • 1,380
  • 1
  • 10
  • 24
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

The choices are:

  1. Set set = new TreeSet();

As per doc:

The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

So this is correct answer as after insertion natural ordering would be [1,2].

  1. Set set = new HashSet(); HashSet is not ordered so no guarantee of natural ordering as well. This is not correct answer.

  2. Set set = new SortedSet(); SortedSet is an interface.

  3. List set = new SortedList(); That is definitely not correct answer for obvious reasons.

  4. Set set = new LinkedHashSet(); Hash table and linked list implementation of the Set interface, with predictable iteration order. In that case output would be [2,1].

1
  1. Set set = new TreeSet();

Yes as TreeSet is a sorted set and natural order for keys 2 and 1 is 1, 2.

  1. Set set = new HashSet();

No as HashSet does not guarantee any order.

  1. Set set = new SortedSet();

Compilation error: SortedSet is an interface and cannot be instantiated.

  1. List set = new SortedList();

Compilation error: there's no standard SortedList class in Java.

  1. Set set = new LinkedHashSet();

The order is guaranteed to be 2 and 1 (insertion order).

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334