String类的HashCode
package demo3;
/*
* 对象的哈希值,普通的十进制整数
* 父类Object,方法public int hashCode()计算int整数
*/
public class HashDemo {
public static void main(String[] args) {
Person p = new Person();
int i = p.hashCode();
System.out.println(i);
String s1 = new String("abc");
String s2 = new String("abc");
// h = 31 * h + val[i];
System.out.println(s1.hashCode());//96354(31*0+97=97,31*97+98=3105,31*3105+99=31354)
System.out.println(s2.hashCode());//96354
String s3="abc";
String s4="abc";
String s5="abd";
String s6 = "ccc";
System.out.println(s3.hashCode());//96354
System.out.println(s4.hashCode());//96354
System.out.println(s5.hashCode());//96355
System.out.println(s6.hashCode());//98307(31*0+99=99,31*99+99=3168,31*3168+99=98307)
//String 的hashCode()源码
/*public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}*/
}
}
哈希表的实现
HashSet存储过程
HashSet存储String类型
public static void function() {
HashSet<String> set = new HashSet<String>();
set.add(new String("abc"));
set.add(new String("abc"));
set.add(new String("bbc"));
set.add(new String("bbc"));
set.add(null);
set.add(null);
System.out.println(set);//[null, bbc, abc]
}
HashSet存储自定义对象,并重写HashCode和equals方法
package demo3;
import java.util.HashSet;
/*
* HashSet集合的自身特点:
* 底层数据结构,哈希表
* 存储,取出都比较快
* 线程不安全,运行速度
*
* 哈希表(链表数组结合体)
*
*/
public class HashSetDemo1 {
public static void main(String[] args) {
// function();
function1();
}
//存储String类型
public static void function() {
HashSet<String> set = new HashSet<String>();
set.add(new String("abc"));
set.add(new String("abc"));
set.add(new String("bbc"));
set.add(new String("bbc"));
set.add(null);
set.add(null);
System.out.println(set);//[null, bbc, abc]
}
//存储自定义Person类型(由于是new出来的所以不是同一个对象,所以变成了可以存储重复了)
public static void function1() {
HashSet<Person> setPerson = new HashSet<Person>();
setPerson.add(new Person("a",20));
setPerson.add(new Person("b",10));
setPerson.add(new Person("b",10));
setPerson.add(new Person("c",15));
setPerson.add(new Person("d",19));
setPerson.add(new Person("e",17));
System.out.println(setPerson);
}
}
重写HashCode和equals方法
@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;
Person other = (Person) 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;
}