对象转换期间线程 "main" 出现异常 [java.lang.ClassCastException] - 如何解决转换问题?

Exception in thread "main" error during object casting [java.lang.ClassCastException] - How to fix casting issue?

我正在编写一个程序,其中包含几个 类(每个 2 个 super类 和一对 sub类)。在我的驱动程序文件中,我创建了两个数组:第一个数组包含来自两个完全独立的 类 的对象(与每个不相关,没有 parent/subclass 关系),第二个数组包含来自我的一个对象的对象超类及其子类类.

在编写和测试从每个数组中查找和打印最便宜和最昂贵的对象的方法时,我遇到了一个与我的转换相关的错误,我必须这样做才能使该方法起作用。我在下面包含了我的各种 类 的较短版本:

//First superclass
package Plane;
public class Plane {
    
    
     private String brand;
     private double price; 
     private int horsepower;
    
     
    public Plane() {
        brand = "test";
        price = 50000.99; 
        horsepower = 500;
    }
    
    public Plane(String planeBrand, double planePrice, int planePower) {
        this.brand = planeBrand;
        this.price = planePrice;
        this.horsepower = planePower;
    }
    
    public String getBrand() {
        return this.brand;
    }
    public void setBrand(String planeBrand) {
        this.brand = planeBrand;
    }
    
    public double getPrice() {
        return this.price;
    }
    
    public void setPrice(double planePrice) {
        this.price = planePrice;
    }
    
    public int getPower() {
        return this.horsepower;
    }
    
    public void setPower(int planePower) {
        this.horsepower = planePower;
    }
    
    public Airplane(Plane plane) {
        this.brand = plane.getBrand();
        this.price = plane.getPrice();
        this.horsepower = plane.getPower();
    }
    
    public String toString() {
        return "The airplane is manufactured by " + this.brand + " and costs $" + this.price + ". It has " + this.horsepower + " horsepower.";
    }

    public boolean equals(Plane plane) {
        if (!(plane instanceof Plane) || plane == null) {
                return false;
            } else if (this.brand != plane.getBrand() || this.price != plane.getPrice() || this.horsepower != plane.getPower()) {
                    return false;
                } else {
                    return true;
                }
            }
        }
//Second superclass
package Boat;
public class Boat {

    private double weight;
    private double price;
    
    public UAV() {
        weight = 3949.5;
        price = 64000;
    }
    
    public UAV(double boatWeight, double boatPrice) {
        weight = boatWeight;
        price = boatPrice;
    }
    
    public double getWeight() {
        return this.weight;
    }
    
    public void setWeight(double boatWeight) {
        this.weight = boatWeight;
    }
    
    public double getPrice() {
        return this.price;
    }

    public void setPrice(double boatPrice) {
        this.price = boatPrice;
    }
    
    public Boat(Boat boat) {
        this.weight = boat.getWeight();
        this.price = boat.getPrice();
    }
    
    public String toString() {
        return "This boat weighs " + this.getWeight() + "kg and costs $" + this.getPrice() + ".";
    }
    
    public boolean equals(Boat boat) {
        if (!(boat instanceof Boat) || boat == null) {
            return false;
        } else if (this.price != boat.price || this.weight != boat.weight) {
            return false;
        } else {
            return true;
        }
    }
    
}
//Driver file that produces the error
public class Main {

    public static void main(String[] args) {
        
       Object[] mixedObjects = new Object[8];
        
        mixedObjects[0] = new Plane();
        mixedObjects[1] = new Plane();
        mixedObjects[2] = new Helicopter();
        mixedObjects[3] = new Helicopter();
        mixedObjects[4] = new Drone();
        mixedObjects[5] = new Drone();
        mixedObjects[6] = new Boat();
        mixedObjects[7] = new Boat();
        
        
        Object[] planeObjects = new Object[6];
        
        airplaneObjects[0] = new Plane();
        airplaneObjects[1] = new Plane();
        airplaneObjects[2] = new Helicopter();
        airplaneObjects[3] = new Helicopter();
        airplaneObjects[4] = new Drone();
        airplaneObjects[5] = new Drone();
        
        findLeastAndMostExpensiveBoat(mixedObjects);
        findLeastAndMostExpensiveBoat(planeObjects);
        //The top line is line 91 (SEE ERROR MESSAGE)

public static void findLeastAndMostExpensiveBoat(Object[] mixedObjects) {
        if(mixedObjects.length == 1 && mixedObjects[0] instanceof Boat) {
            System.out.println(mixedObjects[0] + " is the most and least expensive.");
        }
        else if(mixedObjects.length == 0) {
            System.out.println("Empty array");
        }
        else if (mixedObjects.length == 1 && !(mixedObjects[0] instanceof Boat)){
            System.out.println("No UAV object detected.");
        }
        else {
            int max = 0;
            int min = 0;
            //Maximum
            for(int i = 0 ; i< mixedObjects.length; i++) {
                if(mixedObjects[i] instanceof Boat) {
                    System.out.println(mixedObjects[i].getClass());
            //The following line is line 157 (SEE ERROR MESSAGE)
                    if(((Boat)mixedObjects[i]).getPrice() >        ((Boat)mixedObjects[max]).getPrice()) {
                        max = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
            //Mininmum
            for(int i = 0 ; i< mixedObjects.length; i++) {
                if(mixedObjects[i] instanceof Boat) {
                    if(((Boat)mixedObjects[i]).getPrice() < ((Boat)mixedObjects[min]).getPrice()) {
                        min = i;
                    }
                } else {
                    System.out.println("No Boat object detected.");
                }
            }
        } 
    }
} 

findLeastAndMostExpensiveBoat 方法基本上检查任何数组中最昂贵和最便宜的船。如果没有船只存在,那么它会打印一条消息说明这一点。当我 运行 我的代码时得到的错误代码是:

Exception in thread "main" java.lang.ClassCastException: class Plane.Plane cannot be cast to class Boat.Boat (Plane.Plane and Boat.Boat are in unnamed module of loader 'app')
    at Main.findLeastAndMostExpensiveBoat(Main.java:157)
    at Main.main(Main.java:91)

根据错误消息,第 91 行是:findLeastAndMostExpensiveBoat(planeObjects);

根据错误消息,第 157 行是:if(((Boat)mixedObjects[i]).getPrice() > ((Boat)mixedObjects[max]).getPrice())

我的代码到底哪里出了问题?是我的转换语法有误,还是我需要解决更深层次的问题?

您正在通过 if(mixedObjects[i] instanceof Boat) 检查一个对象是否是 Boat 的实例,但是 您当然不知道 mixedObjects[max]Boat 的类型。最小情况也是如此。您也可以添加额外的条件,例如 mixedObjects[max] instanceof Boat