I have following code :
I am trying to insert Item object in TreeSet and I am not getting desire output.
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;
}
}
Output :
[ Price 1 Name : aa,
Price 5 Name : bb,
Price 10 Name : dd,
Price 41 Name : xx ]
Item i5=new Item(3,"x5"); is not Inserted why?
Why I can do to insert in TreeSet.
You haven’t implemented
compareTo()correctly. Here’s an extract from javadoc:Your implementation doesn’t return
-1in case price of current object is less than price of object you compare with.