-1

String or String Builder which one is preferable in the below method ? Kindly explain.

ArrayList<String> list=new ArrayList< String >();
    list.add(new String ("One"));
    list.add(new String ("Two"));
    list.add(new String ("Three"));
    .
    .
    .
    list.add(new String ("N"));

(or)

ArrayList<StringBuilder> list=new ArrayList<StringBuilder>();
    list.add(new StringBuilder("One"));
    list.add(new StringBuilder("Two"));
    list.add(new StringBuilder("Three"));
    .
    .
    .
    list.add(new StringBuilder("N"));
Vinoth Vasu
  • 53
  • 1
  • 1
  • 6
  • 5
    `list.add(“One”);` is preferable – Thorbjørn Ravn Andersen Oct 09 '18 at 03:26
  • Or `List list = new ArrayList<>(Arrays.asList("One", "Two", "Three", ... "N"));`. – Tom Hawtin - tackline Oct 09 '18 at 03:33
  • `in terms of performance..` - so the first approach creates a String Object. The second approach creates a String object and a StringBuilder object. Which do you think is preferable and why? – camickr Oct 09 '18 at 03:33
  • There is hardly ever any reason to use the constructor `new String` - `String` is immutable, even the [JavaDocs explicitly mention:](https://docs.oracle.com/javase/10/docs/api/java/lang/String.html#%3Cinit%3E(java.lang.String)) "Unless an explicit copy of original is needed, use of this constructor is unnecessary since Strings are immutable." – Hulk Oct 09 '18 at 06:10
  • 1
    Neither. You're achieving two different goals as you're constructing lists designated to hold different types of objects. – Janus Varmarken Oct 09 '18 at 06:33

2 Answers2

0

My answer is based on google search not a own answer, I think my small effort help you in better understanding of the topic.

Stringbuilder vs string:

  • String is immutable whereas StringBuffer and StringBuider are mutable classes.

  • StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.

  • String concat + operator internally uses StringBuffer or StringBuilder class.

Stackoverflow answer

Conclusion/Answer:

Everyone prefer stringbuilder compare to string

kvk30
  • 1,133
  • 1
  • 13
  • 33
0

This is depend on your requirement, if you want to modify object located at certain index then go for string builder. But again if you are working in a multithreaded environment then you have to use string builder carefully as it is a mutable class.

If you are not modifying your list then you must go for String.

Vivek Swansi
  • 409
  • 1
  • 4
  • 13