-1

The question might look trivial but I couldn't find the solution anywhere!

I have an abstract superclass Vehicle, and there are 4 subclasses that extend it, viz Car, Bus, Lorry and Bicycle.

I also have an ArrayList<Vehicle> V containing many Vehicle objects but we don't know which type of vehicle.

Now I am not able to calculate the number of Cars in the ArrayList V

int carCount = 0;
for (Vehicle ob: V){
    if (ob is a car) {
        carCount++;
        }
    }
return carCount;

Would like to know what should be the code inside if(ob is a car) in the code above.

Thanks!

3 Answers3

4
if(ob instanceof Car)

Please try this

BatyaGG
  • 674
  • 1
  • 7
  • 19
3

You can do it in one line, if you use java-8:

V.stream().filter(Car.class::isInstance).count();
Anton Balaniuc
  • 10,889
  • 1
  • 35
  • 53
2

You are looking for

if (ob instanceof Car) {
    carCount++;
}

Get detailed information here: Oracle: instanceof

Mathias Bader
  • 3,585
  • 7
  • 39
  • 61