17-集合框架-25-常用对象API(集合框架-TreeSet集合练习-字符串长度排序)

package cn.itcast.comparator;

import java.util.Comparator;

public class ComparatorByLength implements Comparator {

	public int compare(Object o1, Object o2) {
		
		String s1 = (String)o1;
		String s2 = (String)o2;

		int temp = s1.length() - s2.length();
		
		return temp==0?s1.compareTo(s2):temp;//这里的compareTo是String类自己的方法

	}

}

===========================================分割线====================================

package cn.itcast.treeset.test;


import java.util.Iterator;
import java.util.TreeSet;


import cn.itcast.comparator.ComparatorByLength;


public class TreeSetTest {


public static void main(String[] args) {


/*
* 需求:对字符串长度进行排序
*/
TreeSet ts = new TreeSet(new ComparatorByLength());
ts.add("aaaaa");
ts.add("zz");
ts.add("nbaq");
ts.add("cba");
ts.add("abc");
Iterator it = ts.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}


}

你可能感兴趣的:(17-集合框架-25-常用对象API(集合框架-TreeSet集合练习-字符串长度排序))