BiMap继承自Map,实现了常规Map的所有功能,但是它除了要求Key唯一之外,还要求Value也必须唯一。因为他维持了Key ->Value和Value -> Key的双向映射。
有这样的一个场景,户主与他所居住地址,排除土豪的情况下,这是一个双向映射。
{
BiMap<People, Address> peopleAddressBiMap = HashBiMap.create();
peopleAddressBiMap.put(new People("Tom"), new Address("beijing"));
BiMap<Address, People> addressPeopleBiMap = peopleAddressBiMap.inverse();
addressPeopleBiMap.put(new Address("shanghai"), new People("Bob"));
for (People people : peopleAddressBiMap.keySet()) {
System.out.print(people.name + "-");
}
System.out.println();
for (Address address : addressPeopleBiMap.keySet()) {
System.out.print(address.address + "-");
}
}
static class People {
String name;
public People(String name) {
this.name = name;
}
}
static class Address {
String address;
public Address(String address) {
this.address = address;
}
}
输出结果:
Tom-Bob-
beijing-shanghai-
可以看出,反转前后实际操作的是同一个BiMap,只是从不同的视角来看待而已。