Apache Commons Lang之hashCode()、equals()和compareTo()
 
Apache Commons Lang提供一套生成hashCode()、equals()和compareTo()的API,简单易用。这个与toString()工具用法类似。
 
一、实现策略
 
1、hashCode()
通过HashCodeBuilder反射来生成,这说明类的hashCode与类中所有的域都相关。
也可以通过HashCodeBuilder实例来制定生成。
 
2、equals()
也有两种生成方式,与toString()、hashCode()的生成策略类似。
 
3、compareTo()
与以上都类似。
 
二、实例
 
为了测试,创佳两个类 Foo、Bar,参看上篇文章,分别通过两种方式实现其hashCode()和equals()方法
 
public class Foo {
        private String name;
        private int age;
        private Bar bar;

        public Foo(String name, int age) {
                this.name = name;
                this.age = age;
        }

        //省略getter/setter方法

}
 
public class Bar {
        private String name;

        public Bar(String name) {
                this.name = name;
        }

        //省略getter/setter方法

}
 
1、实现hashCode()
 
反射方式
        @Override
        public int hashCode() {
                return HashCodeBuilder.reflectionHashCode(this);

        }
 
制定方式
        @Override
        public int hashCode() {
                return new HashCodeBuilder(17, 37)
                                .append(name)
                                .append(age)
                                .append(bar)
                                .toHashCode();
        }
 
2、实现equals()
 
反射方式
        @Override
        public boolean equals(Object obj) {
                return EqualsBuilder.reflectionEquals(this, obj);
        }
 
制定方式
 
        @Override
        public boolean equals(Object obj) {
                boolean flag = false;
                if (obj != null && Foo.class.isAssignableFrom(obj.getClass())) {
                        Foo f = (Foo) obj;
                        flag = new EqualsBuilder()
                                        .append(name, f.getName())
                                        .append(age, f.getAge())
                                        .append(bar, f.getBar()).isEquals();
                }
                return flag;
        }
 
3、生成compareTo()
当然,实现compareTo()的前提是Foo类实现了Comparable接口。否则没啥意义。
 
反射实现
        public int compareTo(Object obj) {
                return CompareToBuilder.reflectionCompare(this, obj);

        }
 
制定实现
        public int compareTo(Object obj) {
                int flag = -1;
                if (obj != null && Foo.class.isAssignableFrom(obj.getClass())) {
                        Foo f = (Foo) obj;
                        flag = new CompareToBuilder()
                                        .append(name, getName())
                                        .append(age, f.getAge())
                                        .append(bar, f.getBar())
                                        .toComparison();
                }
                return flag;
        }
 
 
很好,很强大!
 
EqualsBuilder不光可以比较对象,还可以通过其对象来比较各种类型的数据。包括数组。