2014-01-28 63 views
0

我想知道是否有,如果我知道一個ArryList的一部分,我可以找出另一個。我遇到的問題是我對java的有限知識。從ArrayList中選擇特定的數據

我有列表設置爲:

spotsList = new ArrayList<HashMap<String, String>>(); 

活動經歷,並與PID和名稱添加的每一個現場(從服務器)到列表中的for循環:

HashMap<String, String> map = new HashMap<String, String>(); 
        map.put(TAG_PID, id); 
        map.put(TAG_NAME, name); 
spotsList.add(map); 

如果我知道PID,現在有什麼方法可以獲得名稱?

謝謝你在前進,

泰勒

回答

1

你或許應該使用域類代替的HashMap保存該數據。如果你這樣做,你可以輕鬆地搜索一個集合的特定價值。

public class Spot { 
    private final String pid; 
    private final String name; 

    public Spot(String pid, String name) { 
     this.pid = pid; 
     this.name = name; 
    } 

    // getters 
} 

您需要添加覆蓋equals()hashCode()也。

然後使用地圖,而不是一個列表:

Map<String,Spot> spots = new HashMap<String,Spot>(); 
spots.put(pid, new Spot(pid, name)); 

然後找到一個:

Spot spot = spots.get(pid); 
+0

謝謝,但是它強調了map和hashmap指出了不正確的參數個數。另外,我將如何去添加equals()和hashcode()的覆蓋? – TylerM

+0

確保先導入它們。對於equals()和hashCode(),請查看Apache Commons的構建器:http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder。 html和http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html –

+0

先導入什麼? Equals構建器和hashcode構建器? – TylerM

3

看來你期望的PID是唯一的(給定PID,你可以找到相應的名稱)。因此,而不是地圖列表你應該只使用一個地圖:

Map<String, String> map = new HashMap<String, String>(); 
for (Spot s : spots) map.put(s.id, s.name); 

從PID檢索名稱是那麼簡單的事:

String name = map.get(pid); 
+0

感謝:d但是,當我張貼的問題,我只用名和PID簡化IT但還有6個我需要添加到其中。我會以同樣的方式去做嗎? – TylerM

+0

更具體的你的問題,你會得到最好的答案!如果所有字段都鏈接到pid,則可以創建一個包裝6個字段的類並使用「Map '來代替。 – assylias

+0

我嘗試使用下面的類,但是當我將地圖更改爲地圖時得到了錯誤,即使它說它需要更多變量。 – TylerM