Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why only char[] gets printed out as if with the toString method?

Why only the following works?

char [] indeed = new char []{'a','b'}; 
System.out.println(indeed);// ehy it's seems like toString has been overridden!

whereas all the others do not seem to have their toString overridden.

int [] indeed = new int []{3,3};
System.out.println(indeed); // does not work

Is anybody aware of why it works like that?

like image 541
Rollerball Avatar asked Mar 25 '23 04:03

Rollerball


1 Answers

PrintStream has special implementations for print/println for many types, but char[] is the only array type with a custom implementation.

Note: you can write(byte[]) as well.

I assume it is because this class is designed for printing char and byte and byte[] that a char[] seemed consistent.


It is a known issue that the toString() for arrays is inherited from Object and this is not very useful. Instead you have to find an appropriate helper methods to give you useful toString, equals and hashCode() (In Arrays) but there is also an Array class which is useful also.

I suggested that this be fixed in Java 7 and the rumour I got back was to fix arrays properly would be very complicated. In any case it won't be fixed in Java 8 either.

like image 168
Peter Lawrey Avatar answered Apr 06 '23 00:04

Peter Lawrey