A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

本帖最后由 小黑子 于 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

  1. /*
  2.         用Collections中的Sort(List<T> list, Comparator<? super T>)方法排序。
  3. */

  4. import java.util.ArrayList;
  5. import java.util.Collections;
  6. import java.util.Comparator;

  7. class CollectionsDemo
  8. {
  9.         public static void main(String[] args)
  10.         {
  11.                 sort();
  12.         }
  13.         public static void sort()
  14.         {
  15.                 ArrayList<String> al = new ArrayList<String>();
  16.                 al.add("dasd");
  17.                 al.add("qq");
  18.                 al.add("aaa");
  19.                 al.add("gds");
  20.                 al.add("b");
  21.                 al.add("bb");

  22.                 System.out.println(al);
  23.                 Collections.sort(al,new StrLenComparator());
  24.                 System.out.println(al);
  25.         }
  26.         class StrLenComparator implements Comparator<String>
  27.         {
  28.                 public int compare(String s1,String s2)
  29.                 {
  30.                         if(s1.length()>s2.length())
  31.                                 return 1;
  32.                         if(s1.length()<s2.length())
  33.                                 return -1;
  34.                         return s1.compareTo(s2);
  35.                 }
  36.         }
  37. }
复制代码



5 个回复

正序浏览
xplcc 发表于 2014-9-16 16:07
你StrLenComparator这个类是个内部类,你26行获取对象的时候用new StrLenComparator()当然获取不到。这里 ...

我晕,竟然写成内部类了…………写错了。。。
回复 使用道具 举报
看看!!!
回复 使用道具 举报
来这儿看一下,相信对避免内部类的相关错误 很有帮助!
内部类相关知识总结。
http://bbs.itheima.com/thread-143608-1-1.html
(出处: 黑马程序员IT技术论坛)
回复 使用道具 举报
额.......其实楼主在28行回车后再加一个"}"就好了
然后将最后一行的大括号去掉就好
你是大括号弄错了
回复 使用道具 举报
你StrLenComparator这个类是个内部类,你26行获取对象的时候用new StrLenComparator()当然获取不到。这里有个隐藏的this,具体写法是this.new StrLenComparator()。this就是CollectionsDemo对象,你这个对象都没有实例化,她在调用的时候肯定回报错误。解决方法 1、new CollectionsDemo().new StrLenComparator();2、不要把StrLenComparator当内部类
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马