简体   繁体   English

HashMap返回Null,无论如何

[英]HashMap returns Null no matter what

I'm having a little trouble conceptualizing this question, so I apologize in advance if it's vague or been solved elsewhere. 我在概念化此问题时遇到了一些麻烦,因此,如果该问题含糊其辞或在其他地方已解决,我谨向您致歉。

Anyway, I've got a big class called Board . 无论如何,我有一个叫做Board大班。 In board is ArrayList<Space> sList , a list of Space on the Board. 板中是ArrayList<Space> sList ,板中的ArrayList<Space> sList列表。 Which each Space is bList , a HashMap that represents which Spaces border this particular Space. 每个空间是哪个bList ,一个HashMap,表示哪个空间与该特定空间接壤。 The init() method of Board creates all the Spaces and gives them their borders, for example Boardinit()方法创建所有空间并为其指定边界,例如

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

However, if, while in Board , I try and look the bList of a certain Space, it always returns null, like I never added anything to bList. 但是,如果在Board尝试查看某个空格的bList时,它总是返回null,就像我从未向bList添加任何东西一样。 However, if I look within the Space itself, bList is always full of items. 但是,如果我查看Space本身,则bList总是充满项目。 So, basically, I'm trying to invoke a variable from a class in another class and it only shows non-null values if I'm within that other class itself - any ideas (or clarifying questions)? 因此,基本上,我试图从另一个类的一个类中调用一个变量,并且仅当我位于另一个类本身内时,它才会显示非空值-有什么想法(或澄清问题)?

EDIT: I think I'm going to clarify my own question. 编辑:我想我要澄清自己的问题。

If Space has a getBList() getter that returns bList (which is a hashMap), and in Board I add certain values to that bList, why does bList return "{}" when I call getBList() in Board? 如果Space有一个返回bList(是hashMap)的getBList()getter,并且在Board中我向该bList添加了某些值,为什么当我在Board中调用getBList()时bList返回“ {}”?

Also, this is all Arrow is (see bottom). 另外,这就是Arrow的全部功能(请参阅底部)。

The code itself: 代码本身:

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";
    }

}

I suggest you read the Javadoc for Object.hashCode() 我建议您阅读Javadoc for Object.hashCode()

Returns a hash code value for the object. 返回对象的哈希码值。 This method is supported for the benefit of hash tables such as those provided by HashMap. 支持此方法是为了使哈希表(例如HashMap提供的哈希表)受益。

and Object.equals() Object.equals()

Unless you override these, two object are not the same, unless they are the same object, regardless of what values you set in them. 除非您覆盖这些对象,否则两个对象都不相同,除非它们是同一对象,无论您在其中设置了什么值。

For keys, you must implement both methods. 对于密钥,必须同时实现这两种方法。 For values of a map you might only implement equals(Object) or not if you don't use it. 对于地图的值,如果不使用它,则可能仅实现equals(Object)或不实现。

BTW: I suggest you read the Javadoc for all the classes in java.lang and java.util 顺便说一句:我建议您阅读java.langjava.util所有类的Javadoc

You need to implement methods equals() and hashcode() on your class Arrow . 您需要在类Arrow上实现equals()hashcode()方法。 Looking at your code, I can't make out how/where are you adding the elements to your map. 查看您的代码,我无法确定您如何/在何处将元素添加到地图中。 So I am just giving a simple example below if that helps. 因此,如果有帮助,我在下面给出一个简单的示例。 As another person mentioned, you must understand how hashmap works by reading more about it. 正如另一个人提到的那样,您必须通过阅读更多内容来了解​​hashmap的工作原理。

public class Arrow { private String elem1 = "init-value"; private int elem2 = 1001; public class Arrow { private String elem1 = "init-value"; private int elem2 = 1001; { private String elem1 = "init-value"; private int elem2 = 1001;

public Arrow(String elem1, int elem2)
{
    this.elem1 = elem1;
    this.elem2 = elem2;
}

@Override
public boolean equals(Object obj)
{
    if( ! (obj instanceof Arrow) )
    {
        return false;
    }
    Arrow obj2 = (Arrow) obj;
    // put your actual logic for object equality here
    return this.elem1.equals(obj2.elem2) && this.elem2 == obj2.elem2;
}

@Override
public int hashCode()
{
    //put some logic to calculate hashcode for this object. This is used by
    // hashmap to find index/slot for your key
    return 17 * elem1.hashCode() * elem2;
}

}

the it.remove() kept removing my keys from the HashMap. it.remove()一直从HashMap中删除我的密钥。 It works now! 现在可以使用!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM