欢迎访问 生活随笔!

生活随笔

当前位置: 首页 >

java 中的哈希码

发布时间:2024/1/1 35 豆豆
生活随笔 收集整理的这篇文章主要介绍了 java 中的哈希码 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

源博客地址
对哈希码和默认的toString()不了解,百度后总结如下:

一 哈希码

在Java中,哈希码代表了对象的一种特征,例如我们判断某两个字符串是否==,如果其哈希码相等,则这两个字符串是相等的。其次,哈希码是一种数据结构的算法。常见的哈希码的算法有:

1:Object类的hashCode.返回对象的内存地址经过处理后的结构,由于每个对象的内存地址都不一样,所以哈希码也不一样。

2:String类的hashCode.根据String类包含的字符串的内容,根据一种特殊算法返回哈希码,只要字符串内容相同,返回的哈希码也相同。
3:Integer类,返回的哈希码就是Integer对象里所包含的那个整数的数值,例如Integer i1=new Integer(100),i1.hashCode的值就是100 。由此可见,2个一样大小的Integer对象,返回的哈希码也一样。

二 Object对象默认的toString()

假如.直接输出一个实例对象,出现一串字符串,代表什么?

直接输出一个类的对象的时候,会调用这个类的toString()方法,这个方法有些类是覆盖了的,比如String,Integer。你自己写的类没有覆盖这个方法的话就是继承Object类的这个方法,Object中toString()方法的实输出格式是这样的getClass().getName() + “@” + Integer.toHexString(hashCode()) 后面跟的是这个类的哈希码,如果你希望这个类打印出来输出你希望的格式,你就要覆盖这个、toString方法。
以上部分内容摘自:https://zhidao.baidu.com/question/556180467.html https://zhidao.baidu.com/question/179265608.html

测试:

package new_start1; public class Test1 {class Person{public String name;public Person(String n){this.name=n;}public Person(){}}public static void change(Person a)//改变对象a的name值{a.name="haha";}public static void main(String[] args) { Test1 t=new Test1();Person p=t.new Person("zhangsan"); //实例一个对象pPerson a=t.new Person();//又实例一个对象aSystem.out.println("未赋值前,两者的哈希码是不相同的:");System.out.println("a.hashCode="+a.hashCode()+" "+"p.hashCode="+p.hashCode());System.out.println("a.toString()="+a.toString());System.out.println("p.toString()="+p.toString());/*未赋值前,两者的哈希码是不相同的:a.hashCode=366712642 p.hashCode=1829164700a.toString()=new_start1.Test1$Person@15db9742p.toString()=new_start1.Test1$Person@6d06d69c*/a=p; System.out.println("赋值后,两者的哈希码相同:");System.out.println("a.hashCode="+a.hashCode()+" "+"p.hashCode="+p.hashCode());System.out.println("a.toString()="+a.toString());System.out.println("p.toString()="+p.toString());/*赋值后,两者的哈希码相同:a.hashCode=1829164700 p.hashCode=1829164700a.toString()=new_start1.Test1$Person@6d06d69cp.toString()=new_start1.Test1$Person@6d06d69c*/} }

总结

以上是生活随笔为你收集整理的java 中的哈希码的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。