Java面試寶典下載:http://download.csdn.net/source/3563084
Collection的兩個子介面Set和List,Set中的元素要求是不重複的,因此要重寫equals方法。而對於HashSet方法而言一定要重寫hashCode方法。
在向HahSet中添加元素時,沒添加一個元素要判斷這個元素是否已經存在,因此就涉及到了兩個執行個體對象的比較問題。
比較兩個執行個體對象是否相等的步驟:
(1)判斷hashCode的傳回值是否相同,如果不同,則不是同一個執行個體對象,可以添加進去;否則就進去第(2)步;
(2)判斷equals方法的傳回值是否為true,如果為true則相同,否則不同。
下面簡單實現了一下這兩個方法:
public class UserInfo {private String username;private String password;public UserInfo() {}public UserInfo(String _username, String _password) {this.username = _username;this.password = _password;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime*result + (username==null?0:username.hashCode());result = prime*result + (password==null?0:password.hashCode());return result;}@Overridepublic int equals(Object obj) {if(this == obj) {return true;}if(obj == null) {return false;}if(!(obj instanceof UserInfo)) {return false;}final UserInfo other = (UserInfo)obj;if(this.username == null) {if(other.getUsername() != null) {return false;}} else if(!this.username.equals(other.getUsername())) {return false;}if(this.password == null) {if(other.getPassword() != null) {return false;}} else if(!this.password.equals(other.getPassword())) {}return true;}//省去了對屬性的get和set方法}