d4rk5un
d4rk5un

Reputation: 1

How to compare two objects by attribute using comparable - JAVA

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;
        }
    } 
}

Upvotes: 0

Views: 413

Answers (1)

Vishal Gajera
Vishal Gajera

Reputation: 4207

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

    }

}

Upvotes: 1

Related Questions