Tuesday, October 13, 2015

java - How to clear or empty a StringBuilder

MainActivity.java

package com.cfsuman.me.javaexamples;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get widget reference from XML layout
        TextView tv = (TextView) findViewById(R.id.tv);

        // Initialize a new StringBuilder object
        StringBuilder builder = new StringBuilder();
        builder.append("Hi! INNEE how are you?");

        // Show the StringBuilder content and length to TextView
        tv.setText("StringBuilder content : " + builder.toString());
        tv.setText(tv.getText() + "\nStringBuilder length : " + builder.length());

        // Now empty or clear the StringBuilder
        // Set the StringBuilder length to zero, so it will remove all its content
        builder.setLength(0);
        builder.trimToSize(); // Clear the storage by deleting old buffer

        // Again show the StringBuilder content and length to TextView
        tv.setText(tv.getText() + "\n\nStringBuilder after set length zero : StringBuilder.setLength(0)");
        tv.setText(tv.getText() + "\nStringBuilder content : " + builder.toString());
        tv.setText(tv.getText() + "\nStringBuilder length : " + builder.length());

        // Now append content to StringBuilder
        builder.append("LIZU, Where are you?");

        // Show the StringBuilder content and length to TextView
        tv.setText(tv.getText() + "\n\nStringBuilder after append text");
        tv.setText(tv.getText() + "\nStringBuilder content : " + builder.toString());
        tv.setText(tv.getText() + "\nStringBuilder length : " + builder.length());

        // Another way to empty or clear the StringBuilder object
        // Delete the StringBuilder content from index zero to its length
        builder.delete(0,builder.length());
        builder.trimToSize();

        // Show the StringBuilder content and length to TextView
        tv.setText(tv.getText() + "\n\nStringBuilder after call : StringBuilder.delete(0,StringBuilder.length()) ");
        tv.setText(tv.getText() + "\nStringBuilder content : " + builder.toString());
        tv.setText(tv.getText() + "\nStringBuilder length : " + builder.length());
    }
}
More android examples