您的位置:首页 > 编程语言 > Java开发

【Java学习笔记】基础知识学习12【Set接口的实现类】

2013-07-23 00:32 816 查看
Set为集的接口。根据集的性质,中的元素是无序的放置,中的元素不可以重复。

Set接口常用的实现的类为HashSet类和TreeSet类

从TreeSet开始:

TreeSet常用的方法有:

first():返回集中第一个元素

last():返回集中最后一个元素

comparator():返回此集中的排序比较器,如果此集采用自然顺序,则null为返回值

headSet(Object obj):

subSet(Object from,Object to):

tailSet(Object to):

下面是示例代码:

static void TreeSetTry(){
TreeSet<String> nTreeSet=new TreeSet<String>();
nTreeSet.add("we are the world-MJ");
nTreeSet.add("beat it-MJ");
nTreeSet.add("earth song-MJ");
nTreeSet.add("billie jean-MJ");
Iterator<String> nt=nTreeSet.iterator();
for(;nt.hasNext();){
Easy.ShowL((String)nt.next());
}
//以上是排序后,将集中的内容显示出来,看到顺序的结果
SortedSet<String> nkk=nTreeSet.headSet("billie jean-MJ");
Easy.ShowL("headSet后:");
nt=nkk.iterator();
for(;nt.hasNext();){
Easy.ShowL((String)nt.next());
}
//以上是,将"billie jean-MJ"之前的元素顺序提取出来,到SortedSet
Easy.ShowL("首元素:"+nTreeSet.first());
Easy.ShowL("尾元素:"+nTreeSet.last());
//获取首位元素
SortedSet<String> subStr=nTreeSet.subSet("billie jean-MJ", "earth song-MJ");
Easy.ShowL("subSet后的结果:");
nt=subStr.iterator();
for(;nt.hasNext();){
Easy.ShowL((String)nt.next());
}
//将"billie jean-MJ"及其之后的元素,并且满足是"earth song-MJ"之前的元素(不含"earth song-MJ"),按序送到SortedSet里面
SortedSet<String> tailStr=nTreeSet.tailSet("earth song-MJ");
Easy.ShowL("获取earth song(含)之后的:");
nt=tailStr.iterator();
for(;nt.hasNext();){
Easy.ShowL((String)nt.next());
}
}


以下是运行的结果:

beat it-MJ

billie jean-MJ

earth song-MJ

we are the world-MJ

headSet后:

beat it-MJ

首元素:beat it-MJ

尾元素:we are the world-MJ

subSet后的结果:

billie jean-MJ

获取earth song(含)之后的:

earth song-MJ

we are the world-MJ

【·未完待续·】

有疑惑的地方,欢迎大家留言交流!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