接口列表 – java

我们被要求替换ArrayList并在两个类中使用接口List。 我一直在尝试但无济于事。 如果有人可以帮助其中一个课程来展示它是如何完成的,我将非常感激。 提前致谢。

import java.util.ArrayList; public abstract class Animal { // Whether the animal is alive or not. private boolean alive; // The animal's field. private Field field; // The animal's position in the field. private Location location; /** * Create a new animal at location in field. * * @param field The field currently occupied. * @param location The location within the field. */ public Animal(Field field, Location location) { alive = true; this.field = field; setLocation(location); } /** * Make this animal act - that is: make it do * whatever it wants/needs to do. * @param newAnimals A list to add newly born animals to. */ abstract public void act(ArrayList newAnimals); /** 

“List”是一个接口,因此无法实例化。 将所有现在为ArrayList的声明替换为List,其中x是容器包含的类。 但是,保持实例化是相同的( List = new ArrayList();是有效的)。 这是一个简单的更改,但您提供的代码显然不完整。

冒着听起来像巨魔的风险,你也应该标记这个“家庭作业”或在其他地方寻找工作,除非你强烈认为这种改变在你的代码中是合理的。

更改abstract public void act(ArrayList newAnimals); 抽象public void act(List newAnimals);

并在方法体中执行newAnimals = new ArrayList();