是否可以有多个键指向某个值?

Is it possible to have multiple keys to a certain value?

例如,如果我想查找一个人的详细信息,可以通过提供其姓名(key1) 或姓名+姓氏(key2) 姓名,或他的phone 号码(key3)... 可以在哈希图中实现吗?

您不能直接使用散列映射来执行此操作。不过自己写也可以,实现起来也不难。

当然这是可能的(但见下文)。

import java.util.HashMap;
import java.util.Map;

public class SOPlayground {

    public static void main(String[] args) throws Exception {
        Map<String, Person> people = new HashMap<>();

        Person joe = new Person("Joe", "Doe");
        Person jane = new Person("Jane", "Smith");
        people.put(joe.getFirstName(), joe);
        people.put(joe.getLastName(), joe);
        people.put(jane.getFirstName(), jane);
        people.put(jane.getLastName(), jane);

        for (String key : new String[]{"Joe", "Doe", "Jane", "Smith"}) {
            System.out.println(people.get(key));
        }

    }

    private static class Person {

        String firstName;
        String lastName;

        public Person(String firstName, String lastName) {
            this.firstName = firstName;
            this.lastName = lastName;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        @Override
        public String toString() {
            return "Person{" + "firstName=" + firstName + ", lastName=" + lastName + '}';
        }

    }
}

输出:

Person{firstName=Joe, lastName=Doe}
Person{firstName=Joe, lastName=Doe}
Person{firstName=Jane, lastName=Smith}
Person{firstName=Jane, lastName=Smith}

但是混合键的语义是一个非常糟糕的主意。坚持一个。对所有键.

使用名字或姓氏