HashCodeBuilder.reflectionHashCode : HashCodeBuilder « Apache Common « Java Tutorial






import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class MainClass {
    public static void main(String[] args) {
        MyClass one = new MyClass("Becker", 35);
        MyClass two = new MyClass("Becker", 35);
        MyClass three = new MyClass("Agassi", 33);

        System.out.println("One>>>" + one);
        System.out.println("Two>>>" + two);
        System.out.println("Three>>>" + three);

        System.out.println("one equals two? " + one.equals(two));
        System.out.println("one equals three? " + one.equals(three));

        System.out.println("One HashCode>>> " + one.hashCode());
        System.out.println("Two HashCode>>> " + two.hashCode());
        System.out.println("Three HashCode>>> " + three.hashCode());
    }
}

class MyClass {
    private String name = null;
    private int age = 0;

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

    public boolean equals(Object obj) {
        return EqualsBuilder.reflectionEquals(this, obj);
    }

    public String toString() {
        return ToStringBuilder.reflectionToString(this,
            ToStringStyle.MULTI_LINE_STYLE);
    }

    public int hashCode() {
        return HashCodeBuilder.reflectionHashCode(this);
    }
}
One>>>MyClass@743399[
  name=Becker
  age=35
]
Two>>>MyClass@1d8957f[
  name=Becker
  age=35
]
Three>>>MyClass@3ee284[
  name=Agassi
  age=33
]
one equals two? true
one equals three? false
One HashCode>>> 462213092
Two HashCode>>> 462213092
Three HashCode>>> -530629296
  Download:  CommonLangHashCodeBuilder.reflectionHashCode.zip( 200 k)








37.16.HashCodeBuilder
37.16.1.HashCode For String
37.16.2.HashCodeBuilder.reflectionHashCode
37.16.3.HashCode Builder
37.16.4.Custom HashCode Builder