我们是否可以用一个键和两个值实现HashMap。就像HashMap一样?
还请告诉我(如果没有办法)通过其他任何方法来实现三个值的存储(以一个为键)的方法,对我有帮助吗?
你可以:
Map<KeyType, List<ValueType>>。
Map<KeyType, WrapperType>
Map<KeyType, Tuple<Value1Type, Value2Type>>
// create our map Map<String, List<Person>> peopleByForename = new HashMap<>(); // populate it List<Person> people = new ArrayList<>(); people.add(new Person("Bob Smith")); people.add(new Person("Bob Jones")); peopleByForename.put("Bob", people); // read from it List<Person> bobs = peopleByForename["Bob"]; Person bob1 = bobs[0]; Person bob2 = bobs[1];
这种方法的缺点是列表未完全绑定到两个值。
2.使用包装器类
// define our wrapper class Wrapper { public Wrapper(Person person1, Person person2) { this.person1 = person1; this.person2 = person2; } public Person getPerson1 { return this.person1; } public Person getPerson2 { return this.person2; } private Person person1; private Person person2; } // create our map Map<String, Wrapper> peopleByForename = new HashMap<>(); // populate it Wrapper people = new Wrapper(); peopleByForename.put("Bob", new Wrapper(new Person("Bob Smith"), new Person("Bob Jones")); // read from it Wrapper bobs = peopleByForename.get("Bob"); Person bob1 = bobs.getPerson1; Person bob2 = bobs.getPerson2;
这种方法的缺点是,你必须为所有这些非常简单的容器类编写很多样板代码。
3.使用元组
// you'll have to write or download a Tuple class in Java, (.NET ships with one) // create our map Map<String, Tuple2<Person, Person> peopleByForename = new HashMap<>(); // populate it peopleByForename.put("Bob", new Tuple2(new Person("Bob Smith", new Person("Bob Jones")); // read from it Tuple<Person, Person> bobs = peopleByForename["Bob"]; Person bob1 = bobs.Item1; Person bob2 = bobs.Item2;
我认为这是最好的解决方案。
4.多个地图
// create our maps Map<String, Person> firstPersonByForename = new HashMap<>(); Map<String, Person> secondPersonByForename = new HashMap<>(); // populate them firstPersonByForename.put("Bob", new Person("Bob Smith")); secondPersonByForename.put("Bob", new Person("Bob Jones")); // read from them Person bob1 = firstPersonByForename["Bob"]; Person bob2 = secondPersonByForename["Bob"];
此解决方案的缺点是,两个映射之间的关联并不明显,程序错误可能会导致两个映射不同步。