Рубрики
Без рубрики

Java StringBuilder Демистифицирован

Давайте разберемся, что заставляет каждого ведущего разработчика говорить, что вы должны знать, как создать свой собственный… Помеченный как java, код, учебное пособие, руководство.

Давайте поймем, что заставляет каждого ведущего разработчика говорить, что вы должны знать, как создать свой собственный StringBuilder, если вы планируете изменять свои строки. И самое главное – в чем разница между конкатенацией строк и использованием этого шаблона.

Проще говоря, то, что мы хотим сделать, – это эффективное управление пространством и производительностью.

Это самая простая из всех реализаций с основными характеристиками StringBuilder

  • .добавить()
  • .длина ()
  • .toString ()

MyStringBuilder Строитель

import java.util.Arrays;

public class MyStringBuilder {

    private static final int INIT_CAPACITY = 16;
    private static final float LOAD_FACTOR = 0.75f;
    private static final int MULTIPLIER = 2;

    private int currentCapacity = INIT_CAPACITY;

    // store the total number of characters in our string builder
    private int count;

    // storage area for our characters
    private char[] chars;

    public MyStringBuilder() {
        chars = new char[INIT_CAPACITY];
    }

    public MyStringBuilder(String str) {
        this();
        append(str);
    }

    public MyStringBuilder append(String newStr) {

        final int length = newStr.length();

        // check if resized or not
        boolean inflated = ensureCapacity(length);

        if (inflated) {
            final char[] newBuffer = new char[currentCapacity];
            // copy current content
            System.arraycopy(chars, 0, newBuffer, 0, count);
            // copy new content
            System.arraycopy(newStr.toCharArray(), 0, newBuffer, count, length);

            // update the store array
            chars = newBuffer;
        } else {
            // add the new content to the remaining array space
            System.arraycopy(newStr.toCharArray(), 0, chars, count, length);
        }

        // update the count of chars
        count += length;

        return this;
    }

    private boolean ensureCapacity(int newLength) {
        boolean isInflated = false;
        // ensure the new length is properly accommodated
        while (Float.compare((float) (count + newLength) / currentCapacity, LOAD_FACTOR) >= 0) {
            currentCapacity *= MULTIPLIER;
            isInflated = true;
        }

        return isInflated;
    }

    public int length() {
        return count;
    }

    @Override
    public String toString() {
        return new String(Arrays.copyOfRange(chars, 0, count));
    }
}

public class MyStringBuilderDriver {

    public static void main(String[] args) {

        var sb = new MyStringBuilder();

        sb.append("Hi").append(" ");
        sb.append("Saurabh").append(",").append(" ");
        sb.append("how are you today ?");

        System.out.println(sb);
        System.out.println(sb.length());
    }
}

Если вы считаете, что это круто – дайте мне знать, какой объект фреймворка языка Java я должен демистифицировать.

Оригинал: “https://dev.to/saurabhpro/stringbuilder-demystified-1p64”