-2

I'm getting same hashcodes for these two objects.

CASE 1

String s=new String("ll");
String s1=new String(s);

but for case 2 I am getting different hash codes

CASE 2

String s=new String("ll");
String s1=new String("ll");

So in case 1 are two different objects geting created or only one ?

Abhishek Aryan
  • 19,936
  • 8
  • 46
  • 65
Ankit
  • 95
  • 1
  • 9
  • Case 2 should *not* have two different hash codes. You must have made a mistake. – ruakh Nov 12 '17 at 15:41
  • String is a special immutable class in java, please read: https://docs.oracle.com/javase/8/docs/api/java/lang/String.html that should clear it up. If you really want to see what it going on, debug yoru code and see instance id attached to each object. – AlexC Nov 12 '17 at 16:07

1 Answers1

2

The 'new' keyword always creates a new object. Therefore, in both cases 1 and 2, the references s and s1 denote separate objects.

Given the hashcode is based on value, in both cases, the same hashcode is getting generated for each of s and s1.

Code as below:

  // CASE 1
  String s=new String("ll");
  String s1=new String(s);
  System.out.println(s.hashCode());       //prints 3456
  System.out.println(s1.hashCode());      //prints 3456

  // CASE 2
  String ss=new String("ll");
  String ss1=new String("ll");
  System.out.println(ss.hashCode());       //prints 3456
  System.out.println(ss1.hashCode());      //also prints 3456
Saurabh
  • 23
  • 4