TreeSet中实现自己的Comparator,以及常见的Collections方法的使用

比起之前所说的HashSet,TreeSet又有了一定的优势,TreeSet是SortedSet中的子类,顾名思义这是有序的一个集合,先看一个例子:

public class TreeSetTest
{
public static void main(String[] args)
{
TreeSet tree = new TreeSet();
tree.add("aa");
tree.add("ad");
tree.add("c");
tree.add("b");
tree.add("e");
System.out.println(tree);
}

}

如果这是一个,ArrayList或者是Linkedlist他会是原样输出,如果是一个HashSet,他会乱序输出,但现在他会按顺序输出。

但是如果add方法中是一个自己定义的类对象:

public class TreeSetTest
{
public static void main(String[] args)
{
TreeSet tree= new TreeSet();
tree.add(new Persion("zhangran"));
tree.add(new Persion("zhang"));
System.out.println(tree);

}
}
class Persion
{
String name;
Persion(String name)
{
this.name = name;

}
public String toString()
{
return this.name;
}
}

此时此时便会出现异常,问题在于,TreeSet本来是应该比较大小,然后按顺序输出的但是,但是现在你给了他一个自己定义的类,它便无法识别,不知道怎么排序了,所以你现在所做的就是告诉他如何排序,此时就需要一个比较器(Comparator):

public class TreeSetTest
{
public static void main(String[] args)
{

TreeSet tree= new TreeSet(new MyComparator());
tree.add(new Persion("zhangran"));
tree.add(new Persion("zhang"));
System.out.println(tree);

}
}

class Persion
{
String name;
Persion(String name)
{
this.name = name;

}
public String toString()
{
return this.name;
}
}
class MyComparator implements Comparator
{

@Override
public int compare(Object o1, Object o2)
{
Persion p1 = (Persion)o1;
Persion p2 = (Persion)o2;
return p1.name.compareTo(p2.name);
}

}
这样TreeSet便会知道你是要按照字符串从小到大排序,这样便可以顺利运行。


下面再讲一下Collections中的某些方法,Collections是集合的父类,里面有许多的静态方法,可以给他的子类对象提供许多功能

1.让LinkedList中的数值有序输出

LinkedList list = new LinkedList();

list.add(new Integer(1));

list.add(new Integer(0));

list.add(new Integer(3));

list.add(new Integer(2));

//生成一个比较器

Comparator com = Collections.reverseOrder();//倒叙

Collections.sort(list,com);//list按照com的排列反方式排列;

输出:。。。。

此处不能直接用Collections.reverse();

这样的话,他会按照相反的顺序输出(2,3,0,1)而不是从大到小;

--------------------------

2.Collections.shuffle()乱序排列。。。。

3.Collections.min();最小

4.Collections.max();最大

还有好多方法在API里都很详细,大家可以自己多看看。。。。。。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值