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
广告
© . All rights reserved.