Java: TreeSet集合和Comparable接口

5

我有以下代码: 我正在尝试将Item对象插入TreeSet中,但是我没有得到期望的输出。

public class Main
{
    public static void main(String a[])
    {
        Item i1=new Item(1,"aa");
        Item i2=new Item(5,"bb");
        Item i3=new Item(10,"dd");
        Item i4=new Item(41,"xx");
        Item i5=new Item(3,"x5");
        TreeSet t=new TreeSet();    
        t.add(i1);
        t.add(i2);
        t.add(i3);
        t.add(i4);
        t.add(i5);
        System.out.println(t);      
    }
}
class Item implements Comparable<Item>
{
    String  nm;
    int price;
    public Item(int n,String nm)
    {
        this.nm=nm;
        price=n;
    }
    public int compareTo(Item i1)
    {
        if(price==i1.price)
            return 0;
        else if(price>=i1.price)
            return 1;
        else
            return 0;
    }
    public String  toString()
    {
        return "\nPrice "+price+" Name : "+nm;
    }    
}

输出:

[ 价格1的名称:aa,
价格5的名称:bb,
价格10的名称:dd,
价格41的名称:xx ]

Item i5=new Item(3,"x5");为什么没有被插入?
我该怎么做才能把它插入到TreeSet中呢?

5个回答

4
你没有正确实现compareTo()方法。以下是javadoc的一段摘录:
Compares this object with the specified object for order. Returns a negative integer,
zero, or a positive integer as this object is less than, equal to, or greater than
the specified object.

您的实现如果当前对象价格小于您比较的对象的价格,就不会返回-1

2
在你的compareTo方法中,你应该添加else return -1;

2
compareTo 方法中,替换为:
else
        return 0;

使用:

else
        return -1;

2

实现 Comparable 接口的类必须遵守该协议:如果 a.compareTo(b) < 0b.compareTo(a) > 0。但是你的类没有遵守这个协议。


0
主要问题在于您的compareTo方法。您实现了错误的逻辑。我已经修改了您的类并在我的eclipse上进行了测试,它可以输出所需的结果。请查看下面的代码。
import java.util.TreeSet;
public class Main
{
    public static void main(String a[])
    {
        Item i1=new Item(1,"aa");
        Item i2=new Item(5,"bb");
        Item i3=new Item(10,"dd");
        Item i4=new Item(41,"xx");
        Item i5=new Item(3,"x5");
        TreeSet<Item> t=new TreeSet<Item>();    
        t.add(i1);
        t.add(i2);
        t.add(i3);
        t.add(i4);
        t.add(i5);
        System.out.println(t);      
    }
}
class Item implements Comparable<Item>
{
    String  nm;
    int price;
    public Item(int n,String nm)
    {
        this.nm=nm;
        price=n;
    }
    public int compareTo(Item i1)
    {
        // Objects equal so no need to add 
        if(price==i1.price)
        {
            return 0;
        }
        // Object are greater
        else if(price>i1.price)
        {

            return 1;
        }
        // Object is lower
        else
        {
            return -1;
        }
    }
    public String  toString()
    {
        return "\nPrice "+price+" Name : "+nm;
    }    
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接