0

I am trying to print specific item from my ArrayList

I have super class named Item, I created a new class with ArrayList named db in the database I'm storing Cars,Bikes ,

ArrayList< Item > db = new ArrayList< Item >();

Car newCar = new Car(getModel(),getPrice());

db.add(newCar);

Bike newBike = new Bike(getModel(),getPrice())

db.add(newBike);

Now I'm trying to print only cars something like this,

if( db==newCar){
  System.out.println("The first car is : "+db.car)
}
else{

  System.out.println("The first bike is : "+db.car)

}
vvvvv
  • 25,404
  • 19
  • 49
  • 81
cshostgr
  • 3
  • 5
  • You would have found the solution while searching. many posts. https://stackoverflow.com/questions/541749/how-to-determine-an-objects-class – Vaibs Apr 10 '20 at 14:56

1 Answers1

3

Use the instanceof to check the runtime type of object.

Example of iteration:

for (Item item : db) {
    if (item instanceof Car){
        System.out.println("A car is: " + item)
    } else {
        System.out.println("A bike is: " + item)
    }
}
Giancarlo Romeo
  • 663
  • 1
  • 9
  • 24