java sortedset_Java中的SortedSet接口和示例 - Break易站

Java 集合框架

SortedSet是集合框架中的接口。此接口扩展了Set并提供其元素的总排序。实现此接口的Exampled类是TreeSet。

MapInterface.png

SortedSet的所有元素都必须实现Comparable接口(或者被指定的Comparator接受),并且所有这些元素必须是可相互比较的(即,Mutual Comparable只是意味着两个对象互相接受作为compareTo方法的参数)

SortedSet接口的方法:

comparator():返回用于对此集合中的元素进行排序的比较器,如果此集合使用其元素的自然顺序,则返回null。

first():返回此集合中当前的第一个(最低)元素。

headSet(E toElement):返回此set的部分视图,其元素严格小于toElement。

last():返回此集合中当前的最后一个(最高)元素。

subSet(E fromElement,E toElement):返回此set的部分视图,其元素范围从fromElement(包括)到toElement(不包括)。

tailSet(E fromElement):返回此set的部分元素,其元素大于或等于fromElement。

public interface SortedSet extends Set

{

// Range views

SortedSet subSet(E fromElement, E toElement);

SortedSet headSet(E toElement);

SortedSet tailSet(E fromElement);

// Endpoints

E first();

E last();

// Comparator access

Comparator comparator();

}

// A Java program to demonstrate working of SortedSet

import java.util.SortedSet;

import java.util.TreeSet;

public class Main

{

public static void main(String[] args)

{

// Create a TreeSet and inserting elements

SortedSet sites = new TreeSet<>();

sites.add("practice");

sites.add("geeksforgeeks");

sites.add("quiz");

sites.add("code");

System.out.println("Sorted Set: " + sites);

System.out.println("First: " + sites.first());

System.out.println("Last: " + sites.last());

// Getting elements before quiz (Excluding) in a sortedSet

SortedSet beforeQuiz = sites.headSet("quiz");

System.out.println(beforeQuiz);

// Getting elements between code (Including) and

// practice (Excluding)

SortedSet betweenCodeAndQuiz =

sites.subSet("code","practice");

System.out.println(betweenCodeAndQuiz);

// Getting elements after code (Including)

SortedSet afterCode = sites.tailSet("code");

System.out.println(afterCode);

}

}

输出:

Sorted Set:

First: code

Last: quiz

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值