StackTraceElement Array's hashcode returns different value each time

Pankaj Singhal :
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);
}

The above program returns the following output:

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

Can someone please explain why does StackTraceElement[]'s hashcode (the last 8 chars of the toString()'s output) return different each time, since the array is not getting changed?

The same is not getting changed for String[].

Hovercraft Full Of Eels :

It creates a new array each time. E.G.

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"});
    }
} 

While the contents of the array are unchanged, a new array object is created, and that's what matters to the array hashCode() method.

Try this instead to see that the underlying array items are unchanged:

    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()));
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=146287&siteId=1