问题描述
我为我的问题创建了一个简短的示例.我正在匿名创建对象列表并将它们添加到 ArrayList
.一旦项目在 ArrayList
中,我稍后会回来并向列表中的每个对象添加更多信息.如果您不知道其索引,有没有办法从列表中提取特定对象?
I have created a short example of my problem. I'm creating a list of objects anonymously and adding them to an ArrayList
. Once items are in the ArrayList
I later come back and add more information to each object within the list. Is there a way to extract a specific object from the list if you do not know its index?
我只知道对象的名称",但您不能执行 list.get(ObjectName)
或任何其他操作.处理此问题的推荐方法是什么?我宁愿不必每次要检索一个特定对象时都遍历整个列表.
I know only the Object's 'name' but you cannot do a list.get(ObjectName)
or anything. What is the recommended way to handle this? I'd rather not have to iterate through the entire list every time I want to retrieve one specific object.
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
,没有办法查找"一个值而不遍历它...
Given the use of List
, there's no way to "lookup" a value without iterating through it...
例如...
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;
}
}
现在,这需要时间.如果您要查找的元素位于列表的末尾,则必须遍历到列表的末尾才能找到匹配项.
Now, this will take time. If the element you are looking for is at the end of the list, you will have to iterate to the end of the list before you find a match.
最好使用某种Map
...
所以,如果我们更新 Cave
看起来像......
So, if we update Cave
to look like...
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 = ...
}
相反...
最终,这完全取决于您想要实现的目标......
Ultimately, this will all depend on what it is you want to achieve...
这篇关于匿名添加对象时,从 ArrayList 获取特定对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!