如何在树集中按降序存储字符串对象?

时间:2014-03-04 13:22:02

标签: java collections

在给定代码中,TreeSet中的String对象(名称)将按升序显示。如何使用TreeSet以降序显示它?

 import java.util.*;
 public class Lab15   {
 public static void main  (String[ ] args) {
TreeSet set1 = new TreeSet ();
 set1.add   (new Employee3(11,"shake"));
set1.add(new Employee3(15,"mayur"));
set1.add(new Employee3(13,"podu"));
set1.add(new Employee3(18,"manish"));
set1.add(new Employee3(17,"goku"));

Iterator it1=set1.iterator();
while(it1.hasNext()){
    System.out.println(it1.next());
}      
  }
class Employee3 implements Comparable{

int eid;
String name;
Employee3(int eid,String name) {
    this.eid=eid;
    this.name=name;
}
public String toString(){
    return eid+"\t"+name;
}

public int compareTo(Object obj) {
    if(obj instanceof Employee3){
        Employee3 em=(Employee3)obj;
        return this.name.compareTo(em.name);
    }
    return 0;
}


    }

解释一下,如何在树集中按降序存储字符串对象?

3 个答案:

答案 0 :(得分:9)

您只需要使用

实例化TreeSet
new TreeSet<>(Collections.reverseOrder());

这是一个比较器,可以反转对象的自然顺序

答案 1 :(得分:0)

在构造函数中,调用Comparator。

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

public class TreeSetDesc {

    private Set set = null;
    private Comparator comparator = null;
    public TreeSetDesc() {
        comparator = new SetComparator();
        set = new TreeSet<String>(comparator);
    }

    public void addItemsToSet() {
        String[] listItems = {"dog", "cat", "cow", "elephant", "sheep"};
        for (int i = 0; i < listItems.length; i++) {
        set.add(listItems[i]);
        }
    }

    public void displaySet() {
        System.out.println("Displaying contents of set");
        for (Object item : set) {
        System.out.println("Item = " + item.toString());
        }
        }

    public void removeItems() {
        System.out.println("Removing contents of set");
        set.remove("dog");
        set.remove("cat");
        set.remove("cow");
        set.remove("elephant");
        set.remove("sheep");
        System.out.println("Contents removed  ,now size of set = " + set.size());
        }

    public static void main(String[] args) {
        TreeSetDesc sample = new TreeSetDesc();
        sample.addItemsToSet();
        sample.displaySet();
        sample.removeItems();
        }

}

请参阅TreesetComparator按降序排列。

import java.util.Comparator;

public class SetComparator implements Comparator {
        public int compare(Object firstObject, Object secondObject) {
                String first = (String) firstObject;
                String second = (String) secondObject;
                return second.compareTo(first);
        }
}

答案 2 :(得分:0)

这里的想法是你需要改变你比较Employee3对象的方式。如果2个对象相等,则compareTo方法应返回0,如果用于比较的(this)或对象小于要与之比较的对象,则compareTo方法应返回负数,如果更大则为正数。因此,优雅的解决方案是通过执行以下操作来交换比较值:

public int compareTo(Object obj) {
    if(obj instanceof Employee3){
        Employee3 em=(Employee3)obj;
        return em.name.compareTo(this.name);
    }
    return 0;
}