Jomarie Cajes
Jomarie Cajes

Reputation: 103

Overriding Arrays.toString() Method

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

Upvotes: 5

Views: 2182

Answers (3)

Michal
Michal

Reputation: 2423

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

Upvotes: 4

Nicholas K
Nicholas K

Reputation: 15443

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(", ", "[", "]"));
}

Upvotes: 9

Andy Thomas
Andy Thomas

Reputation: 86509

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

Upvotes: 3

Related Questions