每個鍵儲存多個值的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中文網其他相關文章!