前几天在一个前辈的博客中看到Set集合的hashcode与equals解析.
hashcode产生一个哈希码,相当于数组的下标,通过下标查找到值.
Set添加元素的时候,首先调用hashcode定位元素位置,如果该位置上有元素,就调用equals方法比较俩个元素的值是否相等,如果相等则返回,不相等则添加到该位置上.
测试程序:
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setName("s1");
Student s2=new Student();
s2.setName("s2");
Student s3=new Student();
s3.setName("s3");
Set studentSet=new HashSet();
studentSet.add(s1);
System.out.println("========s1=======");
studentSet.add(s2);
System.out.println("========s2=======");
studentSet.add(s3);
System.out.println("========s3=======");
System.out.println(studentSet.contains(s3));
}
}
测试类:
import java.util.*;
public class Student implements Comparable<Student>
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public int compareTo(Student s)
{
return 0;
}
public int hashCode()
{
System.out.println("=========hashcode========");
return 5;
}
public boolean equals(Object obj)
{
System.out.println("===========equals=============");
Student s=(Student)obj;
return s.name.equals(this.name);
}
}
hashcode产生一个哈希码,相当于数组的下标,通过下标查找到值.
Set添加元素的时候,首先调用hashcode定位元素位置,如果该位置上有元素,就调用equals方法比较俩个元素的值是否相等,如果相等则返回,不相等则添加到该位置上.
测试程序:
import java.util.*;
public class SetTest
{
public static void main(String[] args)
{
Student s1=new Student();
s1.setName("s1");
Student s2=new Student();
s2.setName("s2");
Student s3=new Student();
s3.setName("s3");
Set studentSet=new HashSet();
studentSet.add(s1);
System.out.println("========s1=======");
studentSet.add(s2);
System.out.println("========s2=======");
studentSet.add(s3);
System.out.println("========s3=======");
System.out.println(studentSet.contains(s3));
}
}
测试类:
import java.util.*;
public class Student implements Comparable<Student>
{
private String name;
public void setName(String name)
{
this.name=name;
}
public String getName()
{
return name;
}
public int compareTo(Student s)
{
return 0;
}
public int hashCode()
{
System.out.println("=========hashcode========");
return 5;
}
public boolean equals(Object obj)
{
System.out.println("===========equals=============");
Student s=(Student)obj;
return s.name.equals(this.name);
}
}