猿问

arrayList和Object数组的不同类型的错误

我ArrayList从类创建了一个对象数组,Student并且Student该类不是instanceofComparable接口,所以当我用ArrayList此代码编写代码时,会导致编译错误。


import java.util.*;


public class test {

    public static void main(String[] args) {

     ArrayList <Student> studentList = new ArrayList<>();

     studentList.add(new Student("Ahmed",50));

     studentList.add(new Student("Ameen",30));


     java.util.Collections.sort(studentList);

     System.out.println(studentList);


}

  }


public class Student {

    private String name;

    private int score;


    Student ( String name , int score){

        this.name= name;

        this.score = score;   

    }

}

当我用对象数组编写代码时,这会导致运行时错误


import java.util.*;


public class test {


    public static void main(String[] args) {


      Student [] student = new Student[2];

      student[0]=new Student("Ahmed",50);

      student[1]=new Student("Ameen",30);

     java.util.Arrays.sort(student);

     System.out.println(Arrays.toString(student));

}

}


public class Student {

    private String name;

    private int score;

    Student ( String name , int score){

        this.name= name;

        this.score = score;   

    }}

我的问题是为什么我在数组列表中出现编译错误,为什么在对象数组中出现运行时错误?谢谢。


斯蒂芬大帝
浏览 180回答 2
2回答

吃鸡游戏

ArrayList是泛型类,泛型的主要好处是可以在编译时而不是在运行时检测到错误。
随时随地看视频慕课网APP

相关分类

Java
我要回答