2014-09-04 54 views
0

我想要做這樣的如何使用獲得2項或HashMap的設定值或ArrayList的

object.set(lineIndex, wordIndex, value); 

一些東西,這對找回

value=object.get(lineIndex,wordIndex); 

但ArrayList和HashMap中沒有支持2鍵值
任何想法!
感謝

+0

什麼是你真正想實現什麼?你的用例是什麼? – 2014-09-04 01:22:11

回答

1

創建存儲既要使用的按鍵的一類,並用它作爲鑰匙插入Map。它會有一些開銷,但是應該使用比嵌套的內存少的內存。

例子:

class IndexKey{ 
    public final int lineIndex; 
    public final int wordIndex; 
    public IndexKey(int lineIndex, int keyIndex){ 
     this.lineIndex = lineIndex; 
     this.wordIndex = wordIndex; 
    } 

    @Override 
    public int hashCode() { 
     int hash = 7; 
     hash = 97 * hash + lineIndex; 
     hash = 97 * hash + wordIndex; 
     return hash 
    } 

    @Override 
    public boolean equals(Object obj) { 
     if (obj == null) { 
      return false; 
     } 
     if (getClass() != obj.getClass()) { 
      return false; 
     } 
     final IndexKey other = (IndexKey) obj; 
     if (this.lineIndex != other.lineIndex) { 
      return false; 
     } 
     if (this.wordIndex != other.wordIndex) { 
      return false; 
     } 
     return true; 
    } 
} 

Map<IndexKey, Object> map = new HashMap<>(); 

object.set(new IndexKey(lineIndex, keyIndex), value); 
value=object.get(new IndexKey(lineIndex, wordIndex)); 
+0

謝謝我試過這種方式,但「價值」返回空--------地圖地圖=新的HashMap <>(); (新的IndexKey(0,1),「Mahmoud」); \t \t String value = map.get(new IndexKey(0,1)); – JustMe 2014-09-04 01:40:08

+0

@JustMe你重寫了'IndexKey'的'equals'和'hashCode'方法嗎? – resueman 2014-09-04 01:51:12

+0

如何做到這一點,請解釋,並請編輯此答案 – JustMe 2014-09-04 01:53:08

1

嘗試嵌套的地圖是這樣的:

//For a map: 
HashMap<Integer, HashMap<Integer, String>> map; 

//Usage example: 
System.out.println(map.get(0).get(0)); 
+0

謝謝,但是這樣對性能或設備RAM有影響嗎? – JustMe 2014-09-04 01:27:37

+0

我很確定它不會導致任何重大性能問題,但我並不完全確定。 – Pokechu22 2014-09-04 01:30:05

+0

也許您需要切換密鑰和值,與OP要求的密鑰(密鑰是兩種類型的組合)完全相同。 – mrmoment 2014-09-04 01:51:59

相關問題