Make internal API null-safe and Javadoc.

This commit is contained in:
Gary Gregory 2020-07-01 17:21:55 -04:00
parent 954338a152
commit ad433ecc16
2 changed files with 14 additions and 10 deletions

View File

@ -299,20 +299,23 @@ public class CharSequenceUtils {
} }
/** /**
* Green implementation of toCharArray. * Converts the given CharSequence to a char[].
* *
* @param cs the {@code CharSequence} to be processed * @param source the {@code CharSequence} to be processed.
* @return the resulting char array * @return the resulting char array, never null.
* @since 3.11 * @since 3.11
*/ */
public static char[] toCharArray(final CharSequence cs) { public static char[] toCharArray(final CharSequence source) {
if (cs instanceof String) { final int len = StringUtils.length(source);
return ((String) cs).toCharArray(); if (len == 0) {
return ArrayUtils.EMPTY_CHAR_ARRAY;
} }
final int sz = cs.length(); if (source instanceof String) {
final char[] array = new char[cs.length()]; return ((String) source).toCharArray();
for (int i = 0; i < sz; i++) { }
array[i] = cs.charAt(i); final char[] array = new char[len];
for (int i = 0; i < len; i++) {
array[i] = source.charAt(i);
} }
return array; return array;
} }

View File

@ -186,6 +186,7 @@ public class CharSequenceUtilsTest {
final char[] expected = builder.toString().toCharArray(); final char[] expected = builder.toString().toCharArray();
assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder)); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder));
assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString())); assertArrayEquals(expected, CharSequenceUtils.toCharArray(builder.toString()));
assertArrayEquals(ArrayUtils.EMPTY_CHAR_ARRAY, CharSequenceUtils.toCharArray(null));
} }
static class WrapperString implements CharSequence { static class WrapperString implements CharSequence {