我有以下代码:我正在尝试在 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;
}
}
Run Code Online (Sandbox Code Playgroud)
输出 :
[ 价格 1 名称:aa,
价格 5 名称:bb,
价格 10 名称:dd,
价格 41 名称:xx]
Item i5=new Item(3,"x5");没有插入为什么?
为什么我可以插入TreeSet。
你没有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.
Run Code Online (Sandbox Code Playgroud)
-1如果当前对象的价格低于您比较的对象的价格,您的实现不会返回。
| 归档时间: |
|
| 查看次数: |
12871 次 |
| 最近记录: |