Nuno Branco
Nuno Branco

Reputation: 21

How can I compare object with another object

I run the following

Choice choice1 = new Choice(0);
       Choice choice2 = new Choice(1);
       int result = choice1.compareWith(choice2);

       IO.outputln("Actual: " + result);

the compareWith method

public int compareWith(Choice anotherChoice)
    {

        int result=0;           
        if (anotherChoice==0||type==0)
            result=1;
        if (anotherChoice==1&&type==1)
        result=-11;
    }

The program said that i can not compare anotherchoice (choice class) with a integer. How can I do it.

Upvotes: 1

Views: 102

Answers (2)

Michael
Michael

Reputation: 44100

You should be implementing Comparable for this. You should also need to get the type value out of the Choice when you are comparing the values:

public class Choice implements Comparable<Choice>
{
    @Override
    public int compareTo(Choice that)
    {
        int result = 0;
        if (anotherChoice.type == 0 || type == 0)
            result = 1;
        if (anotherChoice.type == 1 && type == 1)
            result = -11; // should probably be -1

        return result;
    }
}

Upvotes: 1

Suresh Atta
Suresh Atta

Reputation: 121998

if (anotherChoice==0||type==0)

Since anotherChoice is an object you cannot directly compare with 0. You should actually check a field of that object. So your code should be

if (anotherChoice.type==0|| this.type==0)

Same for the other condition.

And another error is that you are not returning anything from your method. You should.

public int compareWith(Choice anotherChoice)
    {

        int result=0;           
        if (anotherChoice==0||type==0)
            result=1;
        if (anotherChoice==1&&type==1)
        result=-11;

       return result;
    }

Upvotes: 2

Related Questions