嗨,我在寻找一种通过对象ID检索ArrayList对象的方法,2013年的某个话题告诉您应该使用Map来执行此操作。但是,如何使用对象ID作为Map键?
Map<Item.getId(),Item> items = new TreeMap<>();
答案 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()
的工作方式。