Cannot retrieve array from hashmap

Code: http://pastebin.com/XanGgM26

I tried to fill a hashmap with arrays but can't seem to retrieve a single array (the line in comment): I get a nullpointer exception. But retrieving all the values or keys seems to work fine. I think this line is the problem because an array isn't a primitive datatype: boolean[] result = elementMap.get(test); How can I solve this problem? Thanks.

Answers

  • edited March 2015

    Instead of making us click a link, can you post an MCVE here that demonstrates the problem?

    Also, I don't think this will work the way you want it to. Here's my own little MCVE:

    void setup(){
     int[] a = {1, 2};
     int[] b = {1, 2};
    
     println(a.equals(b));
    }
    

    Run that code and notice that it prints false.

    This is because arrays do not override the equals() method to check for anything in the array. The only time two arrays are equal is when they're the same reference:

    void setup(){
     int[] a = {1, 2};
     int[] b = a;
    
     println(a.equals(b));
    }
    

    The problem is: HashMaps rely on the equals() method. Therefore, it doesn't make a ton of sense to use arrays as keys in a map, unless you're keeping around the references for some reason.

  • edited March 2015
    /**
     * Immutable Coord (v1.03)
     * by GoToLoop (2015/Mar/05)
     * 
     * forum.processing.org/two/discussion/9692/
     * cannot-retrieve-array-from-hashmap
     */
    
    static final class Coord implements Comparable<Coord> {
      final short x, y;
      final int hash;
    
      Coord(int xx, int yy) {
        x = (short) abs(xx);
        y = (short) abs(yy);
        hash = x<<020 | y;
      }
    
      @ Override int compareTo(Coord c) {
        return hash - c.hash;
      }
    
      @ Override int hashCode() {
        return hash;
      }
    
      @ Override boolean equals(Object o) {
        return o.hashCode() == hash;
      }
    
      @ Override String toString() {
        return "[ " + x + ", " + y + " ]";
      }
    }
    
    import java.util.Map;
    
    static final int GRID = 9, CAPACITY = GRID*GRID/3 << 2;
    final Map<Coord, boolean[]> elts = new HashMap(CAPACITY);
    
    void setup() {
      for (int x = 0; x != GRID; ++x)  for (int y = 0; y != GRID; ++y)
        elts.put(new Coord(x, y), new boolean[2]);
    
      for (Coord c : elts.keySet()) {
        print(c, '\t');
        boolean[] b = elts.get(c);
        println(b[0], b[1]);
      }
    
      Coord c = new Coord(3, 5);
      boolean[] b = elts.get(c);
      println("\n" + c, b[0], b[1]);
    
      b[1] = true;
      println(c, b[0], b[1], '\n');
    
      println("Size: ", elts.size(), "\t\tCapacity: ", CAPACITY);
      exit();
    }
    
Sign In or Register to comment.