comparable是用来比较排序的,而equals用来两个对象是否相等,这两个区别很大吧?
如下一个HashSet要判断对象相等
public class HashCode和equals
{
public static void main(String[] args)
{
/*
* HashSet的add方法先比hashCode是否相等,如果相等再equals
*/
HashSet<Student> hs=new HashSet<Student>();
hs.add(new Student("张三"));
hs.add(new Student("李四"));
Iterator<Student> it=hs.iterator();//方法返回一个Interator实例,用接口来引用
//依次指向下一个看还有没有
while(it.hasNext())
{
//依次得到元素
System.out.println(it.next().name);
}
//使用增强for循环
for(Student stu:hs)
{
System.out.println(stu.name);
}
}
}
class Student
{
String name;
public Student(String name)
{
this.name=name;
}
//同时重写两个方法
// @Override
// public int hashCode()
// {
// return this.name.hashCode();
// }
// public boolean equals(Object obj)
// {
// // TODO Auto-generated method stub
// if (obj!=null&&obj instanceof Student)
// {
// Student p = (Student) obj;
// if(this.name.equals(p.name))
// {
// return true;
// }
// }
// return super.equals(obj);
// }
//以下是自动生成
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Student))
return false;
Student other = (Student) obj;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
}
还有个Comparable例子
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;
public class TreeSetTest
{
public static void main(String[] args)
{
Man s1=new Man(10);
Man s2=new Man(20);
Man s3=new Man(30);
TreeSet<Man> ts=new TreeSet<Man>(new ManComparator());
ts.add(s1);
ts.add(s2);
ts.add(s3);
Iterator<Man> it=ts.iterator();
while(it.hasNext())
{
System.out.println(it.next().sorce);
}
}
}
class Man
{
int sorce;
public Man(int sorce)
{
// TODO Auto-generated constructor stub
this.sorce=sorce;
}
}
//加入排序规则
class ManComparator implements Comparator
{
public int compare(Object o1, Object o2)
{
// TODO Auto-generated method stub
Man m1=(Man)o1;
Man m2=(Man)o2;
return m1.sorce-m2.sorce;
}
} |