java treeset treemap_java TreeSet 的基础使用

本文介绍了Java中的TreeSet类,它是一个有序集合,依赖于TreeMap实现,元素默认按自然顺序排序。若元素需要自定义排序,可以实现Comparable接口或在创建时传入Comparator。示例展示了如何通过自定义比较器进行学生对象的学号和姓名排序。
摘要由CSDN通过智能技术生成

java TreeSet 的基础使用

[TreeSet是依靠TreeMap来实现的TreeSet是一个有序集合,她的元素 按照升序排列,默认是按照自然顺序排列,也就是说TreeSet中的对象元素需要实现Comparable接口 ...]

TreeSet是依靠TreeMap来实现的

TreeSet是一个有序集合,她的元素 按照升序排列,默认是按照自然顺序排列,也就是说TreeSet中的对象元素需要实现Comparable接口。

TreeSet类中跟HashSet类一样也没有get()方法来获取列表中的元素,所以也只能通过迭代器方法来获取。

Java代码

public class TreeSetTest

{

public static void main(String[] args)

{

TreeSet tr =new TreeSet();

tr.add("zhangshan");

tr.add("wangwu");

tr.add("lisi");

Iterator it =tr.iterator();

while(it.hasNext())

{

System.out.println(it.next());

}

}

}

输出结果为:lisi wangwu zhangshan

这是因为TreeSet是一个有序并且默认按自然顺序排列,[【JAVA基础】HashSet、LinkedHashSet、TreeSet使用区别HashSet:哈希表是通过使用称为散列法的机制来存储信息的,元素并没有以某种特定顺序来存放;LinkedHashSet:以元素而不像哈希表那样毫无规律。

当然,你也可以在创建TreeSet对象时传递一个比较器来实现你自己的排序方式:

Java代码

import java.util.*;

public class TreeSetTest

{

public static void main(String[] args)

{

//传递一个比较器来实现你自己的排序方式

TreeSet tr =new TreeSet(new Student.StudentComparator());

tr.add(new Student(3,"wnagwu"));

tr.add(new Student(2,"zhangshan"));

tr.add(new Student(2,"lisi"));

tr.add(new Student(1,"xiejin"));

Iterator it =tr.iterator();

while(it.hasNext())

{

System.out.println(it.next());

}

}

}

Student类:

Java代码

class Student implements Comparable,Comparator

{

int num;

String name;

Student(int num,String name)

{

this.num=num;

this.name=name;

}

public int compareTo(Object o)

{

Student st =(Student)o;

int result;

result= num>st.num?1:(num==st.num?0:-1);

//如果学号相等,就按姓名排列

/*if(result==0)

{

return name.compareTo(st.name);

}*/

return result;

}

//实现Comparator接口并实现它的抽象方法

public int compare(Object o1,Object o2)

{

Student st1 =(Student)o1;

Student st2 =(Student)o2;

return st1.name.compareTo(st2.name);

}

//重写toString()方法,因为如果不重写,打印出来的是16进制代码

public String toString()

{

return "num="+num+"; name="+name;

}

public static class StudentComparator implements Comparator

{

public int compare(Object o1,Object o2)

{

Student st1 =(Student)o1;

Student st2 =(Student)o2;

int result;

result=st1.num>st2.num?1:(st1.num==st2.num?0:-1);

if(result==0)//如果学号相等 就进行名字排序

{

result=st1.name.compareTo(st2.name);

}

return result;

}

}

}

上面如果只使用学号排序,那么学号相同的就不会被打印的。[Java中的HashSet和TreeSet 文/ Iangao 一. 问题   1. HashSet,TreeSet是如何使用hashCode()和equal()方法的   2. TreeMap,TreeSet中的对象何时以及为何要实现Comparable接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值