Как обнулить stringbuilder java

Java: очищаемм содержимое StringBuilder/StringBuffer

Для сложения большого количества строк гораздо эффективнее использовать объект StringBuilder (в многопоточной среде StringBuffer ). Но иногда возникает необходимость в очистке содержиммого StringBuilder -а. К сожалению данный класс не имеет метода, который бы очищал его содержимое. Но выход из ситуации есть: можно воспользоваться методом delete(int start, int end) класса StringBuilder , который удаляет строчки начиная с позиции start до позиции end .

В качестве начальной позиции необходимо указать 0, в в качестве конечной позиции — длинну содержимого StringBuilder-а. Выглядеть это все будет приерно так:

public class Test  public static void main (String[] args)  StringBuffer sb = new StringBuffer(); sb.append("This is StringBuilder "); sb.append("example"); System.out.println("StringBuilder content before cleaning: \n" + sb.toString()); //removing StringBuilder content sb.delete(0, sb.length()); sb.append("This is new StringBuilder content"); System.out.println("\n" + sb.toString()); > > 
StringBuilder content before cleaning: This is StringBuilder exampleThis is new StringBuilder content 

Для StringBuffer-а принцип такой же.

Источник

Очистка объекта StringBuilder в Java

Часто встречается ситуация, когда в процессе работы с объектом StringBuilder в Java возникает необходимость его очистить. Например, если используется цикл, в котором StringBuilder наполняется данными, и после каждого n-го повторения цикла требуется начать с пустого StringBuilder .

В Java нет прямого аналога метода Clear , который имеется в .NET для очистки StringBuilder . Вместо этого в Java есть метод delete() , который позволяет удалить подстроку из строки, хранящейся в StringBuilder . Однако использование этого метода может казаться сложным и избыточным, если нужно просто полностью очистить StringBuilder .

Наиболее простым и эффективным способом очистки StringBuilder в Java является присвоение ему нового экземпляра StringBuilder . Это можно сделать следующим образом:

StringBuilder sb = new StringBuilder(); sb.append("Hello, World!"); // Теперь sb содержит "Hello, World!" sb = new StringBuilder(); // Теперь sb пуст

Такой подход работает, потому что в Java объекты являются ссылочными типами. Когда sb присваивается новый экземпляр StringBuilder , старый экземпляр, содержащий «Hello, World!», больше не доступен и будет утилизирован сборщиком мусора.

Важно отметить, что этот подход является предпочтительным не только из-за его простоты, но и потому что он обычно будет быстрее, чем использование метода delete() . Это объясняется тем, что delete() требует времени на обновление внутреннего состояния StringBuilder , в то время как присвоение нового экземпляра StringBuilder является простой операцией.

Источник

Clear a StringBuilder in Java

Clear a StringBuilder in Java

  1. Using the setLength(0) Method to Clear or Empty a StringBuilder in Java
  2. Assign a New Object to a StringBuilder Variable to Clear or Empty It in Java
  3. Using the delete() Method to Clear or Empty a StringBuilder in Java

This Java guide will show you how to clear a StringBuilder . It’s a class in Java that implements different interfaces.

We can use the StringBuilder class to manipulate the strings in Java language. There are four different constructors types to initialize the StringBuilder object.

There are many methods to manipulate a string using this class. Let’s dive in.

Using the setLength(0) Method to Clear or Empty a StringBuilder in Java

We can clear a StringBuilder using the built-in method which is stringBuilderObj.setLength(0) . Two more methods are discussed down below.

In this method, all you need to do is use the setLength(0) method for your respective StringBuilder object. For instance, take a look at the following code.

// Java code to illustrate StringBuilder  import java.util.*; public class Main   public static void main(String[] argv) throws Exception   // ----------------METHOD 01 USING SETLENGHT METHOD--------------------  StringBuilder string = new StringBuilder(); //creating an instance of string  string.append("DelftStack"); // to insert chracters in string builder instance.  System.out.println("String = " + string.toString());  //How To Clear String Builder Object.  /*  using builtin method "stringBuilderObj.setLength(0)" ;  */  string.setLength(0); //clear the stringBuilder using The setlength Method. ;  System.out.println("String = " + string.toString()); // Printing after clear ;  string.append("DelftStack Best Website"); // inserting strings after clear.  System.out.println("String = " + string.toString()); // just printing.  > > 
String = DelftStack String = 

