Robert Vlasiu Robert Vlasiu - 1 month ago 14
Java Question

Java Compare 2 class objects

public class Glasses {
String manufacturer;
int price;
String type;
Glasses(){
}
Glasses(String prd, int pr)
{
manufacturer = prd;
price = pr;

}
Glasses(String prd, int pr, String t)
{
manufacturer = prd;
price = pr;
type = t;

}

public static void Compare()
{

}
}


this is my code and i want to compare 2 glasses like i initialise an object glasses1(ray-ban,200,squared) and glasses2(china,100,rounded) and I want them to be compared. How can i do that?

Answer

You can overwrite the method equals(Object) from class Object which returns the boolean if they are equal (you can define by yourself within this method what needs to be equal to define these instances as equal).

If you want the classes to be sortable for sorted map then you can implement the interface Comparable and the method int compare(Object).

For instance:

@Override
public int compareTo(Glasses other) {
    if (equals(other)) {
        return 0;
    } else {
        //FIXME: when is a Glasses object smaller then an other Glasses object??
        return 0;
    }
}

@Override
public boolean equals(Object o) {
    boolean equal = false;
    if (o instanceof Glasses) {
        Glasses other = (Glasses) o;
        equal = true;
        equal &= (manufacturer == null && other.manufacturer == null) || (manufacturer != null && manufacturer.equals(other.manufacturer));
        equal &= price == other.price;
        equal &= (type == null && other.type == null) || (type != null && type.equals(other.type));
    }
    return equal;
}

The implementation of the compare method is buggy because I don't know your logic when a Glasses object is 'smaller' or 'bigger' than an other Glasses object. Maybe you just need the equals method?

Addition: The equals method can be made a little bit smaller but maybe a little bit harder to understand (depends on the fact if you know the handling of the "?"-operator):

    @Override
    public boolean equals(Object o) {
        boolean equal = false;
        if (o instanceof Glasses) {
            Glasses other = (Glasses) o;
            equal = true;
            equal &= manufacturer == null ? other.manufacturer == null : manufacturer.equals(other.manufacturer);
            equal &= price == other.price;
            equal &= type == null ? other.type == null : type.equals(other.type);
        }
        return equal;
    }