Java基础知识强化47:StringBuffer类之StringBuffer的三个面试题
1. 面试题:String,StringBuffer,StringBuilder的区别 ?
答:String是字符串内容不可变的,而StringBuffer和StringBuilder是字符串内容长度可变的;
StringBuffer是同步的,数据安全,效率低。
StringBuilder是不同步的,数据不安全,效率高。
(1). 在执行速度方面的比较:StringBuilder > StringBuffer
(2). StringBuffer与StringBuilder,他们是字符串变量,是可改变的对象,每当我们用它们对字符串做操作时,实际上是在一个对象上操作的,不像String一样创建一些对象进行操作,所以速度就快了。
(3). StringBuilder:线程非安全的
StringBuffer:线程安全的
当我们在字符串缓冲去被多个线程使用是,JVM不能保证StringBuilder的操作是安全的,虽然他的速度最快,但是可以保证StringBuffer是可以正确操作的。当然大多数情况下就是我们是在单线程下进行的操作,所以大多数情况下是建议用StringBuilder而不用StringBuffer的,就是速度的原因。
对于三者使用的总结:• 如果要操作少量的数据用 = String
• 单线程操作字符串缓冲区 下操作大量数据 = StringBuilder
• 多线程操作字符串缓冲区 下操作大量数据 = StringBuffer
注意:为什么StringBuffer具有数据安全的特性?
答:观察源码,如下:
/*
* @(#)StringBuffer.java 1.101 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/ package java.lang; /**
* A thread-safe, mutable sequence of characters.
* A string buffer is like a {@link String}, but can be modified. At any
* point in time it contains some particular sequence of characters, but
* the length and content of the sequence can be changed through certain
* method calls.
* <p>
* String buffers are safe for use by multiple threads. The methods
* are synchronized where necessary so that all the operations on any
* particular instance behave as if they occur in some serial order
* that is consistent with the order of the method calls made by each of
* the individual threads involved.
* <p>
* The principal operations on a <code>StringBuffer</code> are the
* <code>append</code> and <code>insert</code> methods, which are
* overloaded so as to accept data of any type. Each effectively
* converts a given datum to a string and then appends or inserts the
* characters of that string to the string buffer. The
* <code>append</code> method always adds these characters at the end
* of the buffer; the <code>insert</code> method adds the characters at
* a specified point.
* <p>
* For example, if <code>z</code> refers to a string buffer object
* whose current contents are "<code>start</code>", then
* the method call <code>z.append("le")</code> would cause the string
* buffer to contain "<code>startle</code>", whereas
* <code>z.insert(4, "le")</code> would alter the string buffer to
* contain "<code>starlet</code>".
* <p>
* In general, if sb refers to an instance of a <code>StringBuffer</code>,
* then <code>sb.append(x)</code> has the same effect as
* <code>sb.insert(sb.length(), x)</code>.
* <p>
* Whenever an operation occurs involving a source sequence (such as
* appending or inserting from a source sequence) this class synchronizes
* only on the string buffer performing the operation, not on the source.
* <p>
* Every string buffer has a capacity. As long as the length of the
* character sequence contained in the string buffer does not exceed
* the capacity, it is not necessary to allocate a new internal
* buffer array. If the internal buffer overflows, it is
* automatically made larger.
*
* As of release JDK 5, this class has been supplemented with an equivalent
* class designed for use by a single thread, {@link StringBuilder}. The
* <tt>StringBuilder</tt> class should generally be used in preference to
* this one, as it supports all of the same operations but it is faster, as
* it performs no synchronization.
*
* @author Arthur van Hoff
* @version 1.101, 11/17/05
* @see java.lang.StringBuilder
* @see java.lang.String
* @since JDK1.0
*/
public final class StringBuffer
extends AbstractStringBuilder
implements java.io.Serializable, CharSequence
{ /** use serialVersionUID from JDK 1.0.2 for interoperability */
static final long serialVersionUID = 3388685877147921107L; /**
* Constructs a string buffer with no characters in it and an
* initial capacity of 16 characters.
*/
public StringBuffer() {
super(16);
} /**
* Constructs a string buffer with no characters in it and
* the specified initial capacity.
*
* @param capacity the initial capacity.
* @exception NegativeArraySizeException if the <code>capacity</code>
* argument is less than <code>0</code>.
*/
public StringBuffer(int capacity) {
super(capacity);
} /**
* Constructs a string buffer initialized to the contents of the
* specified string. The initial capacity of the string buffer is
* <code>16</code> plus the length of the string argument.
*
* @param str the initial contents of the buffer.
* @exception NullPointerException if <code>str</code> is <code>null</code>
*/
public StringBuffer(String str) {
super(str.length() + 16);
append(str);
} /**
* Constructs a string buffer that contains the same characters
* as the specified <code>CharSequence</code>. The initial capacity of
* the string buffer is <code>16</code> plus the length of the
* <code>CharSequence</code> argument.
* <p>
* If the length of the specified <code>CharSequence</code> is
* less than or equal to zero, then an empty buffer of capacity
* <code>16</code> is returned.
*
* @param seq the sequence to copy.
* @exception NullPointerException if <code>seq</code> is <code>null</code>
* @since 1.5
*/
public StringBuffer(CharSequence seq) {
this(seq.length() + 16);
append(seq);
} public synchronized int length() {
return count;
} public synchronized int capacity() {
return value.length;
} ...
因为很多方法都是synchronized
2. 面试题:StringBuffer 和数组的区别?
答:二者都可以看出是一个容器,装其他的数据。但是呢,StringBuffer的数据最终是一个字符串数据,而数组可以放置任意类型的同一种数据。
3. 面试题:形式参数问题。
String作为参数传递
StringBuffer作为参数传递
形式参数:
基本类型:形式参数的改变不影响实际参数
引用类型:形式参数的改变直接影响实际参数
案例演示:
package cn.itcast_08; /*
* 形式参数问题:
* String作为参数传递
* StringBuffer作为参数传递
*
* 形式参数:
* 基本类型:形式参数的改变不影响实际参数
* 引用类型:形式参数的改变直接影响实际参数
*
* 注意:
* String作为参数传递,效果和基本类型作为参数传递是一样的。
*/
public class StringBufferDemo {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
System.out.println(s1 + "---" + s2);// hello---world
change(s1, s2);
System.out.println(s1 + "---" + s2);// hello---world StringBuffer sb1 = new StringBuffer("hello");
StringBuffer sb2 = new StringBuffer("world");
System.out.println(sb1 + "---" + sb2);// hello---world
change(sb1, sb2);
System.out.println(sb1 + "---" + sb2);// hello---worldworld } public static void change(StringBuffer sb1, StringBuffer sb2) {
sb1 = sb2;
sb2.append(sb1);
} public static void change(String s1, String s2) {
s1 = s2;
s2 = s1 + s2;
}
}
运行效果如下:

