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?
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?
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
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();
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;
}