Anonymous
Anonymous

Reputation: 25

ClassCastException in Java

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

Upvotes: 0

Views: 734

Answers (4)

Stephen C
Stephen C

Reputation: 718758

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.

Upvotes: 0

Piyush Mattoo
Piyush Mattoo

Reputation: 16105

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.

Upvotes: 0

lindsten
lindsten

Reputation: 88

private ToBeFound find(TreeNode current, Comparable targetObject)

Looks like current is a TreeNode...

Upvotes: 0

Alex Nikolaenkov
Alex Nikolaenkov

Reputation: 2545

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. :)

Upvotes: 1

Related Questions