嗨,我正在寻找通过对象 ID 检索 ArrayList 对象的方法,2013 年主题中的一些人告诉你应该使用 Map 来执行此操作。但是我如何使用对象 ID 作为映射键呢?
Map<Item.getId(),Item> items = new TreeMap<>();
最佳答案
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;
P.S.此外,请确保您了解 hashCode()
和 equals()
的工作原理。
关于java - 使用映射通过 ID 检索对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54555290/