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
有没有不理解的地方?其实这里有一个JVM 的把戏,在 JVM 眼里,这个String two = "l"+"h"+"w",其实就是String three= "lhw"。
我们来看几个String的方法。
第一部分是构造函数:
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;
}