【问题标题】:StackTraceElement Array's hashcode returns different value each timeStackTraceElement Array 的 hashcode 每次返回不同的值
【发布时间】:2019-06-27 16:24:06
【问题描述】:
public static void main(String[] args) {
    try{
        throw new RuntimeException();
    }
    catch (Exception e){
        System.out.println(e.getStackTrace());
        System.out.println(e.getStackTrace());
        System.out.println(e.getStackTrace());
    }
    String[] sArray = new String[]{"a","b"};
    System.out.println(sArray);
    System.out.println(sArray);
    System.out.println(sArray);
}

上述程序返回以下输出:

[Ljava.lang.StackTraceElement;@50040f0c
[Ljava.lang.StackTraceElement;@2dda6444
[Ljava.lang.StackTraceElement;@5e9f23b4
[Ljava.lang.String;@4783da3f
[Ljava.lang.String;@4783da3f
[Ljava.lang.String;@4783da3f

有人能解释一下为什么StackTraceElement[] 的哈希码(toString() 输出的最后 8 个字符)每次返回都不同,因为数组没有改变吗?

String[] 没有改变。

【问题讨论】:

  • 你为什么认为数组没有改变? getStackTrace() 返回堆栈跟踪数组的 clone,因此您不能弄乱存储在异常中的数组,这意味着对 getStackTrace() 的每次调用都会返回不同的数组,因此哈希码不同。
  • 返回一个新数组是面向对象编程中的一种标准做法,称为防御性复制。

标签: java arrays hashcode


【解决方案1】:

它每次都会创建一个新数组。例如

public class TestClass{    
    public static void main(String[] args) {
        try{
            throw new RuntimeException();
        }
        catch (Exception e){
            System.out.println(e.getStackTrace());
            System.out.println(e.getStackTrace());
            System.out.println(e.getStackTrace());
        }


        System.out.println(new String[]{"a","b"});
        System.out.println(new String[]{"a","b"});
        System.out.println(new String[]{"a","b"});
    }
} 

虽然数组的内容不变,但会创建一个新数组object,这对数组hashCode() 方法很重要。

试试这个,看看底层数组项没有改变:

    try{
        throw new RuntimeException();
    }
    catch (Exception e){
        System.out.println(Arrays.hashCode(e.getStackTrace()));
        System.out.println(Arrays.hashCode(e.getStackTrace()));
        System.out.println(Arrays.hashCode(e.getStackTrace()));
    }

【讨论】:

    猜你喜欢
    • 2016-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多