哈希码以及Object.toString()简单理解

对哈希码和默认的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

测试:
---------------------
作者:勤勤勤能补拙
来源:CSDN
原文:https://blog.csdn.net/zark721/article/details/70254548
版权声明:本文为博主原创文章,转载请附上博文链接!

 1 package new_start1;
 2 public class Test1 {
 3     class Person
 4     {
 5         public String name;
 6         public Person(String n)
 7         {
 8             this.name=n;
 9         }
10         public Person(){}
11     }
12     public static void change(Person a)//改变对象a的name值
13     {
14         a.name="haha";
15     }
16     public static void main(String[] args) {    
17         Test1 t=new Test1();
18         Person p=t.new Person("zhangsan"); //实例一个对象p
19         Person a=t.new Person();//又实例一个对象a
20         System.out.println("未赋值前,两者的哈希码是不相同的:");
21         System.out.println("a.hashCode="+a.hashCode()+"  "+"p.hashCode="+p.hashCode());
22         System.out.println("a.toString()="+a.toString());
23         System.out.println("p.toString()="+p.toString());
24         /*
25             未赋值前,两者的哈希码是不相同的:
26             a.hashCode=366712642  p.hashCode=1829164700
27             a.toString()=new_start1.Test1$Person@15db9742
28             p.toString()=new_start1.Test1$Person@6d06d69c
29          */
30         a=p; 
31         System.out.println("赋值后,两者的哈希码相同:");
32         System.out.println("a.hashCode="+a.hashCode()+"  "+"p.hashCode="+p.hashCode());
33         System.out.println("a.toString()="+a.toString());
34         System.out.println("p.toString()="+p.toString());
35         /*
36              赋值后,两者的哈希码相同:
37             a.hashCode=1829164700  p.hashCode=1829164700
38             a.toString()=new_start1.Test1$Person@6d06d69c
39             p.toString()=new_start1.Test1$Person@6d06d69c
40          */
41     }
42 }

 

posted on 2019-06-01 16:47  mike_JP  阅读(568)  评论(0编辑  收藏  举报

导航