2015-12-08 28 views
-1

我有類HashMap的定製類類型的關鍵

public class server_run{ 
    class constatnt_Cells{ 
      private int x; 
      private int y; 
      public constatnt_Cells(int fx , int fy) { 
       x = fx; 
       y = fy; 
      } 
     } 
    private static Map <constatnt_Cells,Integer> test = new HashMap<constatnt_Cells,Integer>(); 
} 

我想創建Integerhashmapconstatnt_Cells關鍵和價值,但現在的問題是靜態部分dose't工作在這種情況下 我解釋我的問題用一個例子

constatnt_Cells goldCell = new constatnt_Cells(2,6); 
    System.out.println(test.get(goldCell)); 
    test.put(goldCell, 50); 

該代碼總是打印,但如果我改變的hashmap鍵的類型,例如我nteger

System.out.println(test.get(10)); 
test.put(10, 50); 

它只能打印一次之後,它總是打印那麼究竟是什麼constatnt_Cells類,並在這種情況下Integer類之間的差別。
我所有的代碼是在server_run類,並像它的名稱服務器運行這個類中的每個第二

+1

預計爲什麼你在put()之前使用'get()'? – Codebender

+0

,因爲我想看看我的靜態哈希映射是否工作,如果它只是在第一秒工作,它打印空和其他時間應該打印50 –

+3

你需要重寫equals和hashcode方法。除非你這樣做,否則首先創建的所有實例都應該是不同的。 – SacJn

回答

-1

由於註釋部分不能發佈這麼多的代碼,我張貼在這裏的答案。 以下是HashMap.get的源代碼(○:Obejct)函數在Java 8:

public V get(Object key) { 
    if (key == null) 
     return getForNullKey(); 
    Entry<K,V> entry = getEntry(key); 

    return null == entry ? null : entry.getValue(); 
} 

而且

final Entry<K,V> getEntry(Object key) { 
    if (size == 0) { 
     return null; 
    } 

    int hash = (key == null) ? 0 : hash(key); 
    for (Entry<K,V> e = table[indexFor(hash, table.length)]; 
     e != null; 
     e = e.next) { 
     Object k; 
     if (e.hash == hash && 
      ((k = e.key) == key || (key != null && key.equals(k)))) 
      return e; 
    } 
    return null; 
} 

你可以看到,當你想從一個HashMap獲取一個對象它將首先計算key的哈希碼,並在內部哈希表中找到具有相同哈希碼的條目。然後,方法將通過測試來測試密鑰和key of the entry in hash table是否爲等於,如果它們通過==運算符指向相同的引用,或者它們通過調用類覆蓋的equals方法相等來測試。

以下是hash方法

final int hash(Object k) { 
    int h = hashSeed; 
    if (0 != h && k instanceof String) { 
     return sun.misc.Hashing.stringHash32((String) k); 
    } 

    h ^= k.hashCode(); 

    // This function ensures that hashCodes that differ only by 
    // constant multiples at each bit position have a bounded 
    // number of collisions (approximately 8 at default load factor). 
    h ^= (h >>> 20)^(h >>> 12); 
    return h^(h >>> 7)^(h >>> 4); 
} 

因此,懇求給予足夠的重視您的hashcodeequals功能,你上課的時候,你希望你的情況下工作,與HashMap

+0

平等應該如何檢查?你知道key.equals(k)如何在這裏工作嗎?' – SacJn

+0

@SacJn正如我在我的文章中所說的那樣,如果你重載equals方法或者它會調用equals方法,將會調用equals方法。方法在類的對象,默認情況下只是測試引用的'==' – VicX

+0

但時間的問題是不應該重寫equals和hashcode?你寫的東西對OP的問題是沒有意義的。 – SacJn