之前学习java的时候,对于HashMap的使用只是停留在了最基本的阶段,好废话少说!
package com.zhukovasky.beans;
public class MyBean {
private String first;
private String second;
public MyBean(String first,String second){
this.first=first;
this.second=second;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((first == null) ? 0 : first.hashCode());
result = prime * result + ((second == null) ? 0 : second.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MyBean other = (MyBean) obj;
if (first == null) {
if (other.first != null)
return false;
} else if (!first.equals(other.first))
return false;
if (second == null) {
if (other.second != null)
return false;
} else if (!second.equals(other.second))
return false;
return true;
}
}
这个是我随便定义的一个类!
注意它的HashCode()生成方法是怎么计算的!
package com.zhukovasky.hashmap;
import com.zhukovasky.beans.MyBean;
public class HashMap {
public static void main(String[] args){
String s="s";
System.out.println(s.hashCode());
String s2="s";
System.out.println(s2.hashCode());
MyBean m1=new MyBean("s","t");
System.out.println(m1.hashCode());
MyBean m2=new MyBean("t","s");
System.out.println(m2.hashCode());
}
}
最后发现,显然s与s2的hashcode值是相等的,m1与m2的值是不等的!
也就是说s与s2是想等的。而m1与m2是不等的!尽管构造方法中两个元素的位置发生了变化!
那么为什么会出现这种情况!显然是HashCode()的计算方法有区别!