【发布时间】:2013-11-08 20:59:27
【问题描述】:
我有一个Person 类:
public class Person{
private String name;
//pleaese think this 'id' simply as an attribute of Person, same as e.g. age, height
private long id;
public Person(String name, long id){
this.name = name;
this.id = id;
}
public String getName(){
return name;
}
public long getId(){
return id;
}
}
然后,我有一个 HashMap 实例,其中包含从服务器获取的多个 Persons:
//key is String type, it is a unique name-like string assigned to each Person
//value is a Person object.
HashMap<String, Person> personsMap = GET_PERSONS_FROM_SERVER();
然后,我有一个人员 ID 数组:
long[] ids = new long[]{1,2,3,4,5, …}
我需要生成另一个 HashMap,它只包含id列在ids数组中的人:
// Only the person whose id is listed in ids array will be in the following Map
Map<String, Person> personNeeded = … ;
如何以高效的方式获取personNeeded?
【问题讨论】:
-
您使用什么作为地图键?你能把 ID 设为地图键吗?
-
NO,ID 是 ID,键是分配给 Person 的另一个唯一名称
-
返回一个id不是key的map很奇怪
-
Oskar,id 只是一个属性,不要认为它是 DB 中的 id,它可以是任何东西,例如年龄、身高……它实际上只是 Person 的一个属性。这样想也不奇怪。
-
取决于... GET_PERSONS_FROM_SERVER() 中是否有任何范围仅返回与您的数组匹配的 ID?否则,打开一个循环,我的朋友!