编写一个toString函数来返回数组的一部分而不是整个部分

时间:2013-12-12 03:53:45

标签: java

所以基本上我有阵列 int[] i = {0,1,2,3,4,5,6,7,8,9};

我想要返回toString方法 仅[0, 1, 2, 3, 4]

如果不创建新阵列,我该怎么做?

3 个答案:

答案 0 :(得分:3)

Arrays.asList(i).subList(0,5).toString()

您无法覆盖原始数组的toString()方法,因此必须将其包装

- 注意: -

不幸的是,这不会为原始int []数组(您的示例)编译,只能编译Object []数组。有关详细信息,请参阅this question

答案 1 :(得分:2)

鉴于您只需要返回String,只需从StringBuilder开始并循环播放范围......

StringBuilder sb = new StringBuilder(12);
for (int index = 0; index < Math.min(5, i.length); index++) {
    if (sb.length() > 0) {
        sb.append(", ");
    }
    sb.append(i[index]);
}
sb.insert(0, "[");
sb.append("]");

return sb.toString();

答案 2 :(得分:0)

您可以使用Arrays.copyOf方法来实现您想要的功能。

    int[] i = {0,1,2,3,4,5,6,7,8,9};

    //Copy first 5 elements
    int[] copy = Arrays.copyOf(i, 5);

    //Print [0, 1, 2, 3, 4]
    System.out.print(Arrays.toString(copy));

或者只需使用以下代码打印:

<强> System.out.print(Arrays.toString(Arrays.copyOf(i, 5)));

它在控制台中输出[0,1,2,3,4]。

copyOf方法的源代码如下:(JDK 1.6)

/**
 * Copies the specified array, truncating or padding with zeros (if necessary)
 * so the copy has the specified length.  For all indices that are
 * valid in both the original array and the copy, the two arrays will
 * contain identical values.  For any indices that are valid in the
 * copy but not the original, the copy will contain <tt>0</tt>.
 * Such indices will exist if and only if the specified length
 * is greater than that of the original array.
 *
 * @param original the array to be copied
 * @param newLength the length of the copy to be returned
 * @return a copy of the original array, truncated or padded with zeros
 *     to obtain the specified length
 * @throws NegativeArraySizeException if <tt>newLength</tt> is negative
 * @throws NullPointerException if <tt>original</tt> is null
 * @since 1.6
 */
public static int[] copyOf(int[] original, int newLength) {
    int[] copy = new int[newLength];
    System.arraycopy(original, 0, copy, 0,
                     Math.min(original.length, newLength));
    return copy;
}