import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; class Mycompara implements Comparator { //自定义一个比较器,按照字符串的长度来比较字符串,然后对其进行储存 //如果字符串的长度一样长了后,再依据字符内容进行排序 public int compare(Object o1, Object o2) { // TODO Auto-generated method stub String s1 = (String)o1; String s2 = (String)o2; int i = s1.length()-s2.length(); if(i==0) return s1.compareTo(s2); return i; } } public class StringLengthCompara { public static void main(String[] args) { // TODO Auto-generated method stub TreeSet ts = new TreeSet(new Mycompara()); ts.add("abhd"); ts.add("abd1111"); ts.add("abd2mk"); ts.add("abdj"); ts.add("abod"); ts.add("aibd"); Iterator<String> it = ts.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } }<span style="font-family:FangSong_GB2312;"> </span>
黑马程序员——java——自定义一个比较器,按照字符串的长度升序的方法来比较字符串进行储存
原文地址:http://blog.csdn.net/zl18603543572/article/details/46559219