用于修改集合中某些元素的适当数据结构是什么



假设我有一个对象集合,对于每个具有特定属性的对象,我想删除该对象并在其位置插入一个新对象。举个例子,我有一个动物对象的集合:

[狗,小狗,小狗,郊狼,小狗,狐狸,小狗,猫,费雷特,土拨鼠]

for each animal -> 
if animal = Dog, Ferret, Groundhog continue iterating
else if animal = Coyote, replace with Dog and continue iterating
else if animal = Fox, replace with Dog and continue iterating

在保持收集的初始顺序的同时,哪种数据结构最适合完成这样的任务?欢迎提出任何建议。

数组是您可以使用的最轻量级的数据结构,如果元素数量不变,则最合适。唯一的问题是,必须声明数组的引用类型为全部相等。我建议所有的类都从父类扩展,比如"Animal"。在下面的解决方案中,我扩展了Animal:中的所有类

class Animal{
}
class Dog extends Animal{
}
class Cat extends Animal{
}
class Coyote extends Animal{
}
class Fox extends Animal{
}
class Ferret extends Animal{
}
class Groundhog extends Animal{
}

然后我使用了一个数组来存储Animal实例。然后,for循环将遍历每个项目,并用Dog替换Fox和Coyote的实例。

public static void main(String[] args) {
Dog a = new Dog();
Dog b = new Dog();
Dog c = new Dog();
Coyote d = new Coyote();
Dog e = new Dog();
Fox f = new Fox();
Dog g = new Dog();
Cat h = new Cat();
Ferret i = new Ferret();
Groundhog j = new Groundhog();
Animal[] animalArray = new Animal[10];
animalArray[0] = a;
animalArray[1] = b;
animalArray[2] = c;
animalArray[3] = d;
animalArray[4] = e;
animalArray[5] = f;
animalArray[6] = g;
animalArray[7] = h;
animalArray[8] = i;
animalArray[9] = j;

for(int ii = 0; ii<animalArray.length; ii++){
if (animalArray[ii] instanceof Coyote || animalArray[ii] instanceof Fox){
animalArray[ii] = new Dog();
}
}
}

如果在公共静态void main方法中包含以下代码,则可以运行该方法以获得以下输出。

for(Animal animal: animalArray){
System.out.println(animal.getClass());
}

输出(其中"Test"是包名称(:

class Test.Dog
class Test.Dog
class Test.Dog
class Test.Dog
class Test.Dog
class Test.Dog
class Test.Dog
class Test.Cat
class Test.Ferret
class Test.Groundhog

最新更新