3

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

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 中插入。

4

5 回答 5

3

您没有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如果当前对象的价格低于您比较的对象的价格,您的实现不会返回。

于 2012-11-18T07:12:08.770 回答
2

在你的compareTo方法中你应该有else return -1;

于 2012-11-18T07:12:24.173 回答
2

compareTo替换:

else
        return 0;

和:

else
        return -1;
于 2012-11-18T07:12:32.510 回答
2

一个类的实现Comparable必须遵守契约:if a.compareTo(b) < 0then b.compareTo(a) > 0。你的不符合。

于 2012-11-18T07:12:55.903 回答
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;
    }    
}
于 2012-12-28T05:03:01.550 回答