We inserted a string into StringBuilder in the above code and printed it. After that, using setLength(0) , we cleared the StringBuilder .

As you can see from the output, the string is empty.

Assign a New Object to a StringBuilder Variable to Clear or Empty It in Java

It is simply assigning a new object to a StringBuilder variable. You are not using any function or method using this way of clearing a string.

Take a look at the following code.

// Java code to illustrate StringBuilder  import java.util.*; public class Main   public static void main(String[] argv) throws Exception   // ----------------METHOD 02 BY ASSIGNING NEW OBJECT--------------------  StringBuilder string = new StringBuilder();  string.append("DelftStack Best Website"); // inserting strings  System.out.println("String = " + string.toString()); // just printing.  string = new StringBuilder(); // By Assgining NEW Object To String Builder Variable..  System.out.println("String = " + string.toString()); // Printing after clear ;  > > 
String = DelftStack Best Website String = 

Using the delete() Method to Clear or Empty a StringBuilder in Java

The delete() method takes two integer parameters. You can delete any part of the string by mentioning the index values.

For instance, in the string Delfstack Best Website , if we were to use string.delete(1,5) for this string, we would be left with DStack Best Website .

As you can see, the first parameter is the starting index, and the second parameter is the ending index.

It deletes that particular part of the string, in this case, from index 1 to index 5. Take a look at the following code.

// Java code to illustrate StringBuilder  import java.util.*; public class Main   public static void main(String[] argv) throws Exception   // ----------------METHOD 03 Using Delete Mehtod-------------------- //  // delete(int start, int end);  StringBuilder string = new StringBuilder();  string.append("DelftStack Best Website"); // inserting strings after clear.  System.out.println("String = " + string.toString()); // just printing.  string.delete(1, 5);  System.out.println("String = " + string.toString()); // Printing after Deleting specific values ;  > > 
String = DelftStack Best Website String = DStack Best Website 

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

Источник

Java StringBuilder clear example, how to empty StringBuilder (StringBuffer)

Java StringBuilder clear example shows how to clear the contents of StringBuilder or StringBuffer object. This example also shows how to empty StringBuilder/StringBuffer object in Java.

How to clear StringBuilder or StringBuffer in Java?

Suppose you have a StringBuilder object being used inside a loop and you want to empty its contents for each iteration of the loop. In such cases, you can clear the contents of the StringBuilder using below given ways.

1) Clear StringBuilder by assigning a new object

This method assigns a new StringBuilder object having no content to the existing reference. This is not exactly clearing the same object, but assigning a new empty object to the same reference.

2) Clear StringBuilder using the delete method

We can use the delete method of the StringBuilder class to selectively delete certain characters from it or we can use it to empty the contents of it.

The delete method accepts two parameters, start index and end index. To clear the contents, we are going to provide 0 as the start index and the length of the StringBuilder object as an end index to clear everything it has.

As you can see from the output, the content of the StringBuilder is cleared at the start of the loop.

3) Clear StringBuilder using setLength method

You can use the setLength method to clear the contents of the StringBuilder object.

For clearing the contents of the StringBuilder, we are going to pass 0 as new the length as shown in the below example.

What is the best way to clear the StringBuilder?

Now that we have seen three different methods to clear the StringBuilder, you may have this question. Well, the best way to clear the StringBuilder is to use the setLength method (3rd option).

Why? Because the first option creates a new StringBuilder object for each iteration of the loop. Object creation is a costly operation because it involves allocating new memory for the new object. Plus, garbage collection has to collect the old unused object. You should avoid this option if the number of iterations is too high due to the performance impact it might have.

Option 2 ( delete method) internally allocates a new buffer with the specified length and then copies the modified contents of the StringBuilder buffer to the new buffer. This is again a costly operation if the number of iteration is too high.

Option 3 is the best choice as it does not involve any new allocation and garbage collection. The setLength method just resets the internal buffer length variable to 0. The original buffer stays in the memory so new memory allocation is not needed and thus it is the fastest way to clear the StringBuilder.

Read this to know how to check if StringBuilder is empty or other String in Java to know more.

About the author

I have a master’s degree in computer science and over 18 years of experience designing and developing Java applications. I have worked with many fortune 500 companies as an eCommerce Architect. Follow me on LinkedIn and Facebook.

Источник

Читайте также:  User defined constructor in java
Оцените статью