"the implementation of compareTo methods of String, Integer, and Double classes are not compatible with each other and they throw ClassCastException when an object of one class is compared with an object of another class." this sentence in the explanation and actually the answer of the question, I strongly advice to add why they are not comparable to each other also. For example, Integer and Double are also not comparable when used together. The code group below would throw the same exception, too.
Object[] sa = { 100.1, 100.0, 100 };
Collections.sort(Arrays.asList(sa), null);
System.out.println(sa[0]+" "+sa[1]+" "+sa[2] );
Why is that exactly?
About Question enthuware.ocpjp.v21.2.1724 :
Moderator: admin
-
- Posts: 7
- Joined: Fri Feb 07, 2025 5:36 pm
- Contact:
-
- Site Admin
- Posts: 10396
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v21.2.1724 :
Because Integer's compareTo method tries to cast the argument to Integer. If you try to invoke the compareTo method on an Integer object and pass it a Double object, then casting it to Integer will cause a ClassCastException to be thrown. The same happens for other classes also.
-
- Posts: 2
- Joined: Fri May 09, 2025 1:38 am
- Contact:
Re: About Question enthuware.ocpjp.v21.2.1724 :
Could you please clarify if there’s any design reason why the compareTo methods in Integer and Double were not implemented to allow cross-type comparison, for example, Agario by using Number as a common interface?
-
- Site Admin
- Posts: 10396
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v21.2.1724 :
We can only guess. Double values are inherently different from integral values (read about how floating point arithmetic and how they are stored). So it does not make much sense to blindly compare a double value with an integral value. If the programmer still wants to compare the two values, they should first convert the values to one or the other type themselves and then compare.
Who is online
Users browsing this forum: No registered users and 4 guests