new String(“12345”) 和 String s = “12345” 的区别
1:String strObj = new String(“12345”);
Class clazz = String.class;
String strObj = new String("12345");
Field[] fields = clazz.getDeclaredFields();
char [] obj = null;
Field hash = null;
System.out.println("before change hashcode is "+ strObj.hashCode());
// before change hashcode is 46792755
for (int i = 0; i < fields.length; i++) {
if(fields[i].getName().equals("value")) {
fields[i].setAccessible(true);
obj = (char[]) fields[i].get(strObj);
obj[0] = 'c';
}
}
System.out.println(strObj);
// c2345
System.out.println("after change new hashCode is "+strObj.hashCode());
// after change new hashCode is 46792755 与之前相同
System.out.println("12345".hashCode()); // 92968805
System.out.println("c2345".hashCode()); // 92968805
2:String strObj = “12345”;
Class clazz = String.class;
String strObj = "12345";
Field [] fields = clazz.getDeclaredFields();
char [] obj = null;
System.out.println("before change hashcode is "+ strObj.hashCode());
// before change hashcode is 46792755
for (int i = 0; i < fields.length; i++) {
if(fields[i].getName().equals("value")) {
fields[i].setAccessible(true);
obj = (char[]) fields[i].get(strObj);
obj[0] = 'c';
}
}
System.out.println(strObj);
// c2345
System.out.println("after change new hashCode is "+strObj.hashCode());
// after change new hashCode is 46792755 与之前相同
System.out.println("12345".hashCode()); // 46792755
System.out.println("c2345".hashCode()); // 92968805
上面两个main方法只有第二行代码不同,都是通过反射改变字符串的值,①main方法"12345"的hashCode()和"c2345".hashCode()相同,②main方法"12345"的hashCode()和"c2345".hashCode()不同,个人猜测是因为new String(“12345”);操作同样会将"12345"这个字符串放在常量池中,当通过反射改变了这个字符串值为"c2345","c2345"也会放在常量池中,且"c2345"的hashCode和"12345"一致。