String原始碼解析二
阿新 • • 發佈:2018-12-26
一.intern方法
1.定義
/** * Returns a canonical representation for the string object. * <p> * A pool of strings, initially empty, is maintained privately by the * class <code>String</code>. * <p> * When the intern method is invoked, if the pool already contains a * string equal to this <code>String</code> object as determined by * the {@link #equals(Object)} method, then the string from the pool is * returned. Otherwise, this <code>String</code> object is added to the * pool and a reference to this <code>String</code> object is returned. * <p> * It follows that for any two strings <code>s</code> and <code>t</code>, * <code>s.intern() == t.intern()</code> is <code>true</code> * if and only if <code>s.equals(t)</code> is <code>true</code>. * <p> * All literal strings and string-valued constant expressions are * interned. String literals are defined in section 3.10.5 of the * <cite>The Java™ Language Specification</cite>. * * @return a string that has the same contents as this string, but is * guaranteed to be from a pool of unique strings. */ public native String intern();
根據原始碼的解釋,該方法返回常量池中對應的字串,若常量池中存在該字串,直接返回該物件引用,若不存在,將該字串物件加入常量池然後再返回其引用。
注意: 字串常量在jdk1.7之前存在方法區,jdk1.7之後移到了堆中。
2.應用
見部落格https://www.cnblogs.com/Kidezyq/p/8040338.html
二.String中面試涉及到的問題
1.JDK 6和JDK 7中substring的原理及區別
https://blog.csdn.net/renfufei/article/details/14058047
2.String對“+”的過載
https://blog.csdn.net/codejas/article/details/78662146