HashSet存储自定义集合及排序问题

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;
	}
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值