使用地图按ID检索对象

时间:2019-02-06 13:55:53

标签: java dictionary

嗨,我在寻找一种通过对象ID检索ArrayList对象的方法,2013年的某个话题告诉您应该使用Map来执行此操作。但是,如何使用对象ID作为Map键?

   Map<Item.getId(),Item> items = new TreeMap<>();

1 个答案:

答案 0 :(得分:1)

class Item {
    // id could be any type you like. Mostly this is simple types: int, long, String, UUID
    private final int id;
    // ... other fields
}

Map<Integer, Item> map = new HashMap<>();
map.put(666, new Item(666));
Item item = map.get(666);  // get an item with id=666;

PS 。此外,请确保您了解hashCode()equals()的工作方式。