我不明白你为什么坚持使用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可以使用地图内部管理的对象:
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
}
}
如果直接使用地图,你可以使用地图的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);
}
}
对象在Java中没有名称。 – fredoverflow 2010-05-09 16:12:32