Good day,
Imagine I have the following code: (These are obviously not all the attributes)
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;
}
}
The objects are added to an ArrayList:
ArrayList<Car> cars = new ArrayList<>();
Examples:
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")));
Now the questions are:
How can I make a method so I only list all cars which have the value isClean "true";
How can I make a method with the following signature: public static void printCarsSpecific(ArrayList Cars, String fuelType) So for example if I put in: printCarsSpecific("gasoline"); that only those cars will be shown when printing the ArrayList.
PS: it's not homework. Just for education I typed the code above by myself and didnt copy and paste because it would become way to large.
I tried these methods:
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));
}
}
}
and
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));
}
}
}
I guess I don't have to delete these items as i've seen by examples under here.