Why does it generate same hash code for both strin

2020-05-05 18:43发布

问题:

I am new to Java programming, I want to create are multiple numbers of strings, for that I written the code below. Why does it generate same hash code for both string objects?

   class SingletonClass {
            public static String mystring="this"; 
        }
        public class SingletonObjectDemo {
            public static void main(String args[]) {
                String str = SingletonClass.mystring;
                String str2 = SingletonClass.mystring;
                System.out.println("String str  "+str.hashCode());
                System.out.println("String str1  "+str2.hashCode());
                    }
        }

回答1:

It's generating the same hash code for both string objects...because they're the same object.



回答2:

They reference the same object in memory, there is in essence no difference..



回答3:

You say you "want to create to multiple number of strings" but you are using something called SingletonObjectDemo. The point of a singleton is that there will only be one object, no matter how many times you "create it", so you can't create multiple objects. As Louis explains, that's why the hash code returns the same.



回答4:

This is the property of a good hashcode.

If A and B are objects such that A.equals(B), then the following property should hold.

A.hashCode().equals(B.hashCode())

You can read about hashCode and equals() here



回答5:

It seems that you are confusing objects with references to them. When you write String str = "a", str2 = "a"; you are not creating two strings, but declaring two variables which contain the exact same reference, to the string constant "a".

Furthermore, if they were two objects, as in String str = new String("a"), str2 = new String("a") then the hashCodes would still be the same because for equal objects their hashcodes must match -- that's the basic tenet of a hashcode.

BUT, if you, say, wrote Object o = new Object(), o2 = new Object(), now the hashcodes are different because no two instances of Object are equal (that's by definition, not by some inescapable logic).