Set集合实现有序


今天面试问到Set集合实现有序的问题,发现集合这部分知识要补一补.... 


以下所有api描述来源:https://docs.oracle.com/javase/7/docs/api/

实现Set接口的类如下,其中最常见的HashSet和TreeSet。

Interface Set<E>


其中,TreeSet的构造方法如下:

Constructor and Description
TreeSet()
Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet(Collection<? extends E> c)
Constructs a new tree set containing the elements in the specified collection, sorted according to the  natural ordering of its elements.
TreeSet(Comparator<? super E> comparator)
Constructs a new, empty tree set, sorted according to the specified comparator.
TreeSet(SortedSet<E> s)
Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.


TreeSet提供了一个参数为Colleciton的构造方法,利用提供的集合的所有元素进行自然排序后构造一个新的TreeSet集合。

该方法详细描述:

Constructs a new tree set containing the elements in the specified collection, sorted according to the  natural ordering of its elements. All elements inserted into the set must implement the  Comparable interface. Furthermore, all such elements must be  mutually comparablee1.compareTo(e2) must not throw a  ClassCastException for any elements  e1 and  e2 in the set.
Parameters:
c - collection whose elements will comprise the new set
Throws:
ClassCastException - if the elements in  c are not  Comparable, or are not mutually comparable
NullPointerException - if the specified collection is null

需要注意的是:1.所有插入set的元素都要实现Comparable接口,即可自然排序。

                        2.任意两个元素之间都是可以相互比较并且不会抛出类型转换异常,也就是类型一致。


综上,实现Set集合排序,可以通过直接使用TreeSet储存,或者将要实现排序的集合作为参数构造新TreeSet集合,得到的TreeSet集合就是有序集合了。


写个类测试一下...

假设现在有无序的HashSet集合装有若干Sort类型元素,要把元素按value值的大小排序。那么我在Sort类中实现Comparable接口,然后将该HashSet集合作为参数构造新的TreeSet即可得到有序的Set集合。

代码:

import java.util.HashSet;
import java.util.TreeSet;

public class Sort implements Comparable<Sort>{
	//排序依据
	private Integer value;
	//有参构造
	public Sort(Integer value){
		this.value = value;
	}
	
	@Override
	public int compareTo(Sort o) {
		//正序
		return this.value-o.value;
	}
	@Override
	public String toString() {
		return value+"";
	}
	
	public static void main(String[] args) {
		
		HashSet<Sort> set = new HashSet<Sort>();
		//生成数据
		for(int i=0; i<16; i+=2){
			set.add(new Sort(i));
		}
		//利用HashSet中的元素通过元素的自然排序构造一个新TreeSet
		TreeSet treeSet = new TreeSet(set);
		//打印结果
		System.out.println("HashSet:"+set);
		System.out.println("TreeSet:"+treeSet);
	}
}

控制台输出:

HashSet:[12, 4, 10, 8, 14, 0, 2, 6]
TreeSet:[0, 2, 4, 6, 8, 10, 12, 14]


  • 3
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值