Java 集合 之 HashSet TreeSet

时间:2021-01-20 17:56:17

http://www.verejava.com/?id=1699456395143

//        注意: 
//	1. HashSet 不保证数据顺序, 也就是说是无序的     TreeSet 有序 
//	2. HashSet 可以添加null 
//	3. HashSet 不能添加重复元素 


package com.set;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TestHashSet
{
	public static void main(String[] args)
	{
		
		//Set set=new TreeSet();
                Set set=new HashSet();
		set.add(new Ticket("a",300));
		set.add(new Ticket("a",100));
		set.add(new Ticket("a",200));
		set.add(new Ticket("a",200));
		
		Iterator iter=set.iterator();
		while(iter.hasNext())
		{
			Object obj=iter.next();
			System.out.print(obj+",");
		}
		System.out.println("");
		Object[] objs=set.toArray();
		for(int i=0;i<objs.length;i++)
		{
			Object obj=objs[i];
			System.out.print(obj+",");
		}
	}
}





package com.set;

public class Ticket implements Comparable
{
	private String name;
	private double price;
	public Ticket(String name, double price)
	{
		super();
		this.name = name;
		this.price = price;
	}
	public String getName()
	{
		return name;
	}
	public void setName(String name)
	{
		this.name = name;
	}
	public double getPrice()
	{
		return price;
	}
	public void setPrice(double price)
	{
		this.price = price;
	}
	
	public String toString()
	{
		return name+","+price;
	}
	

	
	@Override
	public int compareTo(Object o)
	{
		Ticket t=(Ticket)o;
		if(price>t.getPrice())
		{
			return 1;
		}else if(price<t.getPrice())
		{
			return -1;
		}
		return 0;
	}
	
	
}


http://www.verejava.com/?id=1699456395143