应用实例:
创建一个Student类的数组,每个Student对象由学号唯一标识。
类Student,包含字段:学号no:int;姓名name:String;
public class Main{
public static void main(String[] args) {
HashSet<Student> stuSet = new HashSet<Student>();//构造HashSet对象,构造方法中实际调用的HashMap<>();
int[] nos = new int[] {3,2,1,1};//学号单元,重复学号用于测试
//姓名单元
String[] names = new String[] {"cuizhenyu","tiangang","dingchangqing","zhangfeng"};
//创建对象,并加入到HashSet对象中
for(int i=0;i<3;i++){
int no = nos[i];
String name = names[i];
Student s = new Student(no,name);
stuSet.add(s);
/*
* HashSet 的add方法调用过程是
* HashSet中的add方法→HashMap中的put方法→(HashMap中的hash方法)HashMap中的putVal
* 为了指定对象的某个特定属性用于hash
* 需重写hashCode()方法和equals()方法
* 若比较的变量是基本类型变量,需将其转换为基本类型类对象
*/
}
for(Student s:stuSet) System.out.print(s.no+" ");//输出数据
}
class Student {
public int no;//学号
public String name;//姓名
public Student(int no, String name) {
this.no = no;
this.name = name;
}
@Override
public int hashCode() {
//重载hashCode()方法,指定的hash的属性是基本类型,需转换成对应的基本类型类的对象
Integer no = new Integer(this.no);
return no.hashCode();
}
@Override
public boolean equals(Object obj) {
//重载equals()方法,按需求指定比较的属性为学号no;
if(obj instanceof Student) {
Student s = (Student)obj;
return this.no==s.no;
}
return false;
}
}
输出
1 2 3//相同学号的对象没有重复添加
调用过程源码:
public boolean add(E e) {
return map.put(e, PRESENT)==null;
//e是添加的元素,
//PRESENT是个哑值,声明如下:
//private static final Object PRESENT = new Object();
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
java文档中对hashCode()约定中描述到只要不修改对象的equals()方法,并且两个对象是相等的,那么必须产生相同的整数(hash)。
所以要让自定义类的hash是根据指定属性产生的,就要更改equals()方法,使比较的对象是指定的那个参数。
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}