Java基础知识强化47:StringBuffer类之StringBuffer的三个面试题的更多相关文章
- Java基础知识强化09:String、StringBuffer和StringBuilder使用
1. 对于三者使用的总结: (1).如果要操作少量的数据用 = String (2).单线程操作字符串缓冲区下操作大量数据 = StringBuilder (3).多线程操 ...
- Java基础知识强化之IO流笔记62:三种方式实现键盘录入
1. 三种方式实现键盘录入 System.in 标准输入流.是从键盘获取数据的 键盘录入数据三种方式: A:main方法的args接收参数. java HelloWorld hello w ...
- Java基础知识强化之集合框架笔记66:Map集合面试题之HashMap和Hashtable区别(重要)
1. HashMap和Hashtable区别 ? • Hashtable:线程安全,效率低.不允许null键和null值 • HashMap:线程不安全,效率高.允许null键和null值 packa ...
- Java基础知识强化之集合框架笔记76:ConcurrentHashMap之 ConcurrentHashMap简介
1. ConcurrentHashMap简介: ConcurrentHashMap是一个线程安全的Hash Table,它的主要功能是提供了一组和Hashtable功能相同但是线程安全的方法.Conc ...
- Java基础知识强化43:StringBuffer类之StringBuffer和String的相互转化
1. String和StringBuffer的相互转换 思想是:A-----B的转换,我们把A转换为B,其实是为了使用B的功能:B-----A的转换,我们可能的结果是A类型,所以还要转换回来 2. 案 ...
- Java基础知识强化45:StringBuffer类之字符串反转的案例
1. 案例演示: package cn.itcast_07; import java.util.Scanner; /* * 把字符串反转 */ public class StringBufferTes ...
- Java基础知识强化42:StringBuffer类之StringBuffer的截取功能
1. StringBuffer的截取功能: public String subString(int Start): public String subString(int Start, int end ...
- Java基础知识强化40:StringBuffer类之StringBuffer的替换功能
1. StringBuffer的替换功能: public StringBuffer replace(int start, int end, String str): 2. 案例演示: p ...
- Java基础知识强化39:StringBuffer类之StringBuffer的删除功能
1. StringBuffer的删除功能: public StringBuffer deleteCharAt(int index):删除指定位置的字符,并返回字符串缓冲区本身. public Str ...
随机推荐
- 系统管理中 bash shell 脚本常用方法总结
在日常系统管理工作中,需要编写脚本来完成特定的功能,编写shell脚本是一个基本功了!在编写的过程中,掌握一些常用的技巧和语法就可以完成大部分功能了,也就是2/8原则 1. 单引号和双引号的区别 单引 ...
- Jquery中dialog属性小记
代码如下: $('#dialogDiv').dialog( { hide:true, //点击关闭是隐藏,如果不加这项,关闭弹窗后再点就会出错. autoOpen:false, height:380, ...
- C/C++默认浮点型
代码: #include <iostream> #include <cstdio> using namespace std; void test(int a){ cout< ...
- 思科27亿美元收购网络安全公司Sourcefire
据国外媒体报道,思科于今日宣布将以27亿美元的总价收购网络安全公司Sourcefire,以加强自身在网络安全业务领域的优势,该交易将于今年下半年完成. [IT商业新闻网讯](记者 张良)7月23日消息 ...
- Oracle数据库之创建表结构
Oracle数据库之创建表结构 主键与外键 主键:关系型数据库中的一条记录中有若干个属性,若其中的某一个属性组(可以是一个属性,也可以是多个)能唯一标识一条记录,那么该属性组就是主键. 外键:关系型数 ...
- java学习笔记(13) —— google GSON 实现json转化方法
1.配置struts.xml <action name="getGsonAction" class="com.test.action.json.GetGsonAct ...
- phpcms v9版本二次开发四步曲
今晚看了一下PHPCMS V9版本,做一个实例抛砖引玉,其实很简单,以下是二次开发的一个实例以旅游模块为例1. 在phpcms\modules目录下建立一个文件夹tour2. 在phpcms\m ...
- Ubuntu下搭建本地WordPress站点
想在本地搭建WordPress博客站点作测试用?本教程一步一步教您在Linux上搭建一个LAMP(Linux, Apache, MySQL, PHP)服务器并部署WordPress博客. 请注意在复制 ...
- Android 常用对话框Dialog封装
Android 6种 常用对话框Dialog封装 包括: 消息对话框.警示(含确认.取消)对话框.单选对话框. 复选对话框.列表对话框.自定义视图(含确认.取消)对话框 分别如下图所示: ...
- C51程序优化
1.指针: 对于大部分的编译器,使用指针比使用数组生成的代码更短,执行效率更高.但是在Keil中则相反,使用数组比使用的指针生成的代码更短.通常使用自加.自减指令和复合赋值表达式(如a-=1及a+=1 ...