HashMap测试程序2
package com.iotek.map;
import java.util.HashMap;
import java.util.Map;
public class HashMapDemo2 {
/**
* @param args
*/
public static void main(String[] args) {
Map<Student,String> map = new HashMap<Student,String>();
//<Student,String> 來限定map中存放的鍵為Student類型,值為String類型
map.put(new Student("jay",20), "張三"); //1
map.put(new Student("lisi",30), "李四");//2
map.put(new Student("rose",20), "玫瑰");//3
map.put(new Student("lisi",30), "陳飛");//4
System.out.println(map.size());
System.out.println(map);
/*
* Student類中不重寫hashCode() and equals()方法,此處map.size()值是4,即map中有4個封裝了鍵值對的Entry對象
* 重寫了hashCode()和equals()方法后,2和4語句里的學生對象將被判斷為同一個鍵名,因此2位置處的鍵值會被替換掉
* 這正是我們需要的,對象相同,應該判定為是同一個鍵,因此,這就是需要重寫hashCode()和equals()方法的原因
*/
}
}
class Student {
private String name;
private int age;
@Override
/*
* 用source中的 Generate hashCode() and equals() 來
* 生成重寫的hashCode()方法和equals()方法
* 只要姓名和年齡相同的學生,那么這個學生對象產生的hashCode值和equals方法的值也是一樣的,
* 此時就可以認為是hashmap里放的是同一個對象,那么這兩個相同的Student對象作為鍵時,
* 后面添加的Student對象對應的鍵值應該要覆蓋掉前面添加的鍵值
* */
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true; //只有當姓名和年齡都一樣時,才返回一個true,表示是同一個對象
}
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
轉載于:https://www.cnblogs.com/enjoyjava/p/6876328.html
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的HashMap测试程序2的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php经典实例使用正则动态修改配置文件
- 下一篇: 课堂练习 5-22 团队如何做决定