英文:
How to print specific item from ArrayList
问题
我正在尝试从我的ArrayList中打印特定的项目
我有一个名为Item的超类,我创建了一个带有ArrayList的新类,数据库中我存储了汽车和摩托车,
ArrayList<Item> db = new ArrayList<Item>();
Car newCar = new Car(getModel(), getPrice());
db.add(newCar);
Bike newBike = new Bike(getModel(), getPrice());
db.add(newBike);
现在我想只打印汽车,类似这样,
if (db.get(0) instanceof Car) {
Car car = (Car) db.get(0);
System.out.println("The first car is: " + car.getModel());
} else {
System.out.println("The first bike is: " + ((Bike) db.get(0)).getModel());
}
英文:
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)
}
答案1
得分: 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);
}
}
英文:
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)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论