1

So basically I have the array int[] i = {0,1,2,3,4,5,6,7,8,9};

I want the toString method to return [0, 1, 2, 3, 4] only.

How would I do this without creating a new array?

Kpower
  • 1,237
  • 3
  • 11
  • 19

3 Answers3

3

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

You can't override the toString() method for primitive arrays, so you have to wrap it

-- Note: --

Unfortunately, this will not compile for primitive int[] arrays (your example), only Object[] arrays. See this question for details

Community
  • 1
  • 1
torquestomp
  • 3,304
  • 19
  • 26
  • Added a note; Forgot one little detail – torquestomp Dec 12 '13 at 03:59
  • Yeah I just noticed that. The question offers a good way to fix that though so it's not a big deal. – Kpower Dec 12 '13 at 03:59
  • 1
    I'm in two minds if this falls under *"creating a new array"* ... +1 none the less... – MadProgrammer Dec 12 '13 at 04:00
  • Oh yeah that's true because it changes it to a list – Kpower Dec 12 '13 at 04:01
  • There's no copying going on here - `Arrays.asList`, `List.subList`, and `Ints.asList` (from the link) are all merely *views*, lazily-computed. So I don't think it does fall under "*creating a new array*" – torquestomp Dec 12 '13 at 04:03
  • A *view* is a way of taking one object and disguising it as another - for example, disguising an `int[]` as a `List`. Given the underlying `int[]`, one can define a wrapper class that implements `List`, and define the access methods appropriately. The wrapper merely references the `int[]` object, so the memory overhead is constant - nothing new is created, just a light-weight 'converter', so to speak, to translate from `List` speak to `int[]` speak – torquestomp Dec 12 '13 at 04:14
2

Given the fact that you only need to return a String, simply start with a StringBuilder and loop over the range...

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();
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
0

You can use Arrays.copyOf method to implement the function you wanted.

    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));

Or just Print it using the following code:

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

It prints out [0, 1, 2, 3, 4] in console.

Source code of copyOf method is as follows: (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;
}
Mengjun
  • 3,159
  • 1
  • 15
  • 21