Java stringbuilder equals string

StringBuffer и StringBuilder

1. Отличие между String, StringBuilder, StringBuffer

  1. Классы StringBuffer и StringBuilder в Java используются, когда возникает необходимость сделать много изменений в строке символов.
  2. В отличие от String , объекты типа StringBuffer и StringBuilder могут быть изменены снова и снова.
  3. В Java StringBuilder был введен начиная с Java 5.
  4. Основное различие между StringBuffer и StringBuilder в Java является то, что методы StringBuilder не являются безопасными для потоков (несинхронизированные).
  5. Рекомендуется использовать StringBuilder всякий раз, когда это возможно, потому что он быстрее, чем StringBuffer в Java.
  6. Однако, если необходима безопасность потоков, наилучшим вариантом являются объекты StringBuffer .

2. Конструкторы StringBuilder

  • StringBuilder() — объект StringBuilder можно создать без параметров, при этом в нем будет зарезервировано место для размещения 16 символов.
  • StringBuilder(int size) — вы также можете передать конструктору целое число, для того чтобы явно задать требуемый размер буфера.
  • StringBuilder(String str) — вы можете передать конструктору строку, при этом она будет скопирована в объект и дополнительно к этому в нем будет зарезервировано место еще для 16 символов.
  • StringBuilder(CharSequence chars)

В следующем примере создадим объект класса StringBuilder , и выведем на консоль его размер методом length() . Метод capacity() возвращает размер буфера:

public class StringBuilderDemo1 < public static void main(String[] args) < StringBuilder stringBuilder = new StringBuilder("Hello"); System.out.println("string = " + stringBuilder); System.out.println("length = " + stringBuilder.length()); System.out.println("capacity header3">3. Методы charAt(), setCharAt() 

Метод charAt() возвращает символ в указанной позиции. А setCharAt() изменяет символ в указанной позиции:

public class SetCharAtDemo < public static void main(String[] args) < StringBuilder sb = new StringBuilder("Hello"); System.out.println(sb); System.out.println("charAt(1) header4">4. Метод append() 

Метод append() присоединяет подстроку к строке:

public class AppendDemo < public static void main(String[] args) < int a = 42; StringBuilder sb = new StringBuilder(40); String s = sb.append("a = ").append(a).append("!").toString(); System.out.println(s); >>

5. Метод insert()

Метод insert() вставляет подстроку в указанную позицию:

6. Метод reverse()

Используется для инвертирования строки:

7. Методы delete() и deleteCharAt()

Метод delete() удаляет подстроку, используя указанные позиции.

Метод deleteCharAt() удаляет символ с указанной позиции:

8. Метод replace()

Заменяет подстроку в указанной позиции другой:

9. Методы equals() и hashCode()

Классы StringBuilder и StringBuffer не переопределяют методы equals() и hashCode() . Они используют реализацию класса Object :

public class StringBuilderEquals < public static void main(String[] args) < StringBuilder stringBuilder1 = new StringBuilder("Hello"); StringBuilder stringBuilder2 = new StringBuilder("Hello"); System.out.println(stringBuilder1.equals(stringBuilder2)); System.out.println(stringBuilder1 == stringBuilder2); >>

Источник

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are " start ", then the method call z.append("le") would cause the string builder to contain " startle ", whereas z.insert(4, "le") would alter the string builder to contain " starlet ".

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Class StringBuilder

A mutable sequence of characters. This class provides an API compatible with StringBuffer , but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

The principal operations on a StringBuilder are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

For example, if z refers to a string builder object whose current contents are " start ", then the method call z.append("le") would cause the string builder to contain " startle ", whereas z.insert(4, "le") would alter the string builder to contain " starlet ".

In general, if sb refers to an instance of a StringBuilder , then sb.append(x) has the same effect as sb.insert(sb.length(), x) .

Every string builder has a capacity. As long as the length of the character sequence contained in the string builder does not exceed the capacity, it is not necessary to allocate a new internal buffer. If the internal buffer overflows, it is automatically made larger.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

Unless otherwise noted, passing a null argument to a constructor or method in this class will cause a NullPointerException to be thrown.

Источник

Difference between String and StringBuilder in Java

This post will discuss the difference between string and StringBuilder (or StringBuffer ) in Java.

1. Mutability

A String is immutable in Java, while a StringBuilder is mutable in Java. An immutable object is an object whose content cannot be changed after it is created.

When we try to concatenate two Java strings, a new String object is created in the string pool. This can be demonstrated by comparing HashCode for String object after every concat operation.

Output:

2081
64578

As evident from the above code, a new hashcode is generated after concatenation, proving that a new String object is created with updated values and the old object was dereferenced.

2. Equality

We can use the equals() method for comparing two strings in Java since the String class overrides the equals() method of the Object class, while StringBuilder doesn’t override the equals() method of the Object class and hence equals() method cannot be used to compare two StringBuilder objects.

Output:

true
false

3. Comparable

The String class implements the Comparable interface, while StringBuilder doesn’t. To illustrate, consider the following code, which throws ClassCastException since StringBuilder doesn’t provide any mechanism for string comparison.

Output:

java.lang.StringBuilder cannot be cast to java.lang.Comparable

4. Constructor

We can create a String object without using a new operator, which is not possible with a StringBuilder .

5. Performance

StringBuilder is speedy and consumes less memory than a string while performing concatenations. This is because string is immutable in Java, and concatenation of two string objects involves creating a new object.

To illustrate, consider the following code, which logs the time taken by both string and StringBuilder objects on multiple concatenations.

Output (will vary):

The time taken by string concatenation: 504774386ns
The time taken by StringBuilder concatenation: 1081315ns

6. Length

Since String is immutable, its length is fixed. But StringBuilder has the setLength() method, which can change the StringBuilder object to the specified length.

When to use string and StringBuilder ?

A String can be used when immutability is required, or concatenation operation is not required. A StringBuilder can be used when a mutable string is needed without the performance overhead of constructing lots of strings along the way.

That’s all about the differences between String and StringBuilder in Java.

Average rating 4.81 /5. Vote count: 81

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Источник

Читайте также:  Typescript react style type
Оцените статью