hello people,

I am checking the string pool and its basic operation i.e. how it works

public class Test
{
	public static void main(String[] args)
	{
		String s1 = new String("abc");
		String s2 = "abc";
		String s3 = s2;
		
		System.out.println("Hash Table: ");
		System.out.println(s1.hashCode()+ " "+ s2.hashCode()+" "+s3.hashCode());
		
		System.out.println("== Check: ");
		System.out.println((s1==s2) + " " + (s2==s3) + " " + (s1==s3));
		
		System.out.println("equals Check: ");
		System.out.println(s1.equals(s2)+" "+s2.equals(s3)+" "+s1.equals(s3));
		
	}
}

I can't understand why s1,s2,s3 are having same hashcode although i created as strings and objects as shown. all equality and == working is fine. except that hashcode. if they are all having same hashcode how the == operator checks if they are all referring to same location

Recommended Answers

All 6 Replies

Because the hashCode is based on the Strings value not its reference.

then is there any way to print any values based on reference or creation of objects?

What are you trying to accomplish?

Edit: And no, you cannot print out the reference value (in the normal scheme of things), but trust me, the JVM has access to it.

I believe its bit different in C#. in c#, whenever i create an object, that will return new hash value. but in Java, string pool is holding same hash for variable or object which reference to it.

No, the "hash" has nothing to do with the reference value. The "hash" is calculated everytime you call the hashCode function and the calculation is based upon the Objects value not its reference.

I can't understand why s1,s2,s3 are having same hashcode although i created as strings and objects as shown

As already mentioned hashCode depends on the value of the object. Plus, when you override equals() you need to provide a logical implementation of the hashCode() method which adheres to the equals-hashcode contract.

If this were not the case, the behaviour of using Strings in any hash table based implementation would break. E.g.

public static void main(final String[] args) {
  final Set<String> set = new HashSet<String>();
  set.add(new String("HI"));
  set.add(new String("HI"));
  set.add(new String("HI"));
  System.out.println(set.size()); // how many elements does the set contain?
}

The expected count for the above code snippet is 1. If every new String instance which contains the same value returned different hash codes, the above behaviour would be violated.

This however wouldn't be a problem for collections which don't rely on hash table implementation under the hood. For e.g. if TreeSet is used instead of a HashSet in the above example, the only thing that matters would be whether the String class properly implements the Comparable interface and nothing else.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.