I have this Java class for producing rotations of an input string:
StringRotator.java
package net.coderodde.util;
import java.util.Objects;
/**
* This class implements a data type for rotating strings.
*
* @author Rodion "rodde" Efremov
* @version 1.6 (Mar 24, 2016)
*/
public class StringRotator {
/**
* The source string. All rotations will be produced from this string.
*/
private final String string;
/**
* Caches the length of the source string in order to by a little of
* efficiency.
*/
private final int length;
/**
* Caches the current rotation. This field is set to {@code null} after
* every effective rotation. Whenever the user requests the rotated string,
* if this field is not {@code null}, the cached string is returned.
* Otherwise, a rotated string is built and set to this field, and finally
* returned.
*/
private String cachedString;
/**
* Index of the first logical character component in the source string.
*/
private int finger;
public StringRotator(String string) {
this.string = Objects.requireNonNull(string,
"The input string is null.");
this.length = string.length();
}
public void rotate(int offset) {
int oldFinger = finger;
finger += offset;
finger %= string.length();
if (finger != oldFinger) {
cachedString = null;
}
}
@Override
public String toString() {
if (cachedString != null) {
return cachedString;
}
return cachedString = buildString();
}
private String buildString() {
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; ++i) {
sb.append(string.charAt((finger + i) % length));
}
return sb.toString();
}
public static void main(final String... args) {
StringBuilder sb = new StringBuilder();
for (char c = 'a'; c <= 'z'; ++c) {
sb.append(c);
}
String input = sb.toString();
for (int i = 0; i < input.length(); ++i) {
StringRotator string = new StringRotator(input);
string.rotate(i);
System.out.println(string);
}
}
}
Please, tell me anything that comes to mind.