我创建了一个 ArrayList
和一个来自 Student
类的对象数组,并且 Student
类不是 instanceof Comparable
接口(interface),所以当我使用 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;
}}
我的问题是为什么数组列表会出现编译错误,而对象数组会出现运行时错误? 谢谢。
最佳答案
ArrayList 是泛型类,泛型的主要好处是可以在编译时而不是运行时检测到错误。
关于java - arrayList 和 Object 数组的不同类型的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51251925/