java StringBuffer 如何与 .append 一起使用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14287884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:46:16  来源:igfitidea点击:

How is StringBuffer used with .append

javastring-concatenationstringbuffer

提问by user1965081

I'm doing a computer science project and I need to incorporate StringBuffers. I need help with what .appenddoes and what concatenate means. Somebody told me I can show who is the winner (of my game) by using .appendwith StringBuffer.

我正在做一个计算机科学项目,我需要合并StringBuffers. 我需要关于什么.append是什么以及连接意味着什么的帮助。有人告诉我,我可以通过使用.appendwith来显示谁是(我的游戏)的赢家StringBuffer

  public static void winner ()
  {
    if (position1 >= 100){
      System.out.println("THE WINNER IS " + name1); 
    }
    else if (position2 >= 100){
      System.out.println("THE WINNER IS " + name2); 
    }
  }

Instead of having name as strings, can I use StringBufferto output who won the game?

除了将名称作为字符串,我可以使用StringBuffer输出谁赢得了比赛吗?

回答by Brigham

Thanks to the compiler, you are already using StringBuilderwhich is the newer, faster version of StringBuffer.

多亏了编译器,您已经在使用StringBuilder哪个是StringBuffer.

Your code above will compile to the equivalent of:

您上面的代码将编译为等效于:

public static void winner ()
{
  if (position1 >= 100){
    System.out.println(new StringBuilder("THE WINNER IS ").append(name1).toString()); 
  }
  else if (position2 >= 100){
    System.out.println(new StringBuilder("THE WINNER IS ").append(name2).toString()); 
  }
}

So, in this case, you would not be accomplishing anything that isn't already being done for you. Use StringBuilderwhen you are building a Stringin a loop.

因此,在这种情况下,您将不会完成尚未为您完成的任何事情。使用StringBuilder时,你正在建设一个String在一个循环。

In your situation, they were probably talking about pre-initializing a single StringBuilder for both cases:

在您的情况下,他们可能正在谈论为这两种情况预初始化单个 StringBuilder:

public static void winner() {
  StringBuilder out = new StringBuilder("THE WINNER IS ");
  if (position1 >= 100) {
    out.append(name1);
  } else if (position2 >= 100 {
    out.append(name2);
  } else {
    return; // Preserve previous behavior just in case, remove this if it's not needed
  }
  System.out.println(out);
}

回答by phippsnatch

You probably want something like:

你可能想要这样的东西:

  public static void winner ()
  {
      StringBuffer sb = new StringBuffer("THE WINNER IS ");

      if (position1 >= 100)
          System.out.println(sb.append(name1).toString());
      else if (position2 >= 100)
          System.out.println(sb.append(name2).toString());
  }

BUT generally StringBuilder is preferred to StringBuffer as access to StringBuffer is synchronized.

但是通常 StringBuilder 比 StringBuffer 更受欢迎,因为对 StringBuffer 的访问是同步的。

回答by asgoth

You can, since System.out.printlnwill convert its argument to a Stringautomatically, hence resulting the content of the StringBuffer. Mostly you will use it when you need to iterate a set of data.

您可以,因为System.out.printlnString自动将其参数转换为 a ,从而产生StringBuffer. 大多数情况下,您将在需要迭代一组数据时使用它。

With the appendmethod, you can append data to the buffer:

使用该append方法,您可以将数据附加到缓冲区:

String[] values = { 'string value', 'testing' };
StringBuffer sb = new StringBuffer();
for(String value: values) {
    sb.append(value);
}

will result in --> string valuetesting

将导致--> string valuetesting

Note:It might be better to consider StringBuilderinstead.

注意:最好考虑一下StringBuilder

回答by Jesus Ramos

Small string appends and concats typically don't see much of a gain from using StringBuilderbut just keep in mind that a string append has 3 operations, 1 new allocation consisting of the size of both strings added, and 2 copy operations to copy the contents (which means you now have 3 strings in memory), with StringBuilderyou just append and resize to a fixed width buffer which only requires 1 copy most of the time (amortized cost copy, sometimes you need to resize which takes 2). If you are appending a lot into 1 string I would recommend using StringBuilderinstead but for concatentations like yours you should not see a loss in performance (measurable at least).

小字符串追加和连接通常不会从使用中获得多少收益,StringBuilder但请记住,字符串追加有 3 个操作,1 个新分配由添加的两个字符串的大小组成,以及 2 个复制操作来复制内容(这意味着您现在在内存中有 3 个字符串),StringBuilder您只需将固定宽度的缓冲区附加并调整大小,该缓冲区大部分时间只需要 1 个副本(摊销成本副本,有时您需要调整大小,这需要 2 个)。如果您将很多附加到 1 个字符串中,我建议您StringBuilder改用,但对于像您这样的串联,您不应看到性能下降(至少是可测量的)。

回答by AlexWien

The idea of using StringBufferor StringBuilderis to avoid repeated concatenation of Strings as showed below:

使用StringBufferor的想法StringBuilder是避免重复连接字符串,如下所示:

String result = "";
for (int i = 0; i < 200; i++) {
    result = result + i + ",";
}

This is not efficient, in each loop one String object is (java internally) created

这效率不高,在每个循环中都会创建一个 String 对象(java 内部)

Using StringBuilder / StringBuffer:

使用 StringBuilder / StringBuffer:

StringBuilder buf = new StringBuilder(200); // init with a estimation of length has advantage
for (int i = 0; i < 200; i++) {
    buf.append(i).append(",");
}
String result = buf.toString();

This avoids unneeded creation of strings in each loop, it simply fills up the buffer with characters, and resize the buffer if needed.

这避免了在每个循环中创建不必要的字符串,它只是用字符填充缓冲区,并在需要时调整缓冲区的大小。

However in your case it is not worth the effort.

但是,在您的情况下,这是不值得的。

回答by Farhan Syed

Yes you can. Like everyone pointed out, StringBuffer.toString() will flush out the contents as a String. The question you need to ask yourself is, do you really care about what you use or do you specifically want to use StringBuffer to learn something.

是的你可以。就像每个人都指出的那样,StringBuffer.toString() 会将内容作为字符串清除。你需要问自己的问题是,你真的关心你使用的东西还是你特别想使用 StringBuffer 来学习一些东西。

For your operation, one is as good as the other. If you really want to do what your friend tells you, I think folks here have answered it clearly.

对于您的操作,一个和另一个一样好。如果你真的想按照你朋友说的去做,我想这里的人已经回答得很清楚了。

Or you can tell your friend, "It doesn't matter. One is as good as the other in my case" :)

或者你可以告诉你的朋友,“没关系。就我而言,一个和另一个一样好”:)

回答by Pawananjay

For getting synchronized version of string recommended to use StringBuffer where thread-safety is high required . For non-synchronized use StringBuilder class where thread-safety is not required and our application will give better performance ..

为了获得字符串的同步版本,建议在需要高线程安全性的情况下使用 StringBuffer 。对于不需要线程安全的非同步使用 StringBuilder 类,我们的应用程序将提供更好的性能..