I'm just wondering, is it possible to override toString() method of class java.util.Arrays. I'm making a project on our class and I plan to output my arrays instead of
[33, 12, 98] to [033, 012, 098]
I'm just wondering if it is possible to do that without overriding Arrays.toString() method.
Thank you for your assistance :)
A string representation of an object can be obtained using the toString() method in Java. This method is overridden so that the object values can be returned.
toString(int[]) method returns a string representation of the contents of the specified int array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space).
You can't override the toString method of ArrayList 1.
Array classes are final : you cannot extend them and override their methods.
You can't override the Arrays.toString(). Instead you can write your own generic method by appending a leading 0, something like :
public static <T> String toString(T arr[]) {
return Arrays.stream(arr).map(s -> "0" + s).collect(Collectors.joining(", ", "[", "]"));
}
And simply call it :
Integer arr[] = {13, 14, 15};
System.out.println(toString(arr));
If you are dealing with a primitive data-type (assuming only an int
here), then the toString() would look like :
public static String toString(int arr[]) {
return Arrays.stream(arr).mapToObj(s -> "0" + s)
.collect(Collectors.joining(", ", "[", "]"));
}
As others already mentioned, it is not possible to overwrite Arrays.toString
. The solution is to write own code to create the string, for example so with Java 8 streams:
int[] array = { 33, 12, 98 };
String result =
Arrays.stream(array) // stream of ints
.boxed() // converted to Integers
.map(String::valueOf) // converted to String
.map(s -> StringUtils.leftPad(s, 3, "0")) // left-padded
.collect(Collectors.joining(", ", "[", "]")); // appended together with , as separator
Assert.assertEquals("[033, 012, 098]", result);
If you'd like a fixed-width field filled with leading zeros, you can use String.format()
with a format symbol like %03d
, using just standard Java libraries.
For example:
static String toString(int[] array) {
return Arrays.stream(array)
.mapToObj(i -> String.format("%03d", i)) // <-- Format
.collect(Collectors.joining(", ", "[", "]"));
}
With the input below, the result is [033, 012, 098, 123, 001].
public static void main(String[] args) {
int[] myarray = new int[] { 33, 12, 98, 123, 1 };
String s = toString(myarray);
System.out.println(s);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With