我有一个 HashMap,其中 ArrayList 作为键,值作为 Integer,如何从特定键获取值。
Map< List<Object>,Integer> propositionMap=new HashMap<List<Object>,Integer>();
my key are:[Brand, ID], [Launch, ID], [Model, ID], [Brand, UserModelNoMatch], [ProducerPrice, UserModelMatch], [ProducerPrice, ID]]
my values are:[3, 5, 4, 2, 1, 6]
在我的程序中,我需要多次在不同的地方找到特定键的特定值。我不想每次都使用 for 循环来获取值。 我该怎么做?
最佳答案
抛开这是一个坏主意(如评论中所述),您不需要做任何特别的事情:
List<Object> list = new ArrayList<Object>();
// add objects to list
Map<List<Object>,Integer> propositionMap = new HashMap<List<Object>,Integer>();
propositionMap.put(list, 1);
Integer valueForList = propositionMap.get(list); // returns 1
独立构造列表时可以获得相同的值:
List<Object> list2 = new ArrayList<Object>();
// add the same objects (by equals and by hashcode) to list2 as to list
Integer valueForList = propositionMap.get(list2); // returns 1
但需要注意的是,在将列表用作 map 中的键后,不要更改列表!
list.add(new Object());
Integer valueForList = propositionMap.get(list); // likely returns null
同样,这很可能是一个坏主意。
关于java - 如何实现一个以数组列表为键的Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18077933/