We did they make the decision to not implement a toString
method for int[]
, but instead let it inherit the toString
method from Object
?
They did implement more reasonable toString
methods for arrays. They are located in the java.util.Arrays
class.
As for reasoning. I'm assuming by the overrides provided in the Arrays
class, that trying to implement a generic toString
for different types of arrays is either complex or impossible. The toString
method would have to know what type of array it was working on, and output the data approrpiately. For instance, Object[]
must use toString
on each element, while char[]
must output the character, and the numeric datatypes must be converted to a numeric string.
The methods in Arrays
get this for free, because the types are fixed due to the overrides.
I guess because of the following reasoning: how would they know how users would want to present their array? It might "array size: 10" or it might be "[x,y,z]".
They gave you a default, if you want to make it something else it is easy to do.
You can use apache's ToStringBuilder make it easier...
http://commons.apache.org/lang/api/org/apache/commons/lang/builder/ToStringBuilder.html
My guess would be is that because Array objects weren't created in Java source code by the language designers - they are created by the Java compiler. Remember, you can have an array of any object type and so the compiler creates the Array object as appropriate for the type you require.
If they were to create a standard method, it's not immediately obvious how this should work. For example, executing toString()
and concatenating the results might be OK for a small array but it doesn't work for a multidimensional array or an array with 1,000 entries. So I think no toString()
method is created to keep all arrays consistent.
Admittedly, it is annoying and sometimes I do think something along the lines of "Array[" + size + "] of " + getClassName()
would be so much better than the default.
A bit of guesswork here, but...
There isn't an obvious string representation of an int array. People do it in different ways: comma separated, space separated, enclose in brackets or parentheses or nothing. That probably drove the decision not to implement it in Java 1.1, along with it being low priority code (since anyone can implement a method to write an array as a string themselves very simply).
Now you can't upgrade it in Java 1.2 or later because that would break back compatibility for anyone already using the old behaviour. You can however add a utility class that implements some functionality, and that's what they did with java.util.Arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With