HashMap
public class MainTest {
public static void main(String[] args) {
//使用已经重写了hashCode和equals的String作为key
HashMap<String,Person>map=new HashMap<>();
map.put("北京",new Person("张三",18));
map.put("上海",new Person("李四",19));
map.put("广州",new Person("王五",20));
//测试赵六替换张三
map.put("北京",new Person("赵六",18));
Set<String> set = map.keySet();
//遍历
for (String key : set) {
Person value=map.get(key);
System.out.println(key+"->"+value);
}
}
//使Person作为key
@Test
public void Test(){
HashMap<Person,String> map=new HashMap<>();
map.put(new Person("女王",18),"英国");
map.put(new Person("秦始皇",30),"秦国");
map.put(new Person("普京",18),"俄罗斯");
//测试相同key
map.put(new Person("女王",18),"毛里求斯");
Set<Map.Entry<Person, String>> entries = map.entrySet();
for (Map.Entry<Person, String> entry : entries) {
System.out.println(entry);
}
}
LinkedHashMap