1. 程式人生 > 其它 >Java常用類學習:Object類(hashCode方法)

Java常用類學習:Object類(hashCode方法)

Java常用類學習:Object類(hashCode方法)

  • hashCode方法:

    • Object hashCode()方法用於獲取物件的hash值;

       

  • 語法:

    • object.hashCode();

  • 引數:

  • 返回值:

    • 返回物件的雜湊值,是一個整數,表示在雜湊表中的位置;

  • 程式碼案例:

    public class ObjectDemo07 {
       public static void main(String[] args) {

           //Object 使用 hashCode()
           Object obj1=new Object();
           System.out.println(obj1.hashCode());//356573597

           Object obj2=new Object();
           System.out.println(obj2.hashCode());//1735600054

           Object obj3=new Object();
           System.out.println(obj3.hashCode());//21685669

      }
    }
  • 程式碼案例:

    public class ObjectDemo08 {
       public static void main(String[] args) {
           
           //String 使用 hashCode()
           String str=new String();
           System.out.println(str.hashCode());
           
           //Arraylist 使用 hashCode()
           ArrayList arr=new ArrayList();
           System.out.println(arr.hashCode());
      }
    }

     

  • 程式碼案例:2個物件相同,它們的雜湊值也相等

    public class ObjectDemo09 {
       public static void main(String[] args) {

           //Object 使用 hashCode()
           Object obj1=new Object();

           //obj1 賦值給 obj2
           Object obj2=obj1;

           //判斷2個物件是否相等
           System.out.println(obj1.equals(obj2));//true

           //獲取obj1,obj2的雜湊值
           System.out.println(obj1.hashCode());//356573597
           System.out.println(obj2.hashCode());//356573597


      }
    }