请告诉我一个实时情况比较字符串,StringBuffer,和StringBuilder?
当前回答
就我个人而言,我认为StringBuffer在现实世界中没有任何用处。什么时候我想通过操纵字符序列在多个线程之间进行通信?这听起来一点用都没有,但也许我还没有看到光明:)
其他回答
就我个人而言,我认为StringBuffer在现实世界中没有任何用处。什么时候我想通过操纵字符序列在多个线程之间进行通信?这听起来一点用都没有,但也许我还没有看到光明:)
注意,如果您使用的是Java 5或更新版本,您应该使用StringBuilder而不是StringBuffer。来自API文档:
从JDK 5发行版开始,这个类已经被一个为单个线程使用而设计的等效类StringBuilder所补充。通常应该优先使用StringBuilder类,因为它支持所有相同的操作,但速度更快,因为它不执行同步。
在实践中,您几乎永远不会同时从多个线程中使用它,因此StringBuffer所做的同步几乎总是不必要的开销。
String和其他两个类的区别在于String是不可变的,而其他两个类是可变的。
但是为什么我们有两个相同目的的类呢?
原因是StringBuffer是线程安全的,而StringBuilder不是。 StringBuilder是StringBuffer Api上的一个新类,它是在JDK5中引入的,如果你工作在单线程环境中,总是推荐使用它,因为它要快得多
有关完整的详细信息,请访问http://www.codingeek.com/java/stringbuilder-and-stringbuffer-a-way-to-create-mutable-strings-in-java/
下面是一个小代码片段,演示了如何在异步环境中破坏StringBuilder
public static void main(String[] args) throws InterruptedException {
StringBuilder builder = new StringBuilder();
ExecutorService executorService = Executors.newFixedThreadPool(50);
for (int i = 0; i < 1000 * 1000; i++) {
executorService.submit(new AppendRunnable(builder));
}
executorService.shutdown();
executorService.awaitTermination(1, TimeUnit.MINUTES);
Stream.of(builder.toString().split(System.lineSeparator()))
.filter(line -> !line.equals("I just appended this!"))
.forEach(System.out::println);
}
record AppendRunnable(StringBuilder stringBuilder) implements Runnable {
@Override
public void run() {
stringBuilder.append("I just appended this!\n");
}
}
本质上,我们将字符串附加到构建器中,并期望它们都等于“我刚刚附加了这个!”。但它们不是,其中一些前缀是空字符,因为构建器的内部字符缓冲区没有同步,它被错误地调整了大小。在这种情况下使用StringBuffer可以解决问题。更多详细信息请点击这里
字符串
String类表示字符串。Java程序中的所有字符串字面值,例如“abc”,都被实现为该类的实例。
字符串对象是不可变的,一旦创建就不能改变。(字符串是常量)
If a String is created using constructor or method then those strings will be stored in Heap Memory as well as SringConstantPool. But before saving in pool it invokes intern() method to check object availability with same content in pool using equals method. If String-copy is available in the Pool then returns the reference. Otherwise, String object is added to the pool and returns the reference. The Java language provides special support for the string concatenation operator (+), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String heapSCP = new String("Yash"); heapSCP.concat("."); heapSCP = heapSCP + "M"; heapSCP = heapSCP + 777; // For Example: String Source Code public String concat(String str) { int otherLen = str.length(); if (otherLen == 0) { return this; } int len = value.length; char buf[] = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); } String literals are stored in StringConstantPool. String onlyPool = "Yash";
StringBuilder和StringBuffer是可变的字符序列。这意味着可以改变这些对象的值。StringBuffer具有与StringBuilder相同的方法,但是StringBuffer中的每个方法都是同步的,因此它是线程安全的。
StringBuffer and StringBuilder data can only be created using new operator. So, they get stored in Heap memory. Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used. StringBuffer threadSafe = new StringBuffer("Yash"); threadSafe.append(".M"); threadSafe.toString(); StringBuilder nonSync = new StringBuilder("Yash"); nonSync.append(".M"); nonSync.toString(); StringBuffer and StringBuilder are having a Special methods like., replace(int start, int end, String str) and reverse(). NOTE: StringBuffer and SringBuilder are mutable as they provides the implementation of Appendable Interface.
什么时候用哪一个。
If a you are not going to change the value every time then its better to Use String Class. As part of Generics if you want to Sort Comparable<T> or compare a values then go for String Class. //ClassCastException: java.lang.StringBuffer cannot be cast to java.lang.Comparable Set<StringBuffer> set = new TreeSet<StringBuffer>(); set.add( threadSafe ); System.out.println("Set : "+ set); If you are going to modify the value every time the go for StringBuilder which is faster than StringBuffer. If multiple threads are modifying the value the go for StringBuffer.
推荐文章
- c#:如何获得一个字符串的第一个字符?
- String类中的什么方法只返回前N个字符?
- 我可以将c#字符串值转换为转义字符串文字吗?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 在c#中解析字符串为日期时间
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 字符串中的单词大写
- 如何在方法中访问“静态”类变量?
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?