码迷,mamicode.com
首页 > 编程语言 > 详细

按照字符串长度排序

时间:2018-01-16 00:35:11      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:out   post   iterator   方式   blog   new   []   public   tree   

字符串本身具备比较性。但是它的比较方式不是所需要的,这时就只能使用比较器

 1 public class TreeSetDemo2 {
 2     public static void main(String[] args) {
 3          TreeSet ts=new TreeSet(new StringLengthComparator());//也可用匿名内部类实现
 4          ts.add("a");
 5          ts.add("aa");
 6          ts.add("aaa");
 7          ts.add("aaaa");
 8          ts.add("b");
 9          
10          Iterator it=ts.iterator();
11          while(it.hasNext()) {
12               System.out.println(it.next());
13          }
14     }
15 }
16 class StringLengthComparator implements Comparator{
17     public int compare(Object o1,Object o2) {
18         String s1= (String)o1;
19         String s2= (String)o2;
20         int num=new Integer(s1.length()).compareTo(new Integer(s2.length()));
21         if(num==0) {
22             return s1.compareTo(s2);
23         }
24         return num;
25     }
26 
27 
28 }

 

按照字符串长度排序

标签:out   post   iterator   方式   blog   new   []   public   tree   

原文地址:https://www.cnblogs.com/zhaohuan1996/p/8290223.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!