Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix NullPointerException hazard in StringUtils.join(..) method #3983

Merged
merged 1 commit into from
Sep 14, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -344,44 +344,4 @@ public interface StringFormatter<T> {
String format(T obj);
}

public static <T> String join(Collection<T> collection, String separator) {
return join(collection, separator, new StringFormatter<T>() {
@Override
public String format(T obj) {
return obj.toString();
}
});
}

public static <T> String join(Collection<T> collection, String separator,
StringFormatter<T> formatter) {
Iterator<T> iterator = collection.iterator();
// handle null, zero and one elements before building a buffer
if (iterator == null) {
return null;
}
if (!iterator.hasNext()) {
return EMPTY;
}
T first = iterator.next();
if (!iterator.hasNext()) {
return first == null ? "" : formatter.format(first);
}

// two or more elements
StringBuilder buf = new StringBuilder(256); // Java default is 16, probably too small
if (first != null) {
buf.append(formatter.format(first));
}

while (iterator.hasNext()) {
buf.append(separator);
T obj = iterator.next();
if (obj != null) {
buf.append(formatter.format(obj));
}
}

return buf.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,6 @@ public void testIsNumeric() {
Assert.assertTrue(StringUtils.isNumeric("1"));
}

@Test
public void testJoin() {
Assert.assertEquals("", StringUtils.join(new ArrayList(), "1a 2b 3c"));

ArrayList collection = new ArrayList();
collection.add(null);
Assert.assertEquals("", StringUtils.join(collection, "1a 2b 3c"));

collection = new ArrayList();
collection.add(-2_147_483_648);
Assert.assertEquals("-2147483648", StringUtils.join(collection, "1a 2b 3c"));
}

@Test
public void testStartsWithIgnoreCase() {
Assert.assertFalse(StringUtils.startsWithIgnoreCase("A1B2C3", "BAZ"));
Expand Down