Skip to content

Commit

Permalink
Remove uses of String#toCharArray() (#3556)
Browse files Browse the repository at this point in the history
When looping over the contents of a `String` it is typically better to work with `String#charAt()`.
  • Loading branch information
knutwannheden authored Sep 21, 2023
1 parent d9c6cce commit 00edaff
Show file tree
Hide file tree
Showing 11 changed files with 67 additions and 66 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -103,13 +103,11 @@ public static String trimIndent(String text) {
if (end == start) {
end++;
}
char[] charArray = text.substring(start, end).toCharArray();

StringBuilder trimmed = new StringBuilder();
for (int i = 0; i < charArray.length; i++) {
for (int i = start; i < end; i++) {
int j = i;
for (; j < charArray.length; j++) {
char c = charArray[j];
for (; j < end; j++) {
char c = text.charAt(j);
if (c == '\r' || c == '\n') {
trimmed.append(c);
break;
Expand Down Expand Up @@ -139,7 +137,8 @@ private static int minCommonIndentLevel(String text) {
int minIndent = Integer.MAX_VALUE;
int whiteSpaceCount = 0;
boolean contentEncountered = false;
for (char c : text.toCharArray()) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n' || c == '\r') {
if (contentEncountered) {
minIndent = Math.min(whiteSpaceCount, minIndent);
Expand Down Expand Up @@ -565,7 +564,8 @@ private static boolean different(boolean caseSensitive, char ch, char other) {

public static String indent(String text) {
StringBuilder indent = new StringBuilder();
for (char c : text.toCharArray()) {
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n' || c == '\r') {
return indent.toString();
} else if (Character.isWhitespace(c)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,6 @@ public ReloadableJava17JavadocVisitor(Context context, TreePath scope, Reloadabl
}

private void init() {
char[] sourceArr = source.toCharArray();

StringBuilder firstPrefixBuilder = new StringBuilder();
StringBuilder javadocContent = new StringBuilder();
StringBuilder marginBuilder = null;
Expand All @@ -98,12 +96,12 @@ private void init() {

// skip past the opening '/**'
int i = 3;
for (; i < sourceArr.length; i++) {
char c = sourceArr[i];
for (; i < source.length(); i++) {
char c = source.charAt(i);
if (inFirstPrefix) {
// '*' characters are considered a part of the margin until a non '*' is parsed.
if (Character.isWhitespace(c) || c == '*' && isPrefixAsterisk) {
if (isPrefixAsterisk && i + 1 <= sourceArr.length - 1 && sourceArr[i + 1] != '*') {
if (isPrefixAsterisk && i + 1 <= source.length() - 1 && source.charAt(i + 1) != '*') {
isPrefixAsterisk = false;
}
firstPrefixBuilder.append(c);
Expand All @@ -118,30 +116,31 @@ private void init() {
}

if (c == '\n') {
char prev = source.charAt(i - 1);
if (inFirstPrefix) {
firstPrefix = firstPrefixBuilder.toString();
inFirstPrefix = false;
} else {
// Handle consecutive new lines.
if ((sourceArr[i - 1] == '\n' ||
sourceArr[i - 1] == '\r' && sourceArr[i - 2] == '\n')) {
String prevLineLine = sourceArr[i - 1] == '\n' ? "\n" : "\r\n";
if ((prev == '\n' ||
prev == '\r' && source.charAt(i - 2) == '\n')) {
String prevLineLine = prev == '\n' ? "\n" : "\r\n";
lineBreaks.put(javadocContent.length(), new Javadoc.LineBreak(randomId(), prevLineLine, Markers.EMPTY));
} else if (marginBuilder != null) { // A new line with no '*' that only contains whitespace.
String newLine = sourceArr[i - 1] == '\r' ? "\r\n" : "\n";
String newLine = prev == '\r' ? "\r\n" : "\n";
lineBreaks.put(javadocContent.length(), new Javadoc.LineBreak(randomId(), newLine, Markers.EMPTY));
javadocContent.append(marginBuilder.substring(marginBuilder.indexOf("\n") + 1));
}
javadocContent.append(c);
}
String newLine = sourceArr[i - 1] == '\r' ? "\r\n" : "\n";
String newLine = prev == '\r' ? "\r\n" : "\n";
marginBuilder = new StringBuilder(newLine);
} else if (marginBuilder != null) {
if (!Character.isWhitespace(c)) {
if (c == '*') {
// '*' characters are considered a part of the margin until a non '*' is parsed.
marginBuilder.append(c);
if (i + 1 <= sourceArr.length - 1 && sourceArr[i + 1] != '*') {
if (i + 1 <= source.length() - 1 && source.charAt(i + 1) != '*') {
lineBreaks.put(javadocContent.length(), new Javadoc.LineBreak(randomId(),
marginBuilder.toString(), Markers.EMPTY));
marginBuilder = null;
Expand All @@ -152,7 +151,7 @@ private void init() {
marginBuilder.toString(), Markers.EMPTY));
javadocContent.append(c);
} else {
String newLine = marginBuilder.toString().startsWith("\r") ? "\r\n" : "\n";
String newLine = marginBuilder.charAt(0) == '\r' ? "\r\n" : "\n";
lineBreaks.put(javadocContent.length(), new Javadoc.LineBreak(randomId(),
newLine, Markers.EMPTY));
String margin = marginBuilder.toString();
Expand Down Expand Up @@ -864,9 +863,9 @@ public List<Javadoc> visitText(String node) {
node = node.stripLeading();
}

char[] textArr = node.toCharArray();
StringBuilder text = new StringBuilder();
for (char c : textArr) {
for (int i = 0; i < node.length(); i++) {
char c = node.charAt(i);
cursor++;
if (c == '\n') {
if (text.length() > 0) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -835,11 +835,10 @@ public J visitLiteral(LiteralTree node, Space fmt) {
List<J.Literal.UnicodeEscape> unicodeEscapes = null;

int i = 0;
char[] valueSourceArr = valueSource.toCharArray();
for (int j = 0; j < valueSourceArr.length; j++) {
char c = valueSourceArr[j];
if (c == '\\' && j < valueSourceArr.length - 1 && (j == 0 || valueSourceArr[j - 1] != '\\')) {
if (valueSourceArr[j + 1] == 'u' && j < valueSource.length() - 5) {
for (int j = 0; j < valueSource.length(); j++) {
char c = valueSource.charAt(j);
if (c == '\\' && j < valueSource.length() - 1 && (j == 0 || valueSource.charAt(j - 1) != '\\')) {
if (valueSource.charAt(j + 1) == 'u' && j < valueSource.length() - 5) {
String codePoint = valueSource.substring(j + 2, j + 6);
int codePointNumeric = Integer.parseInt(codePoint, 16);
if (codePointNumeric >= SURR_FIRST && codePointNumeric <= SURR_LAST) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -707,8 +707,9 @@ public J visitLiteral(Literal literal, PrintOutputCapture<P> p) {
}
}

char[] valueSourceArr = literal.getValueSource().toCharArray();
for (char c : valueSourceArr) {
String valueSource = literal.getValueSource();
for (int j = 0; j < valueSource.length(); j++) {
char c = valueSource.charAt(j);
p.append(c);
if (surrogate != null && surrogate.getValueSourceIndex() == ++i) {
while (surrogate != null && surrogate.getValueSourceIndex() == i) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,8 +438,10 @@ public Space visitSpace(Space space, Space.Location loc, PrintOutputCapture<P> p
List<Javadoc.LineBreak> lineBreaks = getCursor().getNearestMessage("JAVADOC_LINE_BREAKS");
Integer index = getCursor().getNearestMessage("JAVADOC_LINE_BREAK_INDEX");

if (lineBreaks != null && !lineBreaks.isEmpty() && index != null && space.getWhitespace().contains("\n")) {
for (char c : space.getWhitespace().toCharArray()) {
String whitespace = space.getWhitespace();
if (lineBreaks != null && !lineBreaks.isEmpty() && index != null && whitespace.contains("\n")) {
for (int i = 0; i < whitespace.length(); i++) {
char c = whitespace.charAt(i);
// The Space from a JavaDoc will not contain a CR because the JavaDoc parser
// filters out other new line characters. CRLF is detected through the source
// and only exists through LineBreaks.
Expand All @@ -452,7 +454,7 @@ public Space visitSpace(Space space, Space.Location loc, PrintOutputCapture<P> p
}
getCursor().putMessageOnFirstEnclosing(Javadoc.DocComment.class, "JAVADOC_LINE_BREAK_INDEX", index);
} else {
p.append(space.getWhitespace());
p.append(whitespace);
}
return space;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,8 @@ private String minimumLines(String whitespace, int min) {

private static int getNewLineCount(String whitespace) {
int newLineCount = 0;
for (char c : whitespace.toCharArray()) {
for (int i = 0; i < whitespace.length(); i++) {
char c = whitespace.charAt(i);
if (c == '\n') {
newLineCount++;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ private static String normalizeNewLines(String text, boolean useCrlf) {
return text;
}
StringBuilder normalized = new StringBuilder();
char[] charArray = text.toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (useCrlf && c == '\n' && (i == 0 || text.charAt(i - 1) != '\r')) {
normalized.append('\r').append('\n');
} else if (useCrlf || c != '\r') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,21 +83,20 @@ private String normalize(String text, boolean isComment) {
StringBuilder textBuilder = new StringBuilder();
int consecutiveSpaces = 0;
boolean inMargin = true;
char[] charArray = text.toCharArray();
outer:
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n' || c == '\r') {
inMargin = true;
consecutiveSpaces = 0;
textBuilder.append(c);
} else if (!inMargin) {
textBuilder.append(c);
} else if (style.getUseTabCharacter() && c == ' ' && (!isComment ||
(i + 1 < charArray.length && charArray[i + 1] != '*'))) {
(i + 1 < text.length() && text.charAt(i + 1) != '*'))) {
int j = i + 1;
for (; j < charArray.length && j < style.getTabSize(); j++) {
if (charArray[j] != ' ') {
for (; j < text.length() && j < style.getTabSize(); j++) {
if (text.charAt(j) != ' ') {
continue outer;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ public RemoveTrailingWhitespaceVisitor() {
public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, P p) {
String eof = cu.getEof().getWhitespace();
StringBuilder builder = new StringBuilder();
for (char c : eof.toCharArray()) {
for (int i = 0; i < eof.length(); i++) {
char c = eof.charAt(i);
if (c == '\n' || c == '\r') {
builder.appendCodePoint(c);
}
Expand All @@ -53,13 +54,13 @@ public J.CompilationUnit visitCompilationUnit(J.CompilationUnit cu, P p) {
@Override
public Space visitSpace(Space space, Space.Location loc, P p) {
Space s = space;
int lastNewline = s.getWhitespace().lastIndexOf('\n');
String whitespace = s.getWhitespace();
int lastNewline = whitespace.lastIndexOf('\n');
// Skip import prefixes, leave those up to OrderImports which better understands that domain
if (lastNewline > 0 && loc != Space.Location.IMPORT_PREFIX) {
StringBuilder ws = new StringBuilder();
char[] charArray = s.getWhitespace().toCharArray();
for (int i = 0; i < charArray.length; i++) {
char c = charArray[i];
for (int i = 0; i < whitespace.length(); i++) {
char c = whitespace.charAt(i);
if (i >= lastNewline) {
ws.append(c);
} else if (c == ',' || c == '\r' || c == '\n') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,8 @@ private Space indentTo(Space space, int column, Space.Location spaceLocation) {
private Comment indentComment(Comment comment, String priorSuffix, int column) {
if (comment instanceof TextComment) {
TextComment textComment = (TextComment) comment;
if (!textComment.getText().contains("\n")) {
String text = textComment.getText();
if (!text.contains("\n")) {
return comment;
}

Expand All @@ -489,9 +490,8 @@ private Comment indentComment(Comment comment, String priorSuffix, int column) {
String newMargin = indent(margin, shift);
if (textComment.isMultiline()) {
StringBuilder multiline = new StringBuilder();
char[] chars = textComment.getText().toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
multiline.append(c).append(newMargin);
i += margin.length();
Expand All @@ -504,12 +504,11 @@ private Comment indentComment(Comment comment, String priorSuffix, int column) {
} else if (shift < 0) {
if (textComment.isMultiline()) {
StringBuilder multiline = new StringBuilder();
char[] chars = textComment.getText().toCharArray();
for (int i = 0; i < chars.length; i++) {
char c = chars[i];
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '\n') {
multiline.append(c);
for (int j = 0; j < Math.abs(shift) && i+j+1 < chars.length && (chars[j + i + 1] == ' ' || chars[j + i + 1] == '\t'); j++) {
for (int j = 0; j < Math.abs(shift) && i+j+1 < text.length() && (text.charAt(j + i + 1) == ' ' || text.charAt(j + i + 1) == '\t'); j++) {
i++;
}
} else {
Expand Down Expand Up @@ -585,7 +584,8 @@ private int getLengthOfWhitespace(@Nullable String whitespace) {
}

int size = 0;
for (char c : whitespace.toCharArray()) {
for (int i = 0; i < whitespace.length(); i++) {
char c = whitespace.charAt(i);
size += c == '\t' ? style.getTabSize() : 1;
if (c == '\n' || c == '\r') {
size = 0;
Expand All @@ -604,7 +604,9 @@ private int forInitColumn() {

int column = 0;
boolean afterInitStart = false;
for (char c : alignTo.print(getCursor()).toCharArray()) {
String print = alignTo.print(getCursor());
for (int i = 0; i < print.length(); i++) {
char c = print.charAt(i);
if (c == '(') {
afterInitStart = true;
} else if (afterInitStart && !Character.isWhitespace(c)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -293,12 +293,11 @@ private static class FindLineFormatJavaVisitor extends JavaIsoVisitor<GeneralFor
@Override
public Space visitSpace(Space space, Space.Location loc, GeneralFormatStatistics stats) {
String prefix = space.getWhitespace();
char[] chars = prefix.toCharArray();

for (int i = 0; i < chars.length; i++) {
char c = chars[i];
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (c == '\n') {
if (i == 0 || chars[i - 1] != '\r') {
if (i == 0 || prefix.charAt(i - 1) != '\r') {
stats.linesWithLFNewLines++;
} else {
stats.linesWithCRLFNewLines++;
Expand Down Expand Up @@ -435,6 +434,7 @@ public J.MethodInvocation visitMethodInvocation(J.MethodInvocation m, IndentStat
}
if (m.getPadding().getSelect() != null) {
countIndents(m.getPadding().getSelect().getAfter().getWhitespace(), true, stats);
visit(m.getSelect(), stats);
}
visitContainer(m.getPadding().getTypeParameters(), JContainer.Location.TYPE_PARAMETERS, stats);

Expand All @@ -461,8 +461,8 @@ private void countIndents(String space, boolean isContinuation, IndentStatistics
int spaceIndent = 0;
int tabIndent = 0;
boolean mixed = false;
char[] chars = space.substring(ni).toCharArray();
for (char c : chars) {
for (int i = ni; i < space.length(); i++) {
char c = space.charAt(i);
if (c == ' ') {
if (tabIndent > 0) {
mixed = true;
Expand Down Expand Up @@ -843,11 +843,9 @@ private String longestCommonPrefix(String pkg, @Nullable String lcp) {
return pkg;
}

char[] p1 = pkg.toCharArray();
char[] p2 = lcp.toCharArray();
int i = 0;
for (; i < p1.length && i < p2.length; i++) {
if (p1[i] != p2[i]) {
for (; i < pkg.length() && i < lcp.length(); i++) {
if (pkg.charAt(i) != lcp.charAt(i)) {
break;
}
}
Expand Down

0 comments on commit 00edaff

Please sign in to comment.