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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Redis在SpringBoot的基本使用

    Redis在SpringBoot的基本使用一、配置1.添加依赖在springboot启动器中直接添加依赖,或者创建后添加Maven依赖:<!–spring-boot-starter-data-redis–>&l

    2022年8月16日
    13
  • Win10 下报错 WerFault.exe -解决方法亲测有效

    Win10 下报错 WerFault.exe -解决方法亲测有效Win10WerFault.exe错误装了后经常出现WerFault.exe的应用程序错误提示。内存*****地址不能为read.解决方法两种:1.系统设置2.管理员运行cmd命令行模式我机器用的第二种方式。1.系统设置1.1本地组策略gpedit.msc用户配置-管理模块-Windows组件-Windows错误报告-禁用1.2…

    2022年6月29日
    24
  • Matlab符合矩阵微分,matlab解矩阵微分方程.pdf[通俗易懂]

    matlab解矩阵微分方程MATLAB20180625–MATLAB1Definition1t′()Definition2∫()∫24MATLABode451:–11–MATLAB⩾(1)2.14MATLAB1%RUNGEKUTTA442%hyowinn…

    2022年4月9日
    78
  • Vue学习之v-model指令

    Vue学习之v-model指令Vue学习之v-model指令

    2022年4月23日
    58
  • 虚拟机中安装windows10详细教程_openeuler虚拟机安装

    虚拟机中安装windows10详细教程_openeuler虚拟机安装Neokylin操作系统安装一、准备工作1.安装VmwareWorkstation2.下载镜像二、创建虚拟机及配置1.创建系统2.硬件配置三、选择镜像并安装系统1.导入镜像文件2.安装Neokylin操作系统一、准备工作1.安装VmwareWorkstationVMwareWorkstation是一款功能强大的桌面虚拟计算机软件,为用户提供了在单一的桌面上同时运行不同操作系统的解决方案。后续我们将通过它来创建虚拟机并安装Neokylin操作系统。下载安装包后根据提示即可快速完成安装2.下载

    2022年8月10日
    11
  • python错误和异常处理_python异常处理

    python错误和异常处理_python异常处理抛出异常Python使用raise语句抛出一个指定的异常。raise语法格式如下:raise[Exception[,args[,traceback]]]defdivision():”’功能:分苹果”’print(“\n=====================分苹果了=====================\n”)apple=int(input(“请输入苹果的个数:”))#.

    2022年10月9日
    2

发表回复

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

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