java—什么是适当的数据结构来就地修改集合的某些元素?

ndasle7k  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(286)

假设我有一个对象集合,对于每个具有特定属性的对象,我想移除该对象并在其位置插入一个新对象。举个例子,假设我收集了一些动物物品:
[狗,狗,狗,郊狼,狗,狐狸,狗,猫,雪貂,土拨鼠]

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

在保持集合的初始顺序的同时,哪种数据结构最适合完成这样的任务?任何建议都将不胜感激。

11dmarpk

11dmarpk1#

数组是您可以使用的最轻量的数据结构,如果元素的数量不变,它也是最合适的。唯一的问题是必须将数组的引用类型声明为all相等。我建议所有的类都从父类扩展,比如“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{

}

然后我使用一个数组来存储动物示例。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();
            }
        }
}

如果在publicstaticvoidmain方法中包含以下代码,则可以运行该方法以获得以下输出。

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

相关问题