标签:equals hashcode native object string
public native int hashCode();
public boolean equals(Object obj) {
return (this == obj);
}
因为有的时候equals方法比较复杂,我们如果通过hashcode方法已经说明两个对象不相等了就可以不用调用equals了
hashCode是个本地方法,返回的结果是对对象存储位置的一系列复杂运算;
而equals就是单纯的比较两个对象的地址值是否相等;public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String) anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
/**
* Returns a hash code for this string. The hash code for a
* <code>String</code> object is computed as
* <blockquote><pre>
* s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
* </pre></blockquote>
* using <code>int</code> arithmetic, where <code>s[i]</code> is the
* <i>i</i>th character of the string, <code>n</code> is the length of
* the string, and <code>^</code> indicates exponentiation.
* (The hash value of the empty string is zero.)
*
* @return a hash code value for this object.
*/
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
} String s1=new String("zhaoxudong");
String s2=new String("zhaoxudong");
String s3="zhaoxudong";
String s4="zhaoxudong";
System.out.println(s1==s2); //两个new出来的对象 s1 s2里面放的是两个不同对象的地址 自然不相等
System.out.println(s1==s3); //false 一个指向堆内存 一个指向常量池
System.out.println(s3==s4); //true 都在常量池中
System.out.println("##### ");
System.out.println(s1.equals(s2));//true
System.out.println(s1.hashCode());//s1.hashcode()等于s2.hashcode()等于s3.hashcode()
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
Set hashset=new HashSet();
hashset.add(s1);
hashset.add(s2);
Iterator it=hashset.iterator();
while(it.hasNext())
System.out.println(it.next()); //只打印出一个import java.util.HashSet;
import java.util.Set;
import java.util.Iterator;
public class hashCode
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add(new Student(1,"zhangsan"));
hs.add(new Student(2,"lisi"));
hs.add(new Student(3,"wangwu"));
hs.add(new Student(1,"zhangsan"));
Iterator it=hs.iterator();
while(it.hasNext())
System.out.println(it.next());
}
}
public class Student
{
int num;
String name;
Student(int num,String name)
{
this.num=num;
this.name=name;
}
public String toString()
{
return num+":"+name;
}
} public int hashCode()
{
return num*name.hashCode();
}
public boolean equals(Object o)
{
Student s=(Student)o;
return num==s.num && name.equals(s.name);
} 改完之后,就只有一个zhangsan了。
http://www.iteye.com/topic/257191
标签:equals hashcode native object string
原文地址:http://blog.csdn.net/dlf123321/article/details/40274355