简体   繁体   中英

Why can't I cast an object inside of an if statement?

I haven't seen this exact question here, which surprises me.

The following will not compile:

public int compareTo( Object o )
{
    if ( this.order < ((Category o).order) )
    {
      return -1;
    }
    else if ( this.order > ((Category o).order) ) 
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

Whereas changing this to cast the object and store its reference in a new object outside of the conditional statement fixes the issue:

Category cat = ( Category )o;
if ( this.order < cat.order )
// Etc...

My question is, why is this behavior not allowed in Java? (Java 5 specifically)

EDIT: Aha! Thank you all. Darn modern IDEs giving vague error messages. I've begun to discount them, which didn't do me any good this time. (Netbeans was warning me about both a missing parenthesis and a missing semicolon...)

The problem here is that your syntax is not right. It should be

public int compareTo( Object o )
{
    if ( this.order < ((Category) o).order )
    {
      return -1;
    }
    else if ( this.order > ((Category) o).order ) 
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

I prefer the syntax

Category.class.cast(o)

then you are explicit in what you are doing and it avoids any confusion with brackets. From my understanding the above is the same as ((Category) o)

This should be allowed, it seems as if your parenthesis may be off: have you tried something like

if ( this.order < (((Category)o).order) )

I think you need this:

(((Category) o).order)

I just tried a simpler version of what you have:

int a = 5;
        if(4 < (double)a);

and it compiled fine.

There is a distinct difference between the two code snippets you posted:

(Category o)

is different than:

( Category )o

This first will not compile, the second one will.

Have a look at simple working demo of casting within if :

int i;
float d = 10.5f;
if((i = (int) d) == 10){
//works
}

in your code problem is with if ( this.order < ((Category o).order) ) its incorrect statement

it should be if ( this.order < ((Category) o).order)

EDIT : Your problem solved but one thing more( extra topping ), no need to have else ( ladder form ) as you are having return within if

public int compareTo( Object o )
{
    if ( this.order < ((Category) o).order )
    {
        return -1;
    }
    if ( this.order > ((Category) o).order ) 
    {
        return 1;
    }
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM