简体   繁体   中英

What is the difference between the following two constructors of TreeSet?

For the TreeSet<E> the following two constructors are defined:

  1. TreeSet<E>(Collections<? extends E> c)
  2. TreeSet<E>(SortedSet<E> ss)

What is the need for the second option? Wouldn't the first contructor be compatible with the entire collections framework range of objects? Ie, if there is a scenario where we need to convert a SortedSet to TreeSet obj, can't we use the first contructor method?

Please clarify in this regard.

In addition to being a Collection<E> , SortedSet<E> provides access to its custom comparator:

Comparator<? super E> comparator()    

This overload of the constructor lets the newly created TreeSet<E> use the same custom sorter as that of the sorted set being copied.

Here is the code that demonstrates the difference:

public static void main (String[] args) throws java.lang.Exception
{
    Set<String> a = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    SortedSet<String> b = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
    populate(a);
    show(a, "Original a");
    populate(b);
    show(b, "Original b");
    Set<String> copyA = new TreeSet<String>(a);
    show(copyA, "Copy of a");
    Set<String> copyB = new TreeSet<String>(b);
    show(copyB, "Copy of b");
}
static void populate(Set<String> s) {
    s.add("A");
    s.add("aa");
    s.add("B");
    s.add("bb");
}
static void show(Set<String> s, String name) {
    System.out.println("============ "+name+" ==========");
    for (String t : s) {
        System.out.println(t);
    }
}

This produces the following output:

============ Original a ==========
A
aa
B
bb
============ Original b ==========
A
aa
B
bb
============ Copy of a ==========
A
B
aa
bb
============ Copy of b ==========
A
aa
B
bb

Note how the order of copied a is different from the original order, while the order of copied b remains consistent with the original.

Demo.

The TreeSet(SortedSet ss) constructor uses the same ordering as the ss parameter, while the TreeSet(Collections c) forcibly uses the "natural ordering" of its elements.

The Javadoc for java.util.TreeSet explains that.

Well, in the first case, the natural ordering of the elements of the collection is maintained, while in the second case, the ordering of the SortedSet is maintained. The distinguishing factor is the ordering of the elements in the TreeSet .

You can also set a custom ordering using the other constructor of the TreeSet .

Just check out the documentations for further reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM