HashCode()
package com.itheima.demo02.Set;
import java.sql.SQLOutput;
/*
哈希值:是一个十进制的整数,有系统随机给出(就是对象的地址值,是一个逻辑地址,是模拟出来得到的地址,不是数据实际存储的物理地址)
在Object类有一个方法,可以获取对象的哈希值
int hashCode() 返回该对象的哈希码值
hashCode()方法的源码:
public native int hashCode();
native:代表该方法调用的是本地操作系统的方法
*/
public class Demo02HashCode extends Object{
public static void main(String[] args) {
Person1 p1 = new Person1();
int h1 = p1.hashCode();
System.out.println(h1);
Person1 p2 = new Person1();
int h2 = p2.hashCode();
System.out.println(h2);
/*
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
*/
System.out.println(p1.toString());
System.out.println(p1==p2);//false
/*
String类的哈希值
String类重写了Object类的hashCode方法
*/
String s1 = new String("abc");
String s2 = new String("abc");
System.out.println(s1.hashCode());//96354
System.out.println(s1.hashCode());//96354
System.out.println("重地".hashCode());//1179395
System.out.println("通话".hashCode());///1179395
}
}
class Person1{
//重写hashCode()
@Override
public int hashCode() {
return 1;
}
}
HashSet存储String类型
package com.itheima.demo02.Set;
import java.util.HashSet;
/*
Set集合不允许存储重复元素的原理
*/
public class Demo03HashSetSaveString {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
String s1 = new String("abc");
String s2 = new String("abc");
set.add(s1);
set.add(s2);
set.add("重地");
set.add("通话");
set.add("abc");
System.out.println(set);//[重地, 通话, abc]
}
}
HashSet存储自定义类型数据
package com.itheima.demo02.Set;
import java.util.HashSet;
/*
HashSet存储自定义类型元素
set集合保证元素唯一:
存储的元素(Person,Integer,....Student,....),必须重写hashCode()和equals()
要求:
1.同名同年龄的人,视为同一个人,只能存储一次
*/
public class Demo04HashSetSavePerson {
public static void main(String[] args) {
HashSet<Person2> set = new HashSet<>();
Person2 p1 = new Person2("zhangsan",12);
Person2 p2 = new Person2("zhangsan",12);
Person2 p3 = new Person2("lisi",14);
System.out.println(p1.equals(p2));
System.out.println(p1==p2);
set.add(p1);
set.add(p2);
set.add(p3);
System.out.println(set);
}
}
class Person2{
private String name;
private int age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person2 person2 = (Person2) o;
if (age != person2.age) return false;
return name != null ? name.equals(person2.name) : person2.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
public Person2(String name, int age) {
this.name = name;
this.age = age;
}
public Person2() {
}
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;
}
}