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

Getting max value from object in an abstract class array

我一直在努力解决这个问题。 我想获得最大的 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];
}

但它不工作,那么我应该怎么做才能让它工作? 感谢您的回答。

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

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

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

一个使用多态性的例子可能看起来像

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;
    }
}

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

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];
        }
    }
}