原始碼閱讀之Strings
阿新 • • 發佈:2018-12-20
建議:repeat [自己先實現一個,然後對比一下guava的實現]
注意google工程師使如何使用StringBuilder這個類的
public static String repeat(String string, int count) { Preconditions.checkNotNull(string); if (count <= 1) { Preconditions.checkArgument(count >= 0, "invalid count: %s", count); return count == 0 ? "" : string; } else { int len = string.length(); long longSize = (long)len * (long)count; int size = (int)longSize; if ((long)size != longSize) { throw new ArrayIndexOutOfBoundsException("Required array size too large: " + longSize); } else { char[] array = new char[size]; string.getChars(0, len, array, 0); int n; for(n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); return new String(array); } } }
如果讓自己寫的話,也就是for迴圈用StringBuilder累加一下就完事了,看guava的程式碼,確實魯棒性要高的太多,自己想到的問題和沒想到的問題別人都想到了。
把count <=1 的情況分裂出來,不僅避免了引數錯誤問題,也避免浪費一點點效能。
實現的時候用了一個數組取複製成陣列,比StringBuilder要快
其他幾個方法
public static String padEnd(String string, int minLength, char padChar)
返回一個長度至少為minLength的字串,該字串由附加了儘可能多的padChar副本的字串組成,以達到該長度。
public static String padStart(String string, int minLength, char padChar)
返回一個長度至少為minLength的字串,該字串由字串組成,字串前面加上達到該長度所需的儘可能多的padChar副本。
public static String nullToEmpty(@Nullable String string) { return string == null ? "" : string; }
public static String emptyToNull(@Nullable String string) { return isNullOrEmpty(string) ? null : string; } public static boolean isNullOrEmpty(@Nullable String string) { return Platform.stringIsNullOrEmpty(string); }