无法在迭代器(java)中引用以前使用的元素

时间:2018-11-13 06:38:58

标签: java nullpointerexception hashmap iterator

当我使用迭代器遍历条目集的元素时,我无法引用先前已被遍历的元素。这是更具体的问题:

public void adjSetter(HashMap<ArrayList<Integer>,miniSquare> mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        System.out.println("Hi~!");

        Map.Entry pair = (Map.Entry)it.next();
        ArrayList<Integer> lis=(ArrayList<Integer>)pair.getKey();
        System.out.println(lis.get(0) + "  " + lis.get(1) + "Yerr");
        miniSquare minSqua=(miniSquare)pair.getValue();
        if((minSqua.yCord!=600)){
            lis.set(1,minSqua.yCord+50);
            minSqua.topSquare=mp.get(lis);
             System.out.println("This Square is " + minSqua.xCord + "  " +minSqua.yCord + " and its top square is " + lis.get(0) + " " + lis.get(1) + " And it's actually " + minSqua.topSquare.xCord + " " + minSqua.topSquare.yCord  ); }
        if(minSqua.yCord!=250){
            lis.set(1,minSqua.yCord-50);
            minSqua.bottomSquare=mp.get(lis);
            System.out.println("This Square is " + minSqua.xCord + "  " + minSqua.yCord + " and its bottom square is " + lis.get(0) + " " + lis.get(1) + " And it's actually " + minSqua.bottomSquare.xCord + " " + minSqua.bottomSquare.yCord );
            }
        if(minSqua.xCord!=550){
            lis.set(1,minSqua.yCord);
            lis.set(0,minSqua.xCord+50);
            minSqua.rightSquare=mp.get(lis);
            System.out.println("This Square is " + minSqua.xCord + "  " + minSqua.yCord + " and its right square is " + lis.get(0) + " " + lis.get(1) + " And it's actually " + minSqua.rightSquare.xCord + " " + minSqua.rightSquare.yCord );
        lis.set(0,450); lis.set(1,450); //The error line
            System.out.println(mp.get(lis).xCord+ "Yerd");}
        if(minSqua.xCord!=200){
            lis.set(1,minSqua.yCord);
            lis.set(0,minSqua.xCord-50);
            minSqua.leftSquare=mp.get(lis);
            System.out.println("This Square is " + minSqua.xCord + "  " + minSqua.yCord + " and its left square is " + lis.get(0) + " " + lis.get(1) + " And it's actually " + minSqua.leftSquare.xCord + " " + minSqua.leftSquare.yCord );// This line throws a null pointer exception if the other problem line is deleted 
        }

    }

}

使用键(450,450)遍历元素后,该行

lis.set(0,450); lis.set(1,450);

产生一个空指针异常。任何人都可以帮助您了解如何解决此问题,甚至是真正的问题所在吗?很抱歉,如果没有足够的信息,或者代码难以阅读。

1 个答案:

答案 0 :(得分:2)

我不确定您得到NullPointerException的确切原因,但是您滥用HashMap。即使您没有遍历HashMap的条目,对Map(在您的情况下为ArrayList<Integer>)的键进行突变也会破坏HashMap ,因为它更改了hashCode()中已经存在的密钥的Map(这意味着密钥可能存储在与其新hashCode()不匹配的存储桶中)。

这可能破坏了迭代器代码并导致了NullPointerException。您不应该突变HashMap的键。如果您不遍历条目,则可以从Map中删除该条目,对键进行突变,然后将其放回Map中,但是在遍历{{ 1}}。

P.S。,而不是使用原始的MapIterator(后者需要稍后投射),请使用:

Map.Entry

Iterator<Map.Entry<ArrayList<Integer>,miniSquare>> it = mp.entrySet().iterator();

这不会解决您的异常,但这是一个好习惯。