String 类是final类,不可以继承。String类实现了CharSequence接口,我们看一下CharSequence的部分代码
public interface CharSequence
{
//the number of char in this sequence
int length();
// return the char value at the specified index
char charAt(int index);
// return a new CharSequence that is a subsequence of this sequence.
CharSequence subSequence(int start, int end);
//a string consisting of exactly this sequence of characters
public String toString();
}
public final class String{
// used for character storage
private final char value[];
// cache the hash code for the string
private int hash;
}
public class Test {
public static void main(String[] args) {
String one = "lhw";
String two = "l"+"h"+"w";
String three= "lhw";
String four = new String("lhw");
System.out.println(one==two);
System.out.println(one==three);
System.out.println(one==four);
}
}
输出:
true
true
false
public String() {
this.value = "".value;
}
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
这里如果不理解,我们看一下Arrays.copyOf的源码:
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
我们看一下length()方法,明显就是直接返回数组的length属性了。
public int length() {
return value.length;
}