每个键存储多个值的 HashMap
HashMap 是一种广泛使用的数据结构,用于将键映射到值。但是,它通常设计为为每个键存储单个值。此限制可能并不总是符合现实世界的要求,因为需要在同一键下存储多个值。
在 HashMap 中实现多个值的方法
如果要求每个键恰好存储两个值,可以采用多种方法考虑过:
示例实现
使用列表作为值:
// Initialize the HashMap Map<String, List<Person>> peopleByForename = new HashMap<>(); // Populate the HashMap List<Person> people = new ArrayList<>(); people.add(new Person("Bob Smith")); people.add(new Person("Bob Jones")); peopleByForename.put("Bob", people); // Retrieve values List<Person> bobs = peopleByForename.get("Bob"); Person bob1 = bobs.get(0); Person bob2 = bobs.get(1);
使用包装类:
// Define the wrapper class class Wrapper { private Person person1; private Person person2; public Wrapper(Person person1, Person person2) { this.person1 = person1; this.person2 = person2; } public Person getPerson1() { return person1; } public Person getPerson2() { return person2; } } // Initialize the HashMap Map<String, Wrapper> peopleByForename = new HashMap<>(); // Populate the HashMap peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"), new Person("Bob Jones"))); // Retrieve values Wrapper bobs = peopleByForename.get("Bob"); Person bob1 = bobs.getPerson1(); Person bob2 = bobs.getPerson2();
使用元组类:
// Initialize the HashMap Map<String, Tuple2<Person, Person>> peopleByForename = new HashMap<>(); // Populate the HashMap peopleByForename.put("Bob", new Tuple2<>(new Person("Bob Smith"), new Person("Bob Jones"))); // Retrieve values Tuple2<Person, Person> bobs = peopleByForename.get("Bob"); Person bob1 = bobs.Item1; Person bob2 = bobs.Item2;
以上是如何在 HashMap 中为每个键存储多个值?的详细内容。更多信息请关注PHP中文网其他相关文章!