0

I wish to compare two Die object by "int value" , and return the object with the higher value. What am I doing wrong ... Thanks

public class Die implements DieIntf , Comparable {

    private int value;

    public Die(){}

class ComparatorId implements Comparator<Die> {

        @Override
        public int compare(Die t, Die t1) {
               Integer d1 = t.getValue();
               Integer d2 = t.getValue();
               if(d1>d2) return 1;
               else if(d1<d2) return -1;
               else return 0;
        }
    } 
}
2
  • 2
    it looks like minor mistake, use Integer d2 = t1.getValue() not t.getValue() Commented Dec 13, 2015 at 16:16
  • Also, you haven't override compareTo(...) because of Comparable interface you have been implemented. can you make your code too clear rather than mess up all in one. Commented Dec 13, 2015 at 16:19

1 Answer 1

1

Do not use Comparable/Comparator interface, until you have any requirement like sorting an object into ascending/descending order.

In your case, you want Bigger Object(based upon it's value) return while compare it.

So do something likewise,

public class Die{

    int value;


    public Die compareMyDieObjce(Die d){

        if(this.value > d.value){
            return this;
        }

        return d;

    }

    @Override
    public String toString() {
        return " Object-Value : " + this.value;
    }

    public static void main(String[] args) {

        Die d1 = new Die(); d1.value = 5;
        Die d2 = new Die(); d2.value = 55;

        System.out.println(d1.compareMyDieObjce(d2)); // Object-Value : 55

    }

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

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.