简体   繁体   中英

Easily overriding toString() for Java's built-in classes

I have a simple program which processes an M x N matrix. When done processing, I want to print out the matrix to standard output. I'm aware that I can write some method eg static [void/String] matrixPrint(int[][] myMatrix) to either print out the matrix or return a String representation of it.

However I'm thinking that a more elegant solution would be to override the toString() method in the Arrays class. That way I could just call System.out.println(myMatrix), which seems to me to be more clear and elegant code than either of the above.

Is there an easy way to do this without creating another class that extends Arrays? Or are there other ways to elegantly print out objects from Java's built-in classes?

You can't override array's toString() (it doesn't implement one). But, you could use Arrays.deepToString(Object[]) which Returns a string representation of the "deep contents" of the specified array. If the array contains other arrays as elements, the string representation contains their contents and so on. This method is designed for converting multidimensional arrays to strings.

That might look like,

System.out.println(Arrays.deepToString(myMatrix));

The Arrays class has a number of useful utilities for printing arrays. However they rely on you being happy with the default Java format for printing arrays. If you want to do anything specific you will need to write your own methods.

Java 8 streams provide some nice features that you could use without needing explicit iteration. For example:

Arrays.stream(matrix)
    .map(row -> Arrays.stream(row).collect(Collectors.joining("\t"))
    .forEach(System.out::println);

Short answer is "no".

In order to override a method you need to extend a class. Java does not have a syntax for extending an array, ie you cannot write

class MyClass extends String[] { // <<= This will not compile
    ...
}

However, Arrays class provides a string conversion method that works with arrays of any type. That is the idiomatic way of printing arrays in Java.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM