我已经为我的问题创建了一个简短的例子。我正在匿名创建对象列表并将它们添加到 ArrayList
。一旦项目在 ArrayList
中,我稍后返回并向列表中的每个对象添加更多信息。如果您不知道其索引,是否可以从列表中提取特定对象?
我只知道对象的“名称”,但您不能执行 list.get(ObjectName)
或任何操作。推荐的处理方法是什么?我不想每次想要检索一个特定对象时都遍历整个列表。
public class TestCode{
public static void main (String args []) {
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));
// How do I go about setting the 'index' value of SecondParty for example?
}
}
class Cave {
ArrayList<Party> parties = new ArrayList<Party>();
}
class Party extends CaveElement{
int index;
public Party(String n){
name = n;
}
// getter and setter methods
public String toString () {
return name;
}
}
class CaveElement {
String name = "";
int index = 0;
public String toString () {
return name + "" + index;
}
}
最佳答案
鉴于 List
的使用,没有办法在不遍历它的情况下“查找”一个值...
例如……
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.add(new Party("FirstParty")); // all anonymously added
cave.parties.add(new Party("SecondParty"));
cave.parties.add(new Party("ThirdParty"));
for (Party p : cave.parties) {
if (p.name.equals("SecondParty") {
p.index = ...;
break;
}
}
现在,这需要时间。如果您要查找的元素位于列表末尾,则必须迭代到列表末尾才能找到匹配项。
使用某种 map
可能会更好...
因此,如果我们将 Cave
更新为...
class Cave {
Map<String, Party> parties = new HashMap<String, Party>(25);
}
我们可以做类似...
Cave cave = new Cave();
// Loop adds several Parties to the cave's party list
cave.parties.put("FirstParty", new Party("FirstParty")); // all anonymously added
cave.parties.put("SecondParty", new Party("SecondParty"));
cave.parties.put("ThirdParty", new Party("ThirdParty"));
if (cave.parties.containsKey("SecondParty")) {
cave.parties.get("SecondParty").index = ...
}
相反...
最终,这将完全取决于您想要实现的目标...
关于java - 匿名添加对象时从 ArrayList 获取特定对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18456192/