本帖最后由 张华廷 于 2012-6-25 14:12 编辑
/*
集合框架的工具类
Collections;
*/
import java.util.*;
class CollectionsDemo
{
public static void main(String[] args)
{
sortDemo();
}
public static void sortDemo()
{
List<String> list = new ArrayList<String>();
list.add("abcd");
list.add("aaa");
list.add("z");
list.add("kkkk");
list.add("qq");
list.add("cc");
list.add("z");
sop(list);
//Collections.sort(list);
Collections.sort(list,new StrLenComparator());
/*1 错误
d:\Users\Administrator\Desktop\集合>javac CollectionsDemo.java
CollectionsDemo.java:26: 无法从静态上下文中引用非静态 变量 this
Collections.sort(list,new StrLenComparator());*/
sop(list);
}
public static void sop(Object obj)
{
System.out.println(obj);
}
class StrLenComparator implements Comparator<String>
{
public int compare(String s1,String s2)
{
if(s1.length()>s2.length())
return 1;
if(s1.length()<s2.length())
return -1;
return s1.compareTo(s2);
}
}
}
|
|