Java比较2个类对象

时间:2016-11-02 15:58:42

标签: java class

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() {

    }
}

这是我的代码,我想比较2个眼镜,比如我初始化一个对象glasses1(ray-ban,200,平方)和glasses2(中国,100,圆形),我希望它们进行比较。我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

您可以从Object类中覆盖方法equals(Object),如果它们相等则返回boolean(您可以在此方法中自己定义需要等于将这些实例定义为相等)。

如果您希望类可以对排序后的地图进行排序,那么您可以实现接口Comparable和方法int compare(Object)

例如:

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

compare方法的实施是错误的,因为当眼镜对象较小时,我不知道你的逻辑。或者更大的'比其他眼镜对象。也许你只需要equals方法?

增加: equals方法可以做得稍微小一些,但可能有点难以理解(取决于事实,如果你知道"?" -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;
    }