我不明白您为什么坚持与List 合作,因为您正在寻找的似乎是Map。地图中的条目是命名对象,例如它有一个用于在地图中查找条目的键。
Map<String,SomeObject> map = new HashMap<String,SomeObject>();
map.put("A",new SomeObject());
map.put("B",new SomeObject());
如果您的对象有名称或需要知道它们的名称,那么该对象应该将名称作为属性。使用变量名或映射键进行对象识别是不好的。
Map<String,SomeObject> map = new HashMap<String,SomeObject>();
map.put("A",new SomeObject("A"));
map.put("B",new SomeObject("B"));
但是,这是重复的,您可能希望通过引入新类将其重构为更具表现力的设计:
SomeObjects objects = new SomeObjects();
SomeObject objectA = objects.create("A");
SomeObject objectB = objects.create("B");
// The container can manage references if you like to
SomeObject objectA = objects.get("A");
SomeObjects 可能在内部使用 Map 来管理对象:
class SomeObjects {
Map<String,SomeObject> objects = ...;
public SomeObject create(String name) {
SomeObject newObject = new SomeObject(name);
objects.put(name,newObject);
return newObject;
}
public SomeObject get(String name) {
return objects.get(name);
}
}
要迭代对象名称或对象,容器可以简单地为映射的键或映射的值提供迭代器:
public class SomeObjects {
Map<String,SomeObject> objects = ...;
public Iterator<SomeObject> objects() {
return objects.values().iterator();
}
public Iterator<String> names() {
return objects.keySet().iterator();
}
}
要使用这些迭代器,您可以:
public void test() {
SomeObjects objects = ...;
for(SomeObject obj : objects.objects()) {
// Do something with the object
}
for(String objName : objects.names()) {
// Do something with the object name
}
}
如果直接使用Map,可以使用Map的Entry类,是键值对:
public void test() {
Map<String,SomeObject> objects = new HashMap<String,SomeObject>();
objects.put("A",new SomeObject());
for(Entry entry : objects.entrySet()) {
System.out.printlnt("Processing object with name: " + entry.getKey());
SomeObject obj = entry.getValue();
doSomethingWith(obj);
}
}