Java Arrays::toString(Object[] v)の進化
今日はインタネットでjava.util.Arraysのソースを参考しました、 2007年くらいGNU Classpathのソースで、その時OpenJDKまだ誕生されません。 その中でtoString(Object[] v)の実装は以下です。
/**
* Returns a String representation of the argument array. Returns "null"
* if <code>a</code> is null.
* @param v the array to represent
* @return a String representing this array
* @since 1.5
*/
public static String toString(Object[] v)
{
if (v == null)
return "null";
StringBuilder b = new StringBuilder("[");
for (int i = 0; i < v.length; ++i)
{
if (i > 0)
b.append(", ");
b.append(v[i]);
}
b.append("]");
return b.toString();
}
OpenJDK 25のソースも参考して、同じメソッドだけれど以下ように実装されます。
/**
* Returns a string representation of the contents of the specified array.
* If the array contains other arrays as elements, they are converted to
* strings by the {@link Object#toString} method inherited from
* {@code Object}, which describes their <i>identities</i> rather than
* their contents.
*
* <p>The value returned by this method is equal to the value that would
* be returned by {@code Arrays.asList(a).toString()}, unless {@code a}
* is {@code null}, in which case {@code "null"} is returned.
*
* @param a the array whose string representation to return
* @return a string representation of {@code a}
* @see #deepToString(Object[])
* @since 1.5
*/
public static String toString(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
どちらも素晴らしいが、GUNのほうが分かりやすいと個人的に思います。