fabruce
fabruce

Reputation: 21

Why a java same String has different hashcode

I have a class:

package com.test;
public class TestA {
    public static final String TEST = "饕餮ABCDEFG";

    public TestA() {
        System.out.println(TEST.hashCode());
    }
}

The same class(with no package, put it in E:, javac Test.java, get Test.class):

public class TestA {
    public static final String TEST = "饕餮ABCDEFG";

    public TestA() {
        System.out.println(TEST.hashCode());
    }
}

The Test class:

package com.test;
import java.net.URL;
import java.net.URLClassLoader;


public class Test3 {

    public static void main(String[] args) throws Exception {

        URLClassLoader loaderA = new URLClassLoader(new URL[]{new URL("file:E:/")});

        Class clazzA = loaderA.loadClass("TestA");
        clazzA.newInstance();

        TestA testA = new TestA();
    }
}

output:

250218913

1111280555

question: why this happened? i think the string "饕餮ABCDEFG" has the same address because constant pool. enter image description here

Upvotes: 1

Views: 1120

Answers (1)

Ashraff Ali Wahab
Ashraff Ali Wahab

Reputation: 1108

The program output gave the same hashcode for me.

  • 1111280555
  • 1111280555

The reason(s) why you are getting different hashcode

  1. There are some special character which you cannot see. You can identify by copying the text in hexed.it

  2. One file is stored as UTF8 and another as CP1652 or other encoding.

Upvotes: 5

Related Questions