好日子搜索在ArrayList中的特定对象,通过属性
想象我有以下代码: (这些显然不是所有的属性)
class Owner {
private String name;
}
class Car {
private Owner owner;
private String brandName;
public boolean isClean() { // not included in the contructor
return false;
}
class FuelCar extends Car {
private String fuelType;
public boolean isClean() {
if (fuelType.equals("Diesel")){
return false;
} else {
return true;
}
}
class ElectricCar extends Car {
private int batteryLevel;
public boolean isClean() {
return true;
}
}
的对象添加到一个ArrayList:
ArrayList<Car> cars = new ArrayList<>();
实例:
cars.add(new Auto("Audi", new Owner("Peter")));
cars.add(new Auto("Fiat", new Owner("Rob")));
cars.add(new Auto(Mercedes, null));
cars.add(new ElectricCar(10, "Opel ", new Owner("Unknown")));
cars.add(new ElectricCar(100,"Google", new Owner("Google")));
cars.add(new FuelCar("diesel", "Seat", new Owner("Tom")));
cars.add(new FuelCar("gasonline", "Smart", new Owner("Marcel")));
现在的问题是:
我怎样才能让一个方法,所以我只列出其中具有值isClean“真”的所有汽车;
如何使具有以下签名的方法: 公共静态无效printCarsSpecific(ArrayList的汽车,字符串fuelType) 因此,举例来说,如果我把在: printCarsSpecific(“汽油”); 打印ArrayList时只显示那些汽车。
PS:这不是功课。只为教育 我自己输入了上面的代码,并没有复制和粘贴,因为它会变大。
我尝试以下方法:
public static void printBedrijfsautosMetType(ArrayList<Auto> autos, String brandstof) {
Iterator<Auto> iter = autos.iterator();
while (iter.hasNext()) {
Auto auto = iter.next();
if (auto instanceof BrandstofAuto) {
String brandstof1 = ((BrandstofAuto) auto).getBrandstof();
if (!brandstof1.equals(brandstof) || brandstof1 == null) {
iter.remove();
}
}
for (int i = 0; i < autos.size(); i++) {
System.out.println(autos.get(i));
}
}
}
和
public static void printSchoneAutos(ArrayList<Auto> autos) {
Iterator<Auto> iter = autos.iterator();
while (iter.hasNext()) {
Auto auto = iter.next();
if (auto instanceof BrandstofAuto) {
boolean isschoon = ((BrandstofAuto) auto).isSchoon();
boolean isschoon3 = auto.isSchoon();
if (isschoon3 == false || isschoon == false) {
iter.remove();
}
}
for (int i = 0; i < autos.size(); i++) {
System.out.println(autos.get(i));
}
}
}
我想我没有删除这些项目,因为我已经通过例子在这里看到。
你尝试过什么吗? – proskor
@ R.Schouten您至少应该首先缩进您的代码。此外,你的语法是错误的,为什么像'class'和'private'这样的词汇是大写的?在我看来,你甚至不知道基本知识。也许你应该发布你到目前为止尝试过的东西。 – user3437460
这确实看起来像一个家庭作业... –