We have been asked to replace ArrayList and use interface List instead in two classes. I've been trying but to no avail. If someone could help with one of the classes to show how it is done, I would be very appreciative. Thanks in advance.
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.fie开发者_如何学Cld = 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<Animal> newAnimals);
/**
"List" is an interface, therefore it cannot be instantiated. Replace all declarations that are now ArrayList with List, where x is the class contained by the container. But, leave the instantiation the same (List<x> = new ArrayList<x>();
is valid). It's a simple change but the code you provided is clearly incomplete.
At the risk of sounding like a troll, you should also tag this "homework" or seek employment elsewhere unless you strongly feel that this change is justified in your code.
Change abstract public void act(ArrayList newAnimals); to abstract public void act(List newAnimals);
and in method body do newAnimals = new ArrayList();
精彩评论