Java中的字符串有,String,StringBuilder,StringBuffer
1,String
类的实现关系
源码
由源码可以看出String分别实现了java.io.Serializable, Comparable<String>, CharSequence实现了三个接口,并且类和维护的底层数据char value[]均由关键字final修饰,即,类不能被继承,实例化后不能被修改。
2,StringBuilder
类实现关系
源码
从源码可以看出StringBuilder继承了抽象类AbstractStringBuilder,所以在StringBuilder中并没有所要维护的数组char[] value,因为AbstractStringBuilder类已经包含了继承即可。同时可以看出StringBuilder也被关键字final修饰,即不能被继承,而且底层数组并没,所以StringBuilder是一个可以被修改的动态数组。同时还可以看出,StringBuilder是JDK1.5引入的。
StringBuilder构造函数
/**
* Constructs a string builder with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuilder() {
super(16);
}
/**
* Constructs a string builder with no characters in it and an
* initial capacity specified by the {@code capacity} argument.
*
* @param capacity the initial capacity.
* @throws NegativeArraySizeException if the {@code capacity}
* argument is less than {@code 0}.
*/
public StringBuilder(int capacity) {
super(capacity);
}
/**
* Constructs a string builder initialized to the contents of the
* specified string. The initial capacity of the string builder is
* {@code 16} plus the length of the string argument.
*
* @param str the initial contents of the buffer.
*/
public StringBuilder(String str) {
super(str.length() + 16);
append(str);
}
/**
* Constructs a string builder that contains the same characters
* as the specified {@code CharSequence}. The initial capacity of
* the string builder is {@code 16} plus the length of the
* {@code CharSequence} argument.
*
* @param seq the sequence to copy.
*/
public StringBuilder(CharSequence seq) {
this(seq.length() + 16);
append(seq);
}
StringBuilder总共有四个构造函数,同时有了数组默认大下,16.构造函数有无参构造函数以及三个有三参构造函数。
3,StringBuffer
类实现关系
源码