Home > Blockchain >  How to loop through an array of different objects in Java using the enhanced for loop
How to loop through an array of different objects in Java using the enhanced for loop

Time:05-31

I have an array of objects of classes Car, Bicycle, and Van. I want to iterate through all objects and execute the go() method. go() for one class looks like this.

public class Van extends Vehicle {
    @Override
    public void go() {
        System.out.println("Van started");
    }
}

Each of these classes inherits the Vehicle class. So, when I initialized an array of type Vehicle[], it worked without a problem.

Now I want to do the same with an array of Object[]. But as the objects are of different types, I get an error asking to cast the x to the relevant datatype (in this case Car, Van, or Bicycle). I tried using the x.getClass() but it gives me answers as class Car, class Bicycle, etc. When I try to execute go() method, I get an error saying The method go() is undefined for the type Class<capture#3-of ? extends Object>


public class App {
    public static void main(String[] args) throws Exception {
        Car car = new Car();
        Bicycle bicycle = new Bicycle();
        Van van = new Van();

        Object[] racers = {car, bicycle, van};  

        for(Object x : racers) {
            System.out.println(x.getClass()); 

            x.getClass().go();  // error - The method go() is undefined for the type Class<capture#3-of ? extends Object>
        }
    }
}

CodePudding user response:

Found the answer

public class App {
    public static void main(String[] args) throws Exception {
        Car car = new Car();
        Bicycle bicycle = new Bicycle();
        Van van = new Van();

        Object[] racers = {car, bicycle, van};  

        for(Object x : racers) {
            System.out.println(x.getClass()); 

            ((Vehicle) x).go();  // this is the only change I made
        }
    }
}

CodePudding user response:

The following would have worked

    Vehicle[] racers = {car, bicycle, van};  
    for (Vehicle x : racers) { ... x.go();

Dynamic detection does works too. You could use the modern Stream<?>.

    Object[] racers = {car, bicycle, van};  

    Arrays.stream(racers)
       .filter(r -> r instanceOf(Vehicle)
       .map(Vehicle.class::cast)
       .forEach(r -> {
            r.go(); ...
       };

CodePudding user response:

You have to use the "instanceof" keyword

    Object o = "testString";

    if (o instanceof Integer) {
        System.out.println("is Integer");
        return
    }

    if (o instanceof String) {
        System.out.println("is String");
        return;
    }
  • Related