Is it possible in Java to override 'toString' for an Objects array?

前端 未结 7 602
一整个雨季
一整个雨季 2020-11-28 12:00

Is it possible in Java to override a toString for an Objects array?

For example, let\'s say I created a simple class, User (it doesn\'t really matter wh

7条回答
  •  臣服心动
    2020-11-28 12:47

    You cannot do that. When you declare an array, then Java in fact creates a hidden object of type Array. It is a special kind of class (for example, it supports the index access [] operator) which normal code cannot directly access.

    If you wanted to override toString(), you would have to extend this class. But you cannot do it, since it is hidden.

    I think it is good to be it this way. If one could extend the Array class, then one could add all kinds of methods there. And when someone else manages this code, they see custom methods on arrays and they are "WTF... Is this C++ or what?".

提交回复
热议问题