Set集合实现有序

Set集合实现有序今天面试问到Set集合实现有序的问题,发现集合这部分知识要补一补…. 以下所有api描述来源:https://docs.oracle.com/javase/7/docs/api/实现Set接口的类如下,其中最常见的HashSet和TreeSet。InterfaceSet<E>AllKnownImplementingClasses:AbstractSet, Concurren…

大家好,又见面了,我是你们的朋友全栈君。

今天面试问到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 comparable
e1.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]

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/140023.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 用python画爱心-怎么用python实现画爱心

    用python画爱心-怎么用python实现画爱心Python中可以使用turtle库来画图,通过控制画笔运动来实现在画布上画图案。使用Python画爱心代码如下:#!/usr/bin/envpython#-*-coding:utf-8-*-importturtleimporttime#画心形圆弧defhart_arc():foriinrange(200):turtle.right(1)turtle.forward(2)de…

    2022年9月7日
    0
  • R语言差异检验:t检验「建议收藏」

    R语言差异检验:t检验「建议收藏」文章目录@[toc]单样本t检验适用条件具体计算公式R语言示例独立样本t检验适用条件具体计算公式R语言示例配对样本t检验适用条件具体计算公式R语言示例t检验(studentt检验)是应用t分布的特征,将t作为检验的统计量来进行统计推断方法。它对样本要求较小(例如n<30)。主要用途:样本均数与总体均数的差异比较两样本均数的差异比较分类:单样本t检验独立样本t检验配对样本t…

    2022年6月19日
    27
  • Oracle如何创建数据库[通俗易懂]

    Oracle如何创建数据库[通俗易懂]C:\Users\爸爸>sqlplus–执行OracleSQL*Plus:Release11.2.0.1.0Productionon星期四3月1014:14:052022Copyright(c)1982,2010,Oracle.Allrightsreserved.请输入用户名:system–用户名输入口令:–密码连接到:OracleDatabase11gEnterpriseEditionRelease11.2.0.1….

    2022年9月22日
    0
  • 内核态和用户态的区别_会导致用户进程用户态到内核态

    内核态和用户态的区别_会导致用户进程用户态到内核态1、用户态和内核态的区别?明白这两个概念之前,我们得知道用户空间和内核空间。用户空间:指的就是用户可以操作和访问的空间,这个空间通常存放我们用户自己写的数据等。内核空间:是系统内核来操作的一块空间,这块空间里面存放系统内核的函数、接口等。在用户空间下执行,我们把此时运行得程序的这种状态成为用户态,而当这段程序执行在内核的空间执行时,这种状态称为内核态。当一个任务(进程)执行系统…

    2022年9月18日
    0
  • “密码保护共享”关不掉

    “密码保护共享”关不掉在连接网络打印机时,我开启主机了Guest用户,并在打印机上设置,结果连接不到主机,在"高级共享设置"中关闭了"密码保护共享",可关了保存后再打开,还是没有关闭

    2022年8月5日
    4
  • linux 查看cpu核数、内存总容量、硬盘总容量

    linux 查看cpu核数、内存总容量、硬盘总容量一 查看 cpu 核数 cat proc cpuinfo grep physicalid sort uniq wc lcat proc cpuinfo grep process sort uniq wc l 二 查看内存总容量 cat proc meminfo 三 查看硬盘总容量 df hl 显示 文件系统容量已用可用已用 挂载点 FilesystemSi

    2025年7月14日
    0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号