练习一:
练习二:
CollectionTest 类:
HashSet set = new HashSet();
Person p1 = new Person(1001,"AA");
Person p2 = new Person(1002,"BB");
set.add(p1);
set.add(p2);
System.out.println(set);//正常输出
p1.name = "CC";
set.remove(p1);
//更改了p1的name,但是p1的哈希值没有改变
//而remove方法中的p1是(1001,CC)的哈希值
//和原来的p1(1001,AA)的哈希值对不上,所以没有删除
System.out.println(set);
//该哈希值的位置上还没有存储元素,所以添加成功。
set.add(new Person(1001,"CC"));
System.out.println(set);
//该哈希值上的元素和要添加的元素不一样,所以添加成功。
set.add(new Person(1001,"AA"));
System.out.println(set);
Person 类:
package com.atguigu.exer1;
/**
* @author czh
* @create 2020-04-11-20:44
*/
public class Person {
int id;
String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public Person() {
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
if (id != person.id) return false;
return name != null ? name.equals(person.name) : person.name == null;
}
@Override
public int hashCode() {
int result = id;
result = 31 * result + (name != null ? name.hashCode() : 0);
return result;
}
}