2014-01-28 62 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