如何使用 .getClass 在数组中显示继承的 类 并按吨位对该数组进行排序?

How do I use .getClass to show inherited classes within an Array and sort that Array by tonnage?

我不确定如何在 Array 中显示每个继承的 class shipType 的 class 名称。我最初将 CargoShip.class 等添加到 class 中 toString() 的开始实例,但我需要在 main 方法中的 for 循环中进行,然后按吨位。我需要一些关于如何做到这一点的见解,谢谢?

public class TestShips {
    public static void main(String[] args) {

        Ship[] ships = {
            new CruiseShip("Molly", 1995, 7000, 7400, "the arabian gulf"),
            new CruiseShip("Jummy", 1945, 9000, 8755, "the persian gulf"),
            new CargoShip("Bon", 1925, 7000, "goat milk", 4000),
            new CargoShip("Gimmy", 1934, 4999, "butter milk", 5000),
            new WarShip("USS America", 1996, 7000, "Super Carrier", "US"),
            new WarShip("USS Banebridge", 1911, 7009, "Supply Ship", "US")

        };

        System.out.println("An unordered fleet of various ships");
        for (int i = 0; i < ships.length; ++i) {

            System.out.print(ships[i]);
        }

        CruiseShip cruise3 = new CruiseShip("Harbol", 1993, 70000, 48522, "Egypt");
        ArrayList<Ship> shiplist = new ArrayList<Ship>(Arrays.asList(ships));
        shiplist.add(cruise3);
        System.out.println("\nFleet size is now 7");

        java.util.Arrays.sort(ships);
    }
}

你可能在你的 superclass Ship 中覆盖了 toString(),像这样:

public String toString() {
    return "Ship called " + name + " built in " + year + " can hold " + tonnage + " tons";
}

Ship called Molly built in 1995 can hold 7000 tons

您可以通过调用 o.getClass().getSimpleName();.

获取 Object o 的 class 名称

所以方法应该是这样的:

public String toString() {
    return getClass().getSimpleName() + " called " + name + " built in " + year + " can hold " + tonnage + " tons";
}

CruiseShip called Molly built in 1995 can hold 7000 tons


现在您想按吨位对数组进行排序。

使用此代码:

import java.util.Arrays; // top of your class file
Arrays.sort(ships, Comparator.comparing(ship -> ship.getTonnage());