Why i am getting this output using java TreeSet Compare method?

125 views Asked by At

I used a Comparator class to define the sorting of the StringBuffer.I have implemented the Comparator class and the Comparator method compare.

Why i am getting output like this?

Code:

import java.util.Comparator;
import java.util.TreeSet;

public class SortestSetDemo {
    public static void main(String[] args) {
        TreeSet t1 = new TreeSet(new MyComparator());
        t1.add(new StringBuffer("a"));
        // t1.add("d");
        t1.add(new StringBuffer("q"));
        t1.add(new StringBuffer("w"));
        t1.add(new StringBuffer("r"));

        System.out.println(t1);
    }
}

class MyComparator implements Comparator {
    public int compare(Object ob1, Object ob2) {

        // String i1=(String)ob1;
        String i1 = ob1.toString();
        // String i2=(String)ob2;
        String i2 = ob2.toString(); //corrected error here instead of ob1.toString  it is ob2.toString()

        return -i1.compareTo(i2);
    }
}

Output Shown: [a] instead of [a,q,r,w]

1

There are 1 answers

0
TheCodingFrog On BEST ANSWER

You have a typo in your code. String i2 = ob1.toString(); . This should be

String i2 = ob2.toString();

Below code is working fine -

import java.util.Comparator;
import java.util.TreeSet;

public class SortestSetDemo {
    public static void main(String[] args) {
        TreeSet t1 = new TreeSet(new MyComparator());
        t1.add(new StringBuffer("a"));
        // t1.add("d");
        t1.add(new StringBuffer("q"));
        t1.add(new StringBuffer("w"));
        t1.add(new StringBuffer("r"));

        System.out.println(t1);
    }

}

class MyComparator implements Comparator {
    public int compare(Object ob1, Object ob2) {

        // String i1=(String)ob1;
        String i1 = ob1.toString();
        // String i2=(String)ob2;
        String i2 = ob2.toString();
        return -i1.compareTo(i2);

    }
}

Output:

[w, r, q, a]