2013-07-10 129 views
1

初學者問題:我有一個散列表,它將整數數組存儲爲值。每個值的關鍵是一個由兩個整數(座標)組成的對象。Java Hashmap從對象鍵獲取值

我的問題:我如何根據我的對象中的兩個座標(我的'鍵')從哈希映射中檢索一個值?

我COORDS類(從Eclipse的一點幫助):

public class Coords { 
    int x; 
    int y; 

    public Coords(int x, int y) { 
     super(); 
     this.x = x; 
     this.y = y; 
    } 

    @Override 
    public int hashCode() { 
     final int prime = 31; 
     int result = 1; 
     result = prime * result + x; 
     result = prime * result + y; 
     return result; 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (this == obj) 
      return true; 
     if (obj == null) 
      return false; 
     if (getClass() != obj.getClass()) 
      return false; 
     Coords other = (Coords) obj; 
     if (x != other.x) 
      return false; 
     if (y != other.y) 
      return false; 
     return true; 
    } 

} 

建設的Hashmap:

public class BuildMap { 

public Coords coords; 
public int[] someData = new int[4]; 
public Random random = new Random(); 
HashMap<Coords, int[]> map = new HashMap<Coords, int[]>(); 

public void buildHashMap() { 

    // coordinates from (0,0) to (31,31) 
    for (int i = 0; i < 32; i++) { 
     for (int j = 0; j < 32; j++) { 

      coords = new Coords(i, j); 

      // Every Coord gets a few random numbers 
      for (int k = 0; k < 4; k++) { 
       someData[k] = random.nextInt(8564); 
      } 

      map.put(coords, someData); 

     } 
    } 

如果我要訪問上的座標12,13數組,我怎麼能檢索它?是否需要迭代(我希望不需要,我想添加10萬個座標並快速訪問課程)。

我希望這將在

int[] theValues = map.get(new Coords(12,13)); 

行有些工作,我希望你能幫助我。提前致謝!

+0

你在問題中發佈了答案:'int [] theValues = map.get(new Coords(12,13));''它是如何工作的。 – jlordo

+2

你爲什麼認爲你的get不起作用? – Ayman

+0

你已經正確地覆蓋了你的'Coords'類中的'equals'方法,所以你的'map.get'調用應該按照你想要的那樣工作 –

回答

3

問題在於如何構建地圖。

您正在爲每個元素的值添加相同的數組。

您需要爲每個元素實例化一個新數組。

for (int i = 0; i < 32; i++) { 
    for (int j = 0; j < 32; j++) { 

     coords = new Coords(i, j); 
     int[] someData = new int[4]; // <==== create a new array for each Map value 
     // Every Coord gets a few random numbers 
     for (int k = 0; k < 4; k++) { 
      someData[k] = random.nextInt(8564); 
     } 

     map.put(coords, someData); 

    } 
+0

謝謝大家,特別是Jim!這樣做的竅門......仍然學習:-) – user2150129

1

你有一個錯誤:你只使用一個數組,並且引用了很多。

移動這一行

public int[] someData = new int[4]; // without public 

上面或下面這行:

coords = new Coords(i, j); 

解決它。

+0

感謝您的回答,你真的幫我在這裏 – user2150129