【发布时间】:2015-06-05 18:41:35
【问题描述】:
我在概念化这个问题时遇到了一点麻烦,所以如果它含糊不清或在其他地方得到解决,我提前道歉。
不管怎样,我有一个名为Board 的大班。板上是ArrayList<Space> sList,板上的空间列表。其中每个 Space 是bList,一个 HashMap,表示哪些 Spaces 与这个特定 Space 接壤。 Board 的 init() 方法会创建所有的 Spaces 并给它们提供边界,例如
sList.add(new Location(7, true, "Police Station"));
sList.get(3).addToBList(sList.get(7)); //adds "Police Station" to the bList at sList index 3
但是,如果在 Board 中,我尝试查看某个 Space 的 bList,它总是返回 null,就像我从未向 bList 添加任何内容一样。但是,如果我查看 Space 本身,bList 总是充满了项目。所以,基本上,我试图从另一个类中的一个类中调用一个变量,如果我在另一个类本身中,它只会显示非空值 - 任何想法(或澄清问题)?
编辑:我想我要澄清我自己的问题。
如果 Space 有一个 getBList() getter 返回 bList(这是一个 hashMap),并且在 Board 中我向该 bList 添加某些值,为什么当我在 Board 中调用 getBList() 时 bList 返回“{}”?
此外,这就是 Arrow 的全部内容(见底部)。
代码本身:
public class Board {
ArrayList<Space> sList;
ArrayList<Player> pList;
int moveCount = 0;
ArrayList<Space> visited = new ArrayList<Space>();
public Board(int p, int oldGod){ //num of players, Old God
sList=new ArrayList<Space>();
pList=new ArrayList<Player>();
init();
move(sList.get(0), sList.get(34));
}
public Space move(Space start, Space end){
visited.add(start);
Iterator it = start.bList.entrySet().iterator();//this is where the trouble starts. bList returns only {}
if(start.equals(end)){
System.out.println("Here! You've arrived at " + start);
}
else{System.out.println("Time to debug. You're at " + start);
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
for(Space s : visited){
if(pair.getValue().equals(s)){
}
else{
return move((Space)pair.getValue(), end);
}
}
}
}
return start;
}
private void init() {
sList.add(new Location(1, true, "Ma's Boarding House"));
sList.add(new Location(2, true, "South Church"));
sList.get(1).addToBList(sList.get(2));
//etc...
}
}
public abstract class Space {
int district;
String name;
HashMap<Arrow, Space> bList = new HashMap<Arrow, Space>();
ArrayList<Creep> cList = new ArrayList<Creep>();
ArrayList<Player> pList = new ArrayList<Player>();
public String toString() {
return name;
}
public void addToBList(Space s, Arrow a){
bList.put(a, s);
}
public void borderList(){ //in here it always sees bList as full of variables
Iterator it = bList.entrySet().iterator();
while(it.hasNext()){
Map.Entry pair = (Map.Entry)it.next();
System.out.println(this + ": " + pair.getKey() + "-> " + pair.getValue()); //arrow towards
it.remove();
}
}
}
public class Arrow {
int color;
public Arrow(int c){
color=c;
}
public String toString(){
if(color==0)
return "Black";
else if(color==1)
return "White";
else if(color==2)
return "Both";
else
return "None";
}
}
【问题讨论】:
-
看起来你忘了实现
equals和hashCode,但坦率地说我不知道在哪里。 -
它一定是在
Arrow,因为这是唯一被用作键的东西。 -
Arrow类的代码,请。 -
addToBList(...)方法需要两个参数,但您在此语句中只传递一个参数sList.get(1).addToBList(sList.get(2)); -
addToBList 接收 2 个参数,在您的示例中,您只显示一个。对吗?