首页 > 编程语言 > 详细

按照字符串长度排序

时间:2018-01-16 00:05:46      阅读:260      评论:0      收藏:0      [点我收藏+]

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

 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 }

 

按照字符串长度排序

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!