如何从ArrayList中打印特定项

huangapple go评论73阅读模式
英文:

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&lt; Item &gt; db = new ArrayList&lt; Item &gt;();

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(&quot;The first car is : &quot;+db.car)
}
else{

  System.out.println(&quot;The first bike is : &quot;+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(&quot;A car is: &quot; + item)
    } else {
        System.out.println(&quot;A bike is: &quot; + item)
    }
}

huangapple
  • 本文由 发表于 2020年4月10日 22:39:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/61142631.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定