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

Time:05-29

I'm unsure of how to display the class name for each inherited class shipType within an Array. I originally added CargoShip.class etc. to the beginning instance of the toString() within that class but I need to do it in a for loop within the main method and then sort by tonnage. I need some insight on How I can do that please and thank you?

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

CodePudding user response:

You probably overrode toString() in your superclass Ship, like this:

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

Ship called Molly built in 1995 can hold 7000 tons

You can get the class name of an Object o by calling o.getClass().getSimpleName();.

So the method should look like this:

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


Now you want to sort your array by tonnage.

Use this code:

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