![](/img/trans.png)
[英]How to I print out a specific item from an arraylist based on a string entered
[英]How to print specific item from ArrayList [SOLVED]
我正在嘗試從我的 ArrayList 打印特定項目
我有超級 class 命名項目,我創建了一個新的 class 與 ArrayList 在數據庫中名為 db 我存儲汽車,自行車,
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==newCar){
System.out.println("The first car is : "+db.car)
}
else{
System.out.println("The first bike is : "+db.car)
}
使用instanceof
檢查 object 的運行時類型。
迭代示例:
for (Item item : db) {
if (item instanceof Car){
System.out.println("A car is: " + item)
} else {
System.out.println("A bike is: " + item)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.