方法remove/removeAll无法正常工作



所以我试图打印出我制作的所有宠物。主要是我对方法removeCats有问题,我想是的…,我如何更改我的方法removeCats以使其正确编译?

public class Solution
{
public static void main(String[] args)
{
Set<Cat> cats = createCats();
Set<Dog> dogs = createDogs();
Set<Object> pets = join(cats, dogs);
printPets(pets);
removeCats(pets, cats);
printPets(pets);
}

//2.这里我创建了createCats方法,它必须返回4个cat

public static Set<Cat> createCats()
{
Set<Cat> result = new HashSet<Cat>();
result.add(new Cat());
result.add(new Cat());
result.add(new Cat());
result.add(new Cat());
return result;
}

//3.这里我制作了createDogs方法,它必须返回3个dogs

public static Set<Dog> createDogs()
{
Set<Dog> resultD = new HashSet<Dog>();
resultD.add(new Dog());
resultD.add(new Dog());
resultD.add(new Dog());
return resultD;
}

//4.在这里我创建了方法join,它必须返回所有的猫和狗

public static Set<Object> join(Set<Cat> cats, Set<Dog> dogs)
{
Set<Object> lol = new HashSet<Object>();
lol.add(new Cat());
lol.add(new Dog());
return lol;
}

//5.方法removeCats,必须移除所有猫

public static void removeCats(Set<Object> pets, Set<Cat> cats)
{

Iterator<Object> it = pets.iterator();
while(it.hasNext()){
Object e = it.next();
if(pets.containsAll(cats))
pets.removeAll(cats);
}
}

//6.方法打印宠物,必须在屏幕上打印出他包含的所有动物。每只新品种的动物

public static void printPets(Set<Object> pets)
{
for (Object s : pets){
System.out.println(s);
}
}
**//1. Inside class solution im making class cat and dog.**
public static class Cat{
}
public static class Dog{
}

我看到您的代码有几个问题:

  • 您的removeCats函数正在创建一个迭代器,而不是使用它,然后可能会爆炸为ConcurrentModificationException,因为您在迭代pets集合时从它中删除了一些东西。许多其他答案都指出了这一点,解决这一问题的最佳方法是用类似pets.removeAll(cats);的东西替换整个函数。如果出于某种原因确实必须使用迭代器,那么应该对cats进行迭代,并调用pets.remove(cat);

一旦修复,您就不会崩溃但是。。。removeCats仍然不会达到您的预期,因为cats中的对象实际上都不存在于pets

  • 您的join函数并没有根据方法签名执行我期望它执行的操作——它没有将两个集合连接在一起,而是丢弃输入并创建一个新列表。你可能想做一些类似的事情

    pets.addAll(cats);
    pets.addAll(dogs);
    

一旦修复了此问题,printPets函数将正常工作,而removeCats实际上将以调用它的方式产生正确的效果,因为pets实际上包含cats,而不是它们的一些新实例。

iterating时不能更新Set。此外,也没有迭代它的用法。如果containsAll返回true,只需删除元素

if(pets.containsAll(cats))
{
pets.removeAll(cats);
}

您的removeCats()方法中有一个错误会导致爆炸:您在迭代集合时直接修改集合。

迭代时不能添加或删除元素。您只能拨打iterator.remove();

试试这个:

public static void removeCats(Set<Object> pets, Set<Cat> cats) {
pets.removeAll(cats);
}

您不能从Set中删除元素,在对其进行迭代时,这将给您ConcurrentModificationException

你可以像一样使用什么

pets.removeAll(cats);

最新更新