gogoWebsite

Rewrite the equals and hashcode methods of entity classes to determine the uniqueness of objects

Updated to 17 days ago

Rewrite the equals and hashcode methods of entity classes to determine the uniqueness of objects

1. Introduction

Introduction: In daily project development, we need to determine whether the entity class objects are equal, or we need to store the entity class objects in the set to remove duplicate objects. At this time, we need to rewrite the entity class hashcode and equals methods according to the specific properties of the entity class according to our project needs.

Case:

In the entity class QuestionCharpterDto, I need to judge the entity class's unique object based on the chapter id and chapter type, and directly generate the hashcode and equals methods of the entity class through the development software.

public class QuestionCharpterDto implements Serializable{
	 /**
	  *
	  */
	 private static final long serialVersionUID = 1L;
	
	 /**
	  * Product ID
	  */
	 private Integer goodsId;
	
	 /**
	  * Product question bank id
	  */
	 private Integer qbid;
	
	 /**
	  * Product question bank chapter id
	  */
	 private Integer charpterId;
	
	 /**
	  * Product question bank chapter type
	  */
	 private Integer charpterType;
	
	 /**
	  * Product question bank chapter name
	  */
	 private String charpterTitle;
	
	 @Override
	 public boolean equals(Object obj) {
		 if (this == obj)
			 return true;
		 if (obj == null)
			 return false;
		 if (getClass() != ())
			 return false;
		 QuestionCharpterDto other = (QuestionCharpterDto) obj;
		 if (charpterId == null) {
			 if ( != null)
				 return false;
		 } else if (!())
			 return false;
		 if (charpterType == null) {
			 if ( != null)
				 return false;
		 } else if (!())
			 return false;
		 return true;
	 }
	
	 @Override
	 public int hashCode() {
		 final int prime = 31;
		 int result = 1;
		 result = prime * result + ((charpterId == null) ? 0 : ());
		 result = prime * result + ((charpterType == null) ? 0 : ());
		 return result;
	 }
	
 }

2. Introduction to the development specifications of hashcode and equals methods of Alibaba development manual

1) As long as equals is rewritten, hashCode must be rewritten.

2) Because Set stores non-duplicate objects, and judges based on hashCode and equals, the objects stored in Set must override these two methods.

3) If the custom object is used as the key to the Map, then hashCode and equals must be overridden.

Note: String rewrites hashCode and equals methods, so we can use String objects very happily as keys