0

I'm getting a ClassCastException in the below code, which doesn't make much sense to me, as targetObject is a Comparable and current is a ToBeFound. Where are the Integer and String coming from?

ToBeFound origin = new ToBeFound();
public ToBeFound findWrapper(Comparable targetObject)
{
    return find(origin, targetObject);
}

private ToBeFound find(ToBeFound current, Comparable targetObject)
{
    if (current == null)
        {
        return null;
        }

    System.out.println(targetObject.compareTo(current.getValue()));
     // Exception in thread "main" java.lang.ClassCastException: 
     // java.lang.Integer cannot be cast to java.lang.String

    return new ToBeFound();
}

//body of main() that calls the methods
master.find( (Comparable) scanner.next()); 
   // Scanner is a java.util.Scanner scanning System.in
0

4 Answers 4

1

As compareTo javadoc states:

ClassCastException - if the specified object's type prevents it from being compared to this object.

It seems that your target is of a String type which is Comparable<String> and current.getValue() returns an object of Integer type.

You can try to do String.valueOf(current.getValue) if it works ok then I'm right. :)

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

Comments

0
private ToBeFound find(TreeNode current, Comparable targetObject)

Looks like current is a TreeNode...

1 Comment

Oh, no, sorry. That was part of the anonymoization of the code that I hadn't caught.
0
System.out.println(target.compareTo(current.getValue()));

Return type of compareTo is int, so you can convert your primitive int to String using

System.out.println(Integer.toString(target.compareTo(current.getValue())));

What is the type of target? Seems like you are comparing String against Integer.

Comments

0

If your sample code is reflects what you are actually running then:

System.out.println(target.compareTo(current.getValue()));
  1. Your code does not show the declaration for target, but the exception message implies that it must be String. (You show use the declaration for targetObject ... but that's not what the code is actually using!!)

  2. Your code doesn't show the declaration for the ToBeFound.getValue() method ... but the exception message implies that it must be Integer.

  3. The String.compareTo(Object) throws a CCE if the parameter object is not a String.

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.