熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

Apache Commons Lang之hashCode()、equals()

2022-06-13   來源: JSP教程 

  Apache Commons Lang提供一套生成hashCode()equals()和compareTo()的API簡單易用這個與toString()工具用法類似

  實現策略

  hashCode()

  通過HashCodeBuilder反射來生成這說明類的hashCode與類中所有的域都相關

  也可以通過HashCodeBuilder實例來制定生成

  equals()

  也有兩種生成方式與toString()hashCode()的生成策略類似

  compareTo()

  與以上都類似

  實例

  為了測試創佳兩個類 FooBar參看上篇文章分別通過兩種方式實現其hashCode()和equals()方法

  
public class Foo {
        private String name;
        private int age;
        private Bar bar;

        public Foo(String name int age) {
                thisname = name;
                thisage = age;
        }

        //省略getter/setter方法

}

  
public class Bar {
        private String name;

        public Bar(String name) {
                thisname = name;
        }

        //省略getter/setter方法

}

  實現hashCode()

  反射方式

           @Override
        public int hashCode() {
                return HashCodeBuilderreflectionHashCode(this);

        }

  制定方式

           @Override
        public int hashCode() {
                return new HashCodeBuilder( )
                                append(name)
                                append(age)
                                append(bar)
                                toHashCode();
        }

  實現equals()

  反射方式

           @Override
        public boolean equals(Object obj) {
                return EqualsBuilderreflectionEquals(this obj);
        }

  制定方式

           @Override
        public boolean equals(Object obj) {
                boolean flag = false;
                if (obj != null && FooclassisAssignableFrom(objgetClass())) {
                        Foo f = (Foo) obj;
                        flag = new EqualsBuilder()
                                        append(name fgetName())
                                        append(age fgetAge())
                                        append(bar fgetBar())isEquals();
                }
                return flag;
        }

  生成compareTo()

  當然實現compareTo()的前提是Foo類實現了Comparable接口否則沒啥意義

  反射實現

           public int compareTo(Object obj) {
                return CompareToBuilderreflectionCompare(this obj);

        }

  制定實現

           public int compareTo(Object obj) {
                int flag = ;
                if (obj != null && FooclassisAssignableFrom(objgetClass())) {
                        Foo f = (Foo) obj;
                        flag = new CompareToBuilder()
                                        append(name getName())
                                        append(age fgetAge())
                                        append(bar fgetBar())
                                        toComparison();
                }
                return flag;
        }

  EqualsBuilder不光可以比較對象還可以通過其對象來比較各種類型的數據包括數組


From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19465.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.