我有一個POJO,其中包含hashcode()
和equals()
方法,我已覆蓋,但我的查詢是,如果我如果我做hashcode()
方法評論然後在集合讓我說當我在一個哈希映射存儲用戶定義的對象,那麼它會產生什麼樣的影響......另一件事是,如果我將equals方法作爲註釋,那麼它會產生什麼影響如果我嘗試輸入重複記錄,它會將重複記錄存儲兩次!關於hashcode()和等於()
public class Employee {
String name,job;
int salary;
public Employee(String n , String j, int t)
{
this.name= n;
this.job=j;
this.salary= t;
}
/* @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((job == null) ? 0 : job.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + salary;
return result;
}*/
/*@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (job == null) {
if (other.job != null)
return false;
} else if (!job.equals(other.job))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (salary != other.salary)
return false;
return true;
}
*/
@Override
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
{
return true;
}
// make sure o can be cast to this class
if (obj == null || obj.getClass() != getClass())
{
// cannot cast
return false;
}
Employee e = (Employee) obj;
return this.name.equals(e.name)&&this.job.equals(e.job)&&this.salary==e.salary;
}
@Override
public String toString() {
return name+"\t" +"\t"+ job +"\t"+ salary;
}
}
您在討論'equals()'和'hasCode()'方法時**的影響**。您是否沒有注意到當您將它們交替註釋掉(或可能同時存在)時會發生什麼? – Lion 2012-04-15 18:43:46