从抽象类数组中的对象获取最大值

时间:2015-01-29 21:14:41

标签: java polymorphism

我一直试图解决这个问题。 我想获得最大的ClassA值。 所以我有一个接口和2个类

public interface Something {

}

public class ClassA implements Something{
    private int a;
    public ClassA(int a) {
        this.a = a;
    }
    public int getA() {
        return a;
    }
    public void setA(int a) {
        this.a = a;
    }
 }

 public class ClassB implements Something{
    private int b;
    public ClassB(int b) {
        this.b = b;
    }
    public int getB() {
        return b;
    }
    public void setB(int b) {
        this.b = b;
    }
}

public class Program {
    public static void main(String[] args) {
        Something[] array = new Something[10];
        array[0] = new ClassA(1);
        array[1] = new ClassA(2);
        array[2] = new ClassB(0); 
        ClassA max = null;
        for (int i = 0; i < array.length; i++) {
            if(array[i]!=null && array[i] instanceof ClassA){
                //what do to here
            }
        }
    }
}

我以为我把它放在那里,

if(array[i].getClassA()>max.getClassA()){
                max = array[i];
}

但它不起作用,那么我该怎么做才能使它正常工作? 谢谢你的回答。

2 个答案:

答案 0 :(得分:0)

我猜测代码甚至没有编译。这是因为仅仅确定一个对象是一个类型是不够的,你必须强制引用它来访问它的方法或字段。

ClassA a = (ClassA) array[i];
if (a.getA() > max.getA())
    max = a;

BTW这不是多态性的一个例子,因为你没有在这里使用重写方法。

使用多态的示例可能看起来像

interface Something {
    boolean isA();
    int getA();
}

class ClassA implements Something {
    // fields and constructor
    public boolean isA() { return true; }
    public int getA() { return a; }
}

Something[] array = { new ClassA(1), new ClassA(2), new ClassB(0) }; 
ClassA max = null;
for (Something s : array) {
    if (s.isA()) {
       if (max == null || max.getA() < s.getA())
           max = s;
    }
}

答案 1 :(得分:0)

对max进行空检查,然后比较值

for (int i = 0; i < array.length; i++) 
{
    if(array[i]!=null && array[i] instanceof ClassA){
        if (max == null || array[i].getA() > max.getA()){
            max = array[i];
        }
    }
}
相关问题