java - 使用映射通过 ID 检索对象

标签 java dictionary

嗨,我正在寻找通过对象 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/

相关文章:

java - 为什么没有碰撞?

java - 如何统计ArrayList中的重复元素?

java - 获取给定类文件的目录路径

java - 如果值无效,我如何提示用户重新输入他们的输入值?

arrays - VBA:字典项到字符串数组?

python - 过滤Python字典的键以查找列表中的所有项目

python - 这本字典如何获取数据?

java - 屏蔽 JTextField 中的一些字符

python - 如何在 python 中创建唯一的嵌套字典列表

python - 字典中键替换时的奇怪行为