Java-集合练习题(HashSet添加机制)
- 韩顺平Java视频中的练习题,坑挺多的,mark一下;
class Person{
int id;
String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
//根据id和name属性重写了hashCode()和equals()
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return id == person.id && Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
@SuppressWarnings("all")
public class practices06 {
public static void main(String[] args) {
Set set = new HashSet();
Person p1 = new Person(1001, "AA");
Person p2 = new Person(1002, "BB");
set.add(p1);
set.add(p2);
//此时,set中有两个元素:
// 1.索引hashCode(1001, "AA")====>p1{1001, "AA"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
p1.name = "CC";
//此时,set中的两个元素为:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
set.remove(p1);
//由于remove()方法删除时,是删除set中索引为hashCode(1001, "CC")处的元素,由于该处没有元素,remove()没有删除任何元素;
System.out.println(set);
//打印set中的两个元素:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
set.add(new Person(1001, "CC"));
//此时,set中的三个元素为:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
// 3.索引hashCode(1001, "CC")====>{1001, "CC"};
System.out.println(set);
//打印set中的三个元素:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
// 3.索引hashCode(1001, "CC")====>{1001, "CC"};
set.add(new Person(1001, "AA"));
//此时,set中的四个元素为:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"} ====>{1001, "AA"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
// 3.索引hashCode(1001, "CC")====>{1001, "CC"};
System.out.println(set);
//打印set中的四个元素为:
// 1.索引hashCode(1001, "AA")====>p1{1001, "CC"} ====>{1001, "AA"};
// 2.索引hashCode(1002, "BB")====>p2{1002, "BB"};
// 3.索引hashCode(1001, "CC")====>{1001, "CC"};
}
}