简体   繁体   English

为Java的内置类轻松覆盖toString()

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

I have a simple program which processes an M x N matrix. 我有一个处理M×N矩阵的简单程序。 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. 我知道我可以编写一些方法,例如static [void / String] matrixPrint(int [] [] myMatrix)来打印矩阵或返回它的String表示。

However I'm thinking that a more elegant solution would be to override the toString() method in the Arrays class. 但是我认为更优雅的解决方案是覆盖Arrays类中的toString()方法。 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. 这样我就可以调用System.out.println(myMatrix),这在我看来比上面的任何一个都更清晰优雅。

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? 或者还有其他方法可以优雅地从Java的内置类中打印出对象吗?

You can't override array's toString() (it doesn't implement one). 你不能覆盖数组的toString() (它没有实现一个)。 But, you could use Arrays.deepToString(Object[]) which Returns a string representation of the "deep contents" of the specified array. 但是,您可以使用Arrays.deepToString(Object[]) ,它返回指定数组的“深层内容”的字符串表示形式。 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. Arrays类有许多用于打印数组的实用工具。 However they rely on you being happy with the default Java format for printing arrays. 但是,它们依赖于您对打印阵列的默认Java格式感到满意。 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. Java 8流提供了一些很好的功能,您可以使用它们而无需显式迭代。 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 Java没有扩展数组的语法,即你不能写

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

However, Arrays class provides a string conversion method that works with arrays of any type. 但是, Arrays类提供了一种字符串转换方法 ,可以处理任何类型的数组。 That is the idiomatic way of printing arrays in Java. 这是用Java打印数组的惯用方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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