2011-03-02 64 views
0

我們被要求替換ArrayList,並使用接口List來代替兩個類。我一直在努力,但無濟於事。如果有人能夠幫助其中一個班級展示如何完成,我會非常感激。提前致謝。接口列表 - java

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<Animal> newAnimals); 

/** 
+1

究竟是什麼問題?你試過什麼了? – Tommi 2011-03-02 17:11:12

+4

'abstract public void act(List newAnimals);'不起作用? – 2011-03-02 17:12:03

+1

只是瞭解什麼接口適用,並且解決方案將自然適合您:http://en.wikipedia.org/wiki/Interface_%28Java%29和http://download.oracle.com/javase/tutorial/ java/concepts/interface.html – dm76 2011-03-02 17:16:02

回答

0

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

and in body body do newAnimals = new ArrayList();

2

「List」是一個接口,因此它不能被實例化。將所有現在是ArrayList的聲明替換爲List,其中x是容器包含的類。但是,保持實例不變(List<x> = new ArrayList<x>();有效)。這是一個簡單的改變,但你提供的代碼顯然是不完整的。

如果聽起來像一個巨魔,你也應該標記這個「家庭作業」或在其他地方尋找工作,除非你強烈認爲這個變化在你的代碼中是合理的。

+0

他的問題確實聽起來像作業! – dm76 2011-03-02 17:18:28