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;