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...)
You can use an if statement, if it is within a immediately invoked function. Show activity on this post.
The if/else if statement allows you to create a chain of if statements. The if statements are evaluated in order until one of the if expressions is true or the end of the if/else if chain is reached. If the end of the if/else if chain is reached without a true expression, no code blocks are executed.
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
Type Casting in Java – An IntroductionType Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind of Object, and the process of conversion from one type to another is called Type Casting.
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With