0

例子:

 Car carOne = new Toyota("Camry");
 Toyota carTwo = new Toyota("Corolla");
        

它们都在 ArrayList 中。如何在 for/each 循环的帮助下只能删除carOne但不能删除carTwo?我已经尝试过instanceOf,它删除了这两个项目

4

2 回答 2

0

一种选择是使用增强的 for 循环收集所有要删除的对象,并在完成迭代后删除所有找到的对象。例如,假设您的对象蓝图看起来像这样:

abstract class Car {
    public abstract String getModel();
}

class Toyota extends Car {
    
    private String model;
    private String color;
    
    public Toyota(String model) {
        this.model = model;
    }
    
    public Toyota(String model, String color) {
        this.model = model;
        this.color = color;
    }
    
    public String getModel() {
        return model;
    }
    
    public String toString() {
        return "[model: " + model+ ", color:" + color + "]";
    }
}

你有这样的汽车集合:

List<Car> cars = new ArrayList<Car>();
cars.add(new Toyota("Prius", "Red"));
cars.add(new Toyota("Camry", "Red"));
cars.add(new Toyota("Corolla", "Red"));
cars.add(new Toyota("Prius", "Blue"));
cars.add(new Toyota("Camry", "Blue"));
cars.add(new Toyota("Corolla", "Blue"));

现在,您只想删除属于 Camrys 的汽车。收集型号为“ Camry”的汽车列表。

Car camry = new Toyota("Camry");
List<Car> camryList = new ArrayList<Car>();
        
for (Car car: cars) {
    if (car.getModel().equals(camry.getModel())) {
        camryList.add(car);
    }
}

最后删除camryListfrom cars

System.out.println("Cars before removal: " + cars.toString());
System.out.println("Removing cars: " + camryList);
cars.removeAll(camryList);
System.out.println("Cars after removal: " + cars.toString());

另一种选择是使用ListIterator它支持在迭代过程中删除和添加项目。它看起来像这样:

Car camry = new Toyota("Camry");
ListIterator<Car> iter = cars.listIterator();
while(iter.hasNext()){
    if(iter.next().getModel().equals(camry.getModel())){
        iter.remove();
    }
}

如果您使用的是 JDK* 或更高版本,则可以像这样使用 removeIf 方法:

Car camry = new Toyota("Camry");
cars.removeIf(x -> x.getModel().equals(camry.getModel()));
于 2020-08-21T04:42:44.803 回答
0

使用 java.util.List.remove 方法最容易删除 carTwo:

cars.remove(carTwo);

请参阅上下文中的方法删除:

public static void main(String[] args) {
    Car carOne = new Toyota("Camry");
    Toyota carTwo = new Toyota("Corolla");
    List<Car> cars = new ArrayList<>(Arrays.asList(carOne, carTwo));
    System.out.println("List of cars before removal of carTwo:\t" + cars);

    cars.remove(carTwo);
    System.out.println("List of cars after removal of carTwo:\t" + cars);
}

输出:

List of cars before removal of carTwo:  [Toyota{model='Camry'}, Toyota{model='Corolla'}]
List of cars after removal of carTwo:   [Toyota{model='Camry'}]

见汽车界面:

public interface Car {
    // Intentionally empty
}

见丰田儿童班:

public class Toyota implements Car {
    private final String model;

    public Toyota(String model) {
        this.model = model;
    }

    @Override 
    public String toString() {
        return "Toyota{" +
                "model='" + model + '\'' +
                '}';
    }
}

==============================

使用 foreach 循环删除 carTwo:

==============================

注意:推荐使用这种替代方法,只是为了用 foreach 循环回答原始问题。

在此示例中,将找到列表汽车的索引以删除 carTwo 的实例,只是为了使其与第一个示例不同。

我们将比较类引用以找到 carTwo 索引。

类对象的 toString() 用于获取类引用:

super.toString()

在上下文中查看此方法:

public static void main(String[] args) {
    Car carOne = new Toyota("Camry");
    Toyota carTwo = new Toyota("Corolla");
    List<Car> cars = new ArrayList<>(Arrays.asList(carOne, carTwo));
    System.out.println("List of cars before removal of carTwo:\t" + cars);

    int index = -1;
    for (Car car : cars) {
        if(car.getClassReference().equals(carTwo.getClassReference())) {
            index = cars.indexOf(car);
        }
    }

    cars.remove(index);

    System.out.println("List of cars after removal of carTwo:\t" + cars);
}

输出:

List of cars before removal of carTwo:  [Toyota{model='Camry'}, Toyota{model='Corolla'}]
List of cars after removal of carTwo:   [Toyota{model='Camry'}]

见 Car 接口(添加方法):

public interface Car {
    String getClassReference();
}

查看更改后的 Toyota 子类:

public class Toyota implements Car {
    private final String model;

    public Toyota(String model) {
        this.model = model;
    }

    @Override
    public String toString() {
        return "Toyota{" +
                "model='" + model + '\'' +
                '}';
    }

    @Override
    public String getClassReference() {
        return super.toString();
    }
}

替代:

int index = -1;
for (Car car : cars) {
    if(car.getClassReference().equals(carTwo.getClassReference())) {
        index = cars.indexOf(car);
    }
}

汽车.流():

    int index = cars.stream()
            .filter(car -> car.getClassReference().equals(carTwo.getClassReference()))
            .map(car -> cars.indexOf(car))
            .collect(Collectors.toList())
            .get(0)
            .intValue();
于 2020-08-21T07:59:24.777 回答