【问题标题】:obtain subclass parameters with collection sorting通过集合排序获取子类参数
【发布时间】: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


    【解决方案1】:

    测试 compareTo 中的类:

    • 如果它是你的子类

    • 还有另一个对象

    • 投射它们,并与您的子测试进行比较

    假设:

    public class Kiwi extends Fruit 
       {
       public String taste;  // public for demo
       public String smell;
       }
    

    测试和演员:

    Fruit one_fruit;  // this or other
    if (one_fruit instanceof Kiwi) 
        {
        Kiwi really_kiwi= (Kiwi) one_fruit; // CAST THERE !
        if (really_kiwi.taste ...) // You can then use taste and smell ...
    

    【讨论】:

    • 如何投射它们.. 我听说了,但我不知道该怎么做
    • 我会在几分钟内完成我的回答。
    • 如果 (really_kiwi.taste.compareTo(really_kiwi.taste)!=0) ??但是如何区分 this 和 other 进行比较
    • 另外,演员是在子类或超类中完成的。我不知道演员的方法……我是新人
    猜你喜欢
    • 2020-05-03
    • 1970-01-01
    • 1970-01-01
    • 2016-11-01
    • 1970-01-01
    • 2014-04-29
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    相关资源
    最近更新 更多