Ram
Ram

Reputation: 1213

TreeSet constructor

As per this: https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html

There are 2 constructors in TreeSet class:

TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comparator)

I am not sure which constructor in above 2 is matched in below t2 TreeSet and whether the passed object is used or not?

cat Sorted.java

import java.util.*;

 public class Sorted implements Comparable<Sorted>, Comparator<Sorted> {
    private int num;
    private String text;

    Sorted(int n, String t) {
            this.num = n;
            this.text = t;
    }
    public String toString() { return "" + num; }
    public int compareTo(Sorted s) { return text.compareTo(s.text); }
    public int compare(Sorted s1, Sorted s2) {
            return s1.num-s2.num;
    }

    public static void main(String[] args) {
            Sorted s1 = new Sorted(88, "a");
            Sorted s2 = new Sorted(55, "b");

            TreeSet<Sorted> t1 = new TreeSet<>();
            t1.add(s1); t1.add(s2);

            TreeSet<Sorted> t2 = new TreeSet<>(new Sorted(1,"c"));
            t2.add(s1); t2.add(s2);

            System.out.println(t1 + " " + t2);
    }

}

Output:

[root@localhost temp]# java Sorted
[88, 55] [55, 88]
[root@localhost temp]#

Thanks.

Upvotes: 1

Views: 110

Answers (1)

&#211;scar L&#243;pez
&#211;scar L&#243;pez

Reputation: 235994

You're using this constructor:

TreeSet(Comparator<? super E> comparator)

Because in here:

new TreeSet<>(new Sorted(1, "c"));

You're passing a Sorted object, and Sorted is not a Collection, is a Comparator (and incidentally, also a Comparable):

public class Sorted implements Comparable<Sorted>, Comparator<Sorted>

And certainly, the passed object is used internally by TreeSet to perform its comparisons.

Upvotes: 3

Related Questions