【问题标题】:Why does my code result in a compile error? [closed]为什么我的代码会导致编译错误? [关闭]
【发布时间】:2018-10-24 10:07:48
【问题描述】:

有问题的代码如下:

importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.List;

public class Test{
    public static void main(String[] args) {
        List<Human> humans= newArrayList<Human>();
        humans.add(newHuman(13));
        humans.add(newHuman(33));
        humans.add(newHuman(21));
        humans.add(newHuman(21));
        Collections.sort(humans); 
        System.out.print(humans.get(0).age);
        System.out.print(humans.size()); 
    }
}
class Human implements Comparable<Human> {
    int age;
    public Human(int age) {
        this.age = age;
    }
    public int compareTo(Human h) {
        return h.age.compareTo(this.age);
    }
}

我想知道为什么这段代码会导致编译错误?我不确定我哪里出错了。

一些额外的细节:

【问题讨论】:

  • 错字:importjava... 应该是 import java...。同样的问题:newArrayList
  • 为什么对编译器错误感到惊讶?你写newArrayListnewHuman ...你从哪里得知new 和类型名称之间不需要空格?
  • 另外:int 没有实现任何接口,你不能在它上面调用 compareTo。

标签: java compiler-errors


【解决方案1】:

原始类型如 shrot、int、long、double 不实现 Comparable 接口。使您的实例变量对象类型。导入也发生了变化,同时创建了新对象( new Human(13))。

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    public class Test{
        public static void main(String[] args) {
            List<Human> humans= new ArrayList<Human>();
            humans.add(new Human(13));
            humans.add(new Human(33));
            humans.add(new Human(21));
            humans.add(new Human(21));
            Collections.sort(humans); 
            System.out.print(humans.get(0).age);
            System.out.print(humans.size()); 
        }
    }
    class Human implements Comparable<Human> {
        Integer age;
        public Human(int age) {
            this.age = age;
        }
        public int compareTo(Human h) {
            return h.age.compareTo(this.age);
        }
    }

【讨论】:

    【解决方案2】:

    你在代码中遗漏了很多空格。

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    public class Test{
        public static void main(String[] args) {
            List<Human> humans= new ArrayList<Human>();
            humans.add(new Human(13));
            humans.add(new Human(33));
            humans.add(new Human(21));
            humans.add(new Human(21));
            Collections.sort(humans); 
            System.out.print(humans.get(0).age);
            System.out.print(humans.size()); 
        }
    }
    class Human implements Comparable<Human> {
        int age;
        public Human(int age) {
            this.age = age;
        }
        public int compareTo(Human h) {
            return h.age - this.age;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-28
      • 1970-01-01
      相关资源
      最近更新 更多