4

    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?

4
  • 1
    Integer is not a string Commented Jan 23, 2020 at 17:28
  • 1
    String intAsString = Integer.toString(someInt); Commented Jan 23, 2020 at 17:29
  • 1
    return ("" + super.getValue()).compareTo("" + item.getValue()); Commented Jan 23, 2020 at 17:29
  • Thank you. It's working. Could you tell me why here we are using an empty string? Commented Jan 23, 2020 at 17:41

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Good explanation.
Integer.parseInt() converts a String to an Integer not an Integer to a String.
@ChadNC Good catch! Not sure how I reversed that, but it's fixed now. Thanks!
4

You should use a method such as parseInt()

For example:

int xInteger = Integer.parseInt(someString);

The reason you receive the exception you do is because there is no parent to child relationship between the Integer class and the String class.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.