【发布时间】:2016-03-18 17:31:42
【问题描述】:
问题:
1) 我想做collection.sort。问题出在“public int compareTo(Fruit other)”内部,我想按字母顺序对味道和气味进行排序,但是,我不知道如何将子类值传递给超类并使用“this & other”比较.感谢帮助
PS:代码简化了,只想知道子类参数的排序方式。
代码如下:
public class Fruit implements Comparable<Fruit>{
protected String Type;
protected int price;
public Fruit(String Type , int Price)
{
this.Type = Type;
this.price = Price;
}
public int compareTo (Fruit other)
{
if (this.Type.compareTo(other.Type) != 0)
{
return (this.Type.compareTo(other.Type));
}
else if (Integer.compare(this.price, other.price)!=0)
{
return (Integer.compare(this.price, other.price));
}
//else if ( ** If price is same , then get sorting with taste
in alphabetical order **) //
{
}
//else if ( ** if taste is the same , then get sorting with smell
in alphabetical order **) //
{
}
else
{
return 0;
}
}
public class orange extends Fruit()
{
private String taste;
private String smell;
public orange (String Type , int Price , String taste , String smell)
{
super (Type, Price);
this.taste = taste;
this.smell = smell;
}
}
【问题讨论】:
标签: java sorting collections