一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

java程序编译不通过怎么办

时间:2018-01-18 编辑:猪哥 来源:一聚教程网

本文介绍了java程序编译不通过的解决办法,遇到问题的朋友快来看看吧:

运行该段代码:

import java.util.*;
class  CollectionsDemo
{
public static void main(String[] args) 
{
System.out.println("Hello World!");
sortDemo();
}
public static void sortDemo()
{
List list = new ArrayList();
list.add("dsa");
list.add("dss");
list.add("dssas");
list.add("dsada");
list.add("dssa");
list.add("dsdas");
list.add("dswa");
sop(list);
LengthComparator it=  new LengthComparator();
Collections.sort(list, it);
sop(list);

}
public static void sop(List list)
{
System.out.println(list);
}
class LengthComparator implements Comparator
{
public int compare(String s1,String s2)
{
if(s1.length()>s2.length())
return 1;
 if(s1.length()
会提示:
CollectionsDemo.java:20: 错误: 无法从静态上下文中引用非静态 变量 this LengthComparator it=  new LengthComparator();

错误原因:内部类不能直接new
解决方法一: 将内部类LengthComparator拿到CollectionsDemo类外面 简单粗暴,推荐!
解决方法二: LengthComparator it = new CollectionsDemo().new LengthComparator(); 使用这条代码new内部类
解决方法三: 如前面的朋友所说 CollectionsDemo类前加static关键字 用 CollectionsDemo.LengthComparator it = new LengthComparator(); new内部类

相关推荐

java语言描述Redis分布式锁的正确实现方式》、《详解分别用Kotlin和java写RecyclerView的示例

热门栏目