本帖最后由 小黑子 于 2014-9-16 19:02 编辑
编译结果如下:
CollectionsDemo.java:26: error: non-static variable this cannot be referenced fr
om a static context
Collections.sort(al,new StrLenComparator());
^
1 error
- /*
- 用Collections中的Sort(List<T> list, Comparator<? super T>)方法排序。
- */
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Comparator;
- class CollectionsDemo
- {
- public static void main(String[] args)
- {
- sort();
- }
- public static void sort()
- {
- ArrayList<String> al = new ArrayList<String>();
- al.add("dasd");
- al.add("qq");
- al.add("aaa");
- al.add("gds");
- al.add("b");
- al.add("bb");
- System.out.println(al);
- Collections.sort(al,new StrLenComparator());
- System.out.println(al);
- }
- 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);
- }
- }
- }
复制代码
|
|