您的位置:首页 > 产品设计 > UI/UE

String,StringBuilder以及StringBuffer三者之间的区别

2018-03-05 21:16 597 查看
来广州面试的第一家鸟公司。就问到了一个一问题。String,StringBuilder以及StringBuffer三者之间的区别;1,对于运行速度而讲。StringBuiler>StringBuffer>String 。为什么String速度最慢。举个栗子:String Str = “abc”+“qwe”;jvm虚拟机会对以上操作对象进行以下操作。String str 1= “abc”;String str2 = "qwe";String str = str1 + str2;这也是正式印证了jvm的工作原理,不停的创造对象,回收对象来进行操作的。2,对于线程安全来讲、StringBuffer线程是安全的。通过编译器.按住Ctrl键后进去去看以下。StringBuffer源码。就会发现里面很多的方法都是用synchronized来修饰过的。这里就不解释为什么用synchronized修饰的线程是安全的好吗?其实我也不是很懂。下节再去讨论!(附上源码自己研究)

public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
}

public synchronized int length() {
return count;
}

public synchronized int capacity() {
return value.length;
}

public synchronized void ensureCapacity(int minimumCapacity) {
if (minimumCapacity > value.length) {
expandCapacity(minimumCapacity);
}
}

/**
* @since      1.5
*/
public synchronized void trimToSize() {
super.trimToSize();
}

/**
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see        #length()
*/
public synchronized void setLength(int newLength) {
super.setLength(newLength);
}

/**
* @throws IndexOutOfBoundsException {@inheritDoc}
* @see        #length()
*/
public synchronized char charAt(int index) {
if ((index < 0) || (index >= count))
throw new StringIndexOutOfBoundsException(index);
return value[index];
}

/**
* @since      1.5
*/
public synchronized int codePointAt(int index) {
return super.codePointAt(index);
}

/**
* @since     1.5
*/
public synchronized int codePointBefore(int index) {
return super.codePointBefore(index);
}

/**
* @since     1.5
*/
public synchronized int codePointCount(int beginIndex, int endIndex) {
return super.codePointCount(beginIndex, endIndex);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: