Java StackTraceElement hashCode() 方法



描述

Java StackTraceElement hashCode() 方法返回此堆疊跟蹤元素的雜湊碼值。

宣告

以下是 java.lang.StackTraceElement.hashCode() 方法的宣告

public int hashCode()

引數

返回值

此方法返回此物件的雜湊碼值。

異常

示例:使用 StackTraceElement 獲取當前執行緒的雜湊碼

以下示例演示了 Java StackTraceElement hashCode() 方法的用法。在這個程式中,我們定義了一個名為 function2() 的函式,它從當前執行緒的 StackTraceElement 獲取雜湊碼。另一個名為 function1() 的函式用於例項化 StackTraceElementDemo 類並呼叫 function2() 方法。在 main 方法中,我們呼叫了 function1() 方法,並列印結果。

package com.tutorialspoint;

public class StackTraceElementDemo {

   public static void main(String[] args) {
      function1();
   }
 
   public static void function1() {
      new StackTraceElementDemo().function2();
   }
 
   public void function2() {
      int i;
      System.out.println("hash code : ");

      // print stack trace
      for(i = 1 ; i < 3 ; i++) {
         System.out.println(Thread.currentThread().getStackTrace()[i].
         hashCode());
      }
   }
}   

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

hash code : 
1520931877
1520930907

示例:使用 ArithmeticException 的 StackTraceElement 獲取雜湊碼

以下示例演示了 Java StackTraceElement hashCode() 方法的用法。在 main 方法中,我們建立了三個 int 變數,其中一個變數的值為零。在 try-catch 塊中,我們建立了一個除以零的情況以引發 ArithmeticException。在 catch 塊中,我們處理了 ArithmeticException,使用 getStackTrace() 方法從中檢索 StackTraceElement 陣列,然後在陣列的第一個元素上使用 hashCode() 方法,列印雜湊碼。

package com.tutorialspoint;

public class StackTraceElementDemo {

   public static void main(String[] args) {

      // variables to store int values
      int a = 0, b = 1, c;

      try {
         // being divide by zero, this line will throw an ArithmeticException
         c = b / a;
      }catch(ArithmeticException e) {
         // get the array of StackTraceElement
         StackTraceElement[] stackTraceElements =  e.getStackTrace();
         // print the hashcode
         System.out.println(stackTraceElements[0].hashCode());
      }
   }
}  

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

-1766072766

示例:使用 Exception 的 StackTraceElement 獲取雜湊碼

以下示例演示了 Java StackTraceElement hashCode() 方法的用法。在 main 方法中,我們建立了三個 int 變數,其中一個變數的值為零。在 try-catch 塊中,我們建立了一個除以零的情況以引發 ArithmeticException。在 catch 塊中,我們處理了 Exception,使用 getStackTrace() 方法從中檢索 StackTraceElement 陣列,然後在陣列的第一個元素上使用 hashCode() 方法,列印雜湊碼。

package com.tutorialspoint;

public class StackTraceElementDemo {

   public static void main(String[] args) {

      // variables to store int values
      int a = 0, b = 1, c;

      try {
         // being divide by zero, this line will throw an ArithmeticException
         c = b / a;
      }catch(Exception e) {
         // get the array of StackTraceElement
         StackTraceElement[] stackTraceElements =  e.getStackTrace();
         // print the hashcode
         System.out.println(stackTraceElements[0].hashCode());
      }
   }
}  

輸出

讓我們編譯並執行上面的程式,這將產生以下結果:

-1766072766
java_lang_stacktraceelement.htm
廣告