public int compareTo(ListItem item) {
if(item!=null) {
return ((String) super.getValue()).compareTo((String) item.getValue());
}
My program is based on the Abstract class concept.
How can I resolve this
java.lang.ClassCastException:
in my program?
Casting in Java doesn't magically convert data from one type to another. Rather, it tells Java that the object stored in a variable actually is some other type, which is useful when dealing with inheritance or interfaces. See this StackOverflow question for more details.
In this case, the value you get from item.getValue()
is an Integer. Trying to cast to a String does not, and can not, work, because it's not a String. It really is an Integer, and trying to call String methods on it won't work.
As others have mentioned, you can convert the Integer to a String using Integer.toString(someInteger)
. However, since you're doing a comparison, you should probably just compare the values as Integers.