具体源码实现
package com.runoob.test; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class HashSetTest { public static void main(String[] args) { // TODO Auto-generated method stub /* * 练习:往HashSet中存储学生对象(姓名,年龄) 同姓名,同年龄视为一个人,不存 * 1.描述学生 * 2.定义容器 * 3.将学生对象存储到容器中 * * * 发现存储了同姓名童年里的学生是可以的 * 原因是每一次存储学生对象时,都先调用hashCode方法获取哈希值 * 但是调用的是Object类中的hashCode,所以不同的对象,哈希值也不同 * 这就是同姓名同年龄存入的原因 * * 解决: * 需要根据学生对象自身的特点来定义哈希值 * 所以就需要覆盖hashCode方法 */ //1.创建容器对象 Set set = new HashSet(); //2.存储学生对象 set.add(new Student("xiaoqiang",21)); set.add(new Student("wangcai",27)); set.add(new Student("xiaoming",22)); set.add(new Student("xiaoqi",23)); set.add(new Student("xiaoming",22)); set.add(new Student("xiaoqi",23)); //3.获取所有学生 for (Iterator it = set.iterator(); it.hasNext();) { Student stu = (Student) it.next(); System.out.println(stu.getName()+"::"+stu.getAge()); } } }
=============================================================================================================================================================================================
package com.runoob.test; class Student { private String name; private int age; public Student() { super(); // TODO Auto-generated constructor stub } 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; } @Override public String toString() { return "Student [name=" + name + ", age=" + age + "]"; } /*shift+alt+s 快捷键出来的 * *(non-Javadoc) * @see java.lang.Object#hashCode() @Override 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; }*/ //哈希值冲突了 需要判断内容 equlas 自己写的 //自定义重写hashCode 和equals 方法 public int hashCode(){ final int NUMBER=37; return name.hashCode()+age*NUMBER; } public boolean equals(Object obj){ //System.out.println(this+"vs"+obj); if(this==obj){ return true; } if(!(obj instanceof Student)){ throw new ClassCastException("类型错误"); } Student stu =(Student)obj; return this.name.equals(stu.name)&&this.age==stu.age; } }
时间: 2024-10-23 00:36:05