我需要一个数组类型来存储对象。但我需要两种类型的访问属性,如下所示:
数组[0] >>> 对象1
数组[“a”] >>> object1
这意味着索引 0(整数)和索引 a(字符串)取消引用数组中的相同对象。对于存储对象,我认为我们需要集合,但我怎样才能访问我上面提到的属性?
我需要一个数组类型来存储对象。但我需要两种类型的访问属性,如下所示:
数组[0] >>> 对象1
数组[“a”] >>> object1
这意味着索引 0(整数)和索引 a(字符串)取消引用数组中的相同对象。对于存储对象,我认为我们需要集合,但我怎样才能访问我上面提到的属性?
创建从字符串键到数字键的映射:
Map<String, Integer> keyMap = new HashMap<String, Integer>();
keyMap.put("a", o);
// etc
然后创建一个对象列表,其中 MyObject 是值类型:
List<MyObject> theList = new ArrayList<MyObject>();
按整数访问:
MyObject obj = theList.get(0);
按字符串访问
MyObject obj = theList.get(keyMap.get("a"));
这需要维护您的关键数据结构,但允许从一个数据结构访问您的值。
如果您愿意,可以将其封装在一个类中:
public class IntAndStringMap<V> {
private Map<String, Integer> keyMap;
private List<V> theList;
public IntAndStringMap() {
keyMap = new HashMap<String, Integer>();
theList = new ArrayList<V>();
}
public void put(int intKey, String stringKey, V value) {
keyMap.put(stringKey, intKey);
theList.ensureCapacity(intKey + 1); // ensure no IndexOutOfBoundsException
theList.set(intKey, value);
}
public V get(int intKey) {
return theList.get(intKey);
}
public V get(String stringKey) {
return theList.get(keyMap.get(stringKey));
}
}
数组只支持indecies。
看来您可以通过索引和键来查找对象。在这种情况下,我建议你有两个系列。每种类型的查找一个。
List<MyObject> list = new ArrayList<MyObject>();
Map<String, MyObject> map = new HashMapList<MyObject>():
// array[0] >>> object1
MyObject object0 = list.get(0);
// array["a"] >>> object1
MyObject objectA = map.get("a");