今日主要学习内容
目录
关于==的深入研究
String str1 = "abc";
String str2 = "abc";
String strb1 = new StringBuilder("abc").toString();
System.out.println(str1 == str2);//true
System.out.println(str1 == strb1);// flase
String str3 = new String("abc");
System.out.println(str1 == str3);// flase
String str4 = new String("abc").intern();
System.out.println(str1 == str4);//true
String str5 = "a"+"b"+"c";
System.out.println(str1 == str5);//true
str1和str2比较结果是true,因为他们赋值时的字符串都是相等的。地址都指向常量池中的“abc"
str1和strb1比较结果是flase,因为通过查看StringBuilder中的toString()方法源码可以看到:
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
这里是new了一个新的String对象,因此地址肯定是不同的,所以结果是flase;
str1和str3比较结果是flase,原因和上一条相同
str1和str4中的比较结果是true,查看文档和源码说明;
Returns a canonical representation for the string object.
A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.
All literal strings and string-valued constant expressions are interned. String literals are defined in section 3.10.5 of the The Java™ Language Specification.
Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.
当常intern方法被调用的时候,如果常量池中已经包含了一个等于该 String 对象的字符串(由 equals(Object) 方法确定),则返回池中的字符串。(说明中标红的语句)
集合框架中的List
LinkedList
链表是一个线性表,由三个部分组成。左节点右节点和数据域。
数据域存放数据,左节点指向上一个右节点,右节点指向下一个左节点。表头的左节点是空(循环链表是指向表尾的右节点),表尾的右节点是空(循环链表是指向表头的左节点)。