Skip to main content
Added `println(line)`
Source Link
rolfl
  • 97.5k
  • 17
  • 218
  • 418

The wayAs an example usage, this is one of the ways that the above code is used is like. There are other places too:

String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
            + " "
            + DotPadding.getPadding(width - (2 + description.length() + index.length()))
            + " "
            + index;
System.out.println(line);

The way this code is used is like:

String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
            + " "
            + DotPadding.getPadding(width - (2 + description.length() + index.length()))
            + " "
            + index;

As an example usage, this is one of the ways that the above code is used. There are other places too:

String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
            + " "
            + DotPadding.getPadding(width - (2 + description.length() + index.length()))
            + " "
            + index;
System.out.println(line);
Source Link
rolfl
  • 97.5k
  • 17
  • 218
  • 418

Poke-a-Dot (Provider)

I need to create variable-length strings of dots/periods/full-stops to add to some text content, in a way that is similar to a formatted table-of-contents:

Chapter 1 .................................... 1
  Section 1.1 ................................ 1
  Subsection 1.1.2 .......................... 12

I know that things like String.format exist, but that is not suitable for formatting periods this way.

The code is complicated by the need for there to be many threads doing similar work at the same time.

I have written this utility class that caches a 'base' string in a Thread-local, and uses that to supply the required data.

Are there any alternatives, improvements, or other recommendations you have?

public final class DotPadding {

    private static final ThreadLocal<String> PAD_BASE = new ThreadLocal<String>() {
        @Override
        protected String initialValue() {
            return "................";
        }
    };

    public static final String getPadding(final int length) {
        if (length <= 0) {
            return "";
        }
        String base = PAD_BASE.get();
        if (base.length() >= length) {
            return base.substring(0, length);
        }
        while (base.length() < length) {
            base = base.concat(base);
        }
        PAD_BASE.set(base);
        return base.substring(0, length);
    }

}

The way this code is used is like:

String description = getFormattedDescription(title);
String index = getFormattedIndex(page);
String line = description
            + " "
            + DotPadding.getPadding(width - (2 + description.length() + index.length()))
            + " "
            + index;