Program to demonstrate how to implement the hashCode and equals method using Apache Commons in Java.
In order to use below code, you have to get Apache's commons-lang jar.
Output of the program :
In order to use below code, you have to get Apache's commons-lang jar.
package com.hubberspot.apache.commons; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang.builder.EqualsBuilder; import org.apache.commons.lang.builder.HashCodeBuilder; public class Author { private int id; private String name; private List < String > books; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List < String > getBooks() { return books; } public void setBooks(List < String > books) { this.books = books; } @Override public int hashCode() { return new HashCodeBuilder() .append(id) .append(name) .append(books) .toHashCode(); } @Override public boolean equals(final Object object) { if(object instanceof Author){ final Author other = (Author) object; return new EqualsBuilder() .append(id, other.id) .append(name, other.name) .append(books, other.books) .isEquals(); } else { return false; } } public static void main(String[] args) { // Creating Author1 Author author1 = new Author(); author1.setId(1234); author1.setName("Martin Fowler"); List < string > books = new ArrayList < String >(); books.add("Code Refactoring in Java"); books.add("Java Design Patterns"); author1.setBooks(books); // Creating Author2 Author author2 = new Author(); author2.setId(1234); author2.setName("Martin Fowler"); books = new ArrayList < String >(); books.add("Code Refactoring in Java"); books.add("Java Design Patterns"); author2.setBooks(books); // Creating Author3 Author author3 = new Author(); author3.setId(1235); author3.setName("Steve Holzner"); books = new ArrayList < String >(); books.add("Design Patterns for Dummies"); books.add("Ajax for Dummies"); author3.setBooks(books); System.out.println("author1.hashCode() = " + author1.hashCode()); System.out.println("author2.hashCode() = " + author2.hashCode()); System.out.println("author1.equals(author2) = " + author1.equals(author2)); System.out.println("author1.hashCode() = " + author1.hashCode()); System.out.println("author3.hashCode() = " + author3.hashCode()); System.out.println("author1.equals(author3) = " + author1.equals(author3)); System.out.println("author2.hashCode() = " + author2.hashCode()); System.out.println("author3.hashCode() = " + author3.hashCode()); System.out.println("author2.equals(author3) = " + author2.equals(author3)); } }
Output of the program :