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)
上一篇 2022年5月28日 下午8:36
下一篇 2022年5月28日 下午8:36


相关推荐

  • razorpages_rabeprazole

    razorpages_rabeprazole什么是RazorPage我们都知道在Asp.NetMVC中,Razor是其一种视图引擎。而今天我们介绍的RazorPage却是一种web框架,它是一种简化的MVC框架,如果你曾经做过WebForm的开发者,你会发现,RazorPage有点类似WebForm,一个page,一个class。大家或许会有疑惑,我们现在Asp.NetMVC已经很完善了,为何还需要出来一种新型的框架呢?在我看来,MVC确实已经足够强大了,只是因为太强大了,却变成了它的缺点。当我们的业务越来越庞大的时候,你是否觉得你的一

    2025年6月29日
    5
  • DenseNet模型[通俗易懂]

    DenseNet模型[通俗易懂]《DenselyConnectedConvolutionalNetworks》阅读笔记代码地址:https://github.com/liuzhuang13/DenseNet首先看一张图:稠密连接:每层以之前层的输出为输入,对于有L层的传统网络,一共有LL个连接,对于DenseNet,则有L(L+1)2\frac{L(L+1)}2。这篇论文主要参考了HighwayNetw

    2026年4月18日
    6
  • FileInputFormat.setInputPaths多路径读取规则

    FileInputFormat.setInputPaths(job,input1,input2);在读取文件时候,默认先读单个大文件所在的路径(一次性读清该文件下所有文件),后读小文件所在路径。写协同过滤时候,想让setInputPaths方法先读第一个输入路径input1,再读第二个输出路径input2就算把文件位置交换,读取的顺序还是错误publicstaticclassmyMapp…

    2022年4月6日
    36
  • 三角形的余弦定理

    三角形的余弦定理余弦定理 如图 三角形 ABC 则 cosB frac BA 2 BC 2 AC 2 2 BA BC 证明余弦定理最初级的方法其实是用射影定理联立方程组 根据射影定理 我们知道 begin equation label eq 1 AB cosB AC cosC BC end equation 同理有 begin equa

    2026年3月19日
    2
  • java学习—探秘Java中的String、StringBuilder以及StringBuffer

    相信String这个类是Java中使用得最频繁的类之一,并且又是各大公司面试喜欢问到的地方,今天就来和大家一起学习一下String、StringBuilder和StringBuffer这几个类,分析它们的异同点以及了解各个类适用的场景。下面是本文的目录大纲:  一.你了解String类吗?  二.深入理解String、StringBuffer、StringBuilder  三.不同场景下三个类的性能测试

    2022年2月25日
    39
  • pycharm 开启代码提示[通俗易懂]

    pycharm 开启代码提示[通俗易懂]1、先打开pycharm2、依次选择红框部分3、搞好之后,代码提示便可以使用了

    2022年8月26日
    13

发表回复

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

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