java 中的哈希码
源博客地址
對(duì)哈希碼和默認(rèn)的toString()不了解,百度后總結(jié)如下:
一 哈希碼
在Java中,哈希碼代表了對(duì)象的一種特征,例如我們判斷某兩個(gè)字符串是否==,如果其哈希碼相等,則這兩個(gè)字符串是相等的。其次,哈希碼是一種數(shù)據(jù)結(jié)構(gòu)的算法。常見(jiàn)的哈希碼的算法有:
1:Object類(lèi)的hashCode.返回對(duì)象的內(nèi)存地址經(jīng)過(guò)處理后的結(jié)構(gòu),由于每個(gè)對(duì)象的內(nèi)存地址都不一樣,所以哈希碼也不一樣。
2:String類(lèi)的hashCode.根據(jù)String類(lèi)包含的字符串的內(nèi)容,根據(jù)一種特殊算法返回哈希碼,只要字符串內(nèi)容相同,返回的哈希碼也相同。
3:Integer類(lèi),返回的哈希碼就是Integer對(duì)象里所包含的那個(gè)整數(shù)的數(shù)值,例如Integer i1=new Integer(100),i1.hashCode的值就是100 。由此可見(jiàn),2個(gè)一樣大小的Integer對(duì)象,返回的哈希碼也一樣。
二 Object對(duì)象默認(rèn)的toString()
假如.直接輸出一個(gè)實(shí)例對(duì)象,出現(xiàn)一串字符串,代表什么?
直接輸出一個(gè)類(lèi)的對(duì)象的時(shí)候,會(huì)調(diào)用這個(gè)類(lèi)的toString()方法,這個(gè)方法有些類(lèi)是覆蓋了的,比如String,Integer。你自己寫(xiě)的類(lèi)沒(méi)有覆蓋這個(gè)方法的話就是繼承Object類(lèi)的這個(gè)方法,Object中toString()方法的實(shí)輸出格式是這樣的getClass().getName() + “@” + Integer.toHexString(hashCode()) 后面跟的是這個(gè)類(lèi)的哈希碼,如果你希望這個(gè)類(lèi)打印出來(lái)輸出你希望的格式,你就要覆蓋這個(gè)、toString方法。
以上部分內(nèi)容摘自:https://zhidao.baidu.com/question/556180467.html https://zhidao.baidu.com/question/179265608.html
測(cè)試:
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)//改變對(duì)象a的name值{a.name="haha";}public static void main(String[] args) { Test1 t=new Test1();Person p=t.new Person("zhangsan"); //實(shí)例一個(gè)對(duì)象pPerson a=t.new Person();//又實(shí)例一個(gè)對(duì)象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*/} }總結(jié)
以上是生活随笔為你收集整理的java 中的哈希码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SpringBoot整合定时任务和Emi
- 下一篇: 曲面之美:三星 S6 Edge+