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

南楼画角 提交于 2019-11-26 22:41:19

No. Of course you can create a static method User.toString( User[] ), but it won't be called implicitly.

You can use Arrays.toString(Object[] a); which will call the toString() method on each object in the array.

Edit (from comment):

I understand what it is you're trying to achieve, but Java doesn't support that at this time.

In Java, arrays are objects that are dynamically created and may be assigned to variables of type Object. All methods of class Object may be invoked on an array. See JLS Ch10

When you invoke toString() on an object it returns a string that "textually represents" the object. Because an array is an instance of Object that is why you only get the name of the class, the @ and a hex value. See Object#toString

The Arrays.toString() method returns the equivalent of the array as a list, which is iterated over and toString() called on each object in the list.

So while you won't be able to do System.out.println(userList); you can do System.out.println(Arrays.toString(userList); which will essentially achieve the same thing.

Jeroen

You can create a separate class containing the array, and override toString().

I think the simplest solution is to extend the ArrayList class, and just override toString() (for example, UserArrayList).

Peter Lawrey

The only way you can do this is to re-compile Object.toString() and add instanceof clauses.

I had requested a change in Project Coin to handle arrays in a more object orientated way. I felt that it's too much for beginners to learn all the functionality you need in Array, Arrays and 7 other helper classes which are commonly used.

I think in the end it was concluded that to make arrays properly object orientated is a non-trivial task which will be pushed back to Java 9 or beyond.

Stan Fad

Try this

User[] array = new User[2];
System.out.println(Arrays.asList(array));

of course if you have customized user.toString() method

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?".

Anton

Well, you can try to wrap all calls to Object.toString with an AspectJ around advice and return the desired output for arrays. However, I don't think it's a good solution :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!