English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans cet exemple, nous allons apprendre à utiliser les méthodes delete() et setLength() pour supprimer le tampon de chaîne et à créer un nouveau objet StringBuffer en Java.
class Main { public static void main(String[] args) { //Créer un tampon de chaîne StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" popular."); System.out.println("StringBuffer: ") + str); //Clear the string //Utilisation de delete() str.delete(0, str.length()); System.out.println("Updated StringBuffer: ") + str); } }
Output result
StringBuffer: Java est populaire. Updated StringBuffer:
Dans l'exemple ci-dessus, nous avons utilisé la méthode delete() de la classe StringBuffer pour supprimer le tampon de chaîne.
Ici, la méthode delete() supprime tous les caractères dans l'index spécifié.
class Main { public static void main(String[] args) { //Créer un tampon de chaîne StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: ") + str); //Clear the string //Utilisation de setLength() str.setLength(0); System.out.println("Updated StringBuffer: ") + str); } }
Output result
StringBuffer: Java is awesome. StringBuffer mis à jour
Ici, la méthode setLength() change la séquence de caractères dans le StringBuffer et la fixe à une nouvelle séquence. Et, la longueur de la nouvelle séquence de caractères est définie sur 0.
Par conséquent, la séquence de caractères ancienne est recyclée.
Attention:La méthode SetLength() ignore complètement la séquence de caractères existante dans le tampon de chaîne. En revanche, la méthode delete() accède à la séquence de caractères et la supprime. Par conséquent, setLength() est plus rapide que delete().
class Main { public static void main(String[] args) { //Créer un tampon de chaîne StringBuffer str = new StringBuffer(); //Add the string to the string buffer str.append("Java"); str.append(" is"); str.append(" awesome."); System.out.println("StringBuffer: ") + str); //Clear the string //Using new //In this case, a new object is created and assigned to str str = new StringBuffer(); System.out.println("Updated StringBuffer: ") + str); } }
Output result
StringBuffer: Java is awesome. Updated StringBuffer:
In this case, new StringBuffer() creates a new StringBuffer object and assigns the previous variable to the new object. In this case, the previous object will be there. But it will not be accessible and will be garbage collected.
Because it does not clear the previous string buffer each time, but creates a new string buffer. Therefore, it is less efficient in terms of performance.