HashSet存储自定义集合及排序问题
因为HashSet集合没有排序功能,故需要借其它集合完成,一般借助于TreeSet完成(List集完成给HashSet排序正在研究中)。
过程如下:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
public class HashSetSummarize {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
operateObject();
}
public static void operateObject()
{
Prisoner prisoner1 = new Prisoner("xiashengbing", 32, 13.7);
Prisoner prisoner2 = new Prisoner("lifenghong", 35, 3.5);
Prisoner prisoner3 = new Prisoner("yangwei", 29, 10.2);
Prisoner prisoner4 = new Prisoner("dongyuxing", 21, 1);
Prisoner prisoner5 = new Prisoner("qingshan", 38, 6.5);
Prisoner prisoner6 = new Prisoner("lifenghong", 35, 3.5);
HashSet<Prisoner> hashSet = new HashSet<Prisoner>();
hashSet.add(prisoner1);
hashSet.add(prisoner2);
hashSet.add(prisoner3);
hashSet.add(prisoner4);
hashSet.add(prisoner5);
hashSet.add(prisoner6);
printSet(hashSet);
System.out.println("*************************************************************");
/*
* 如下为利用TreeSet集合以name排序输出,必须是在HashSet内实现Comparable接口
*/
TreeSet<Prisoner> treeSet = new TreeSet<Prisoner>(hashSet);
printSet(treeSet);
}
public static void printSet(Set<Prisoner> set)
{
for (Iterator<Prisoner> iterator = set.iterator(); iterator.hasNext();) {
Prisoner prisoner = iterator.next();
System.out.println(prisoner);
}
}
}
看如下关键部分:
import cn.itcast.list.Person;
public class Prisoner extends Person implements Comparable<Prisoner>
{
private double sentenceDate;
public Prisoner(String name, int age, double sentenceDate) {
// TODO Auto-generated constructor stub
super(name, age);
this.setSentenceDate(sentenceDate);
}
@Override
public int compareTo(Prisoner o)
{
int num = this.getName().compareTo(o.getName());
if(num == 0)
{
return new Integer(this.getAge()).compareTo(new Integer(o.getAge()));
}
return num;
}
public int hashCode()
{
int hashCode = this.getName().hashCode() + this.getAge() * 31;
return hashCode;
}
public boolean equals(Object object)
{
Prisoner prisoner = null;
if(object instanceof Prisoner)
{
prisoner = (Prisoner)object;
}
return (this.getName().equals(prisoner.getName()) && this.getAge() == prisoner.getAge() &&
this.getSentenceDate() == this.getSentenceDate());
}
public void setSentenceDate(double sentenceDate) {
this.sentenceDate = sentenceDate;
}
public double getSentenceDate() {
return sentenceDate;
}
public String toString(){
return this.getName()+"::"+this.getAge()+"::"+ this.sentenceDate;
}
}