来自String 类的实习方法的javaDocs :
当调用 intern 方法时,如果池中已经包含一个等于该 String 对象的字符串,由 equals(Object) 方法确定,则返回池中的字符串。否则,将此 String 对象添加到池中并返回对该 String 对象的引用。
考虑以下用例:
String first = "Hello";
String second = "Hello";
System.out.println(first == second);
String third = new String("Hello");
String fourth = new String("Hello");
System.out.println(third == fourth);
System.out.println(third == fourth.intern());
System.out.println(third.intern() == fourth);
System.out.println(third == fourth);
System.out.println(third.intern() == fourth.intern());
System.out.println(third.intern() == first);
String fifth = new String(new char[]{'H','e','l', 'l', 'o'});
String sixth = new String(new char[]{'H','e','l', 'l', 'o'});
System.out.println(fifth == fifth.intern());
System.out.println(sixth == sixth.intern());
String seven = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
String eight = new String(new char[]{'H','e','l', 'l', 'o' , '2'});
System.out.println(seven == seven.intern());
System.out.println(eight == eight.intern());
有人可以解释为什么seven == seven.intern()
是真的,而以下是假的:
System.out.println(fifth == fifth.intern());
System.out.println(sixth == sixth.intern());
System.out.println(eight == eight.intern());