有勇气的牛排博客

java学习笔记 集合 --- Set 哈希值

有勇气的牛排 1141 Java 2021-08-20 00:14:44

1 Set哈希值

哈希值:是JDK根据对象的地址或者字符串或者数字算出来的int类型的数值

Object类中有一个方法可以获取对象哈希值

(1)public int hashCode:返回对象的哈希码值

特点

(1)同一个对象多次调用hashCode()方法返回的哈希值时相同的

(2)默认情况下,不同对象的哈希值时不同的,而重写hashCode()方法,可以实现让不同对象的哈希值相同

package Hash; public class HashDemo { public static void main(String[] args) { // 创建学生对象 Student s1 = new Student("灰太狼", 20); // 同一个对象多次调用 hashCode() 方法的哈希值时相同的 System.out.println(s1.hashCode()); // 460141958 System.out.println(s1.hashCode()); // 460141958 System.out.println("--------"); Student s2 = new Student("灰太狼", 20); // 默认情况下,不同对象的哈希值时不同的 // 通过方法重写,可以实现不同对象的哈希值是相同的 System.out.println(s2.hashCode()); // 1163157884 System.out.println("--------"); System.out.println("hello".hashCode()); // 99162322 System.out.println("world".hashCode()); // 113318802 System.out.println("java".hashCode()); // 3254818 System.out.println("--------"); // 这里有些版本是 不同汉字 相同哈希 System.out.println("牛排".hashCode()); // 933015 System.out.println("勇气".hashCode()); // 684589 } }

参考地址
https://www.bilibili.com/video/BV18J411W7cE?p=239


留言

专栏
文章
加入群聊