具有可比接口的通用列表

时间:2019-02-04 01:11:37

标签: java

这是我的代码。尝试编译时出现运行时错误。它在第9行给了我一个错误(contact =(AnyType [])new Object [MAX_LIST];)

public class ArrayBasedSortedList<AnyType extends Comparable<AnyType>> 
{
     private AnyType[] contact;
     private static int MAX_LIST = 5;
     private int numItems;
     public ArrayBasedSortedList() 
     {
          contact = (AnyType[]) new Object[MAX_LIST];
     }

它给了我这个错误。

Exception in thread "main" java.lang.ClassCastException: class [Ljava.lang.Object; cannot be cast to class [Ljava.lang.Comparable; ([Ljava.lang.Object; and [Ljava.lang.Comparable; are in module java.base of loader 'bootstrap')
    at ArrayBasedSortedList.<init>(ArrayBasedSortedList.java:9)
    at test.main(test.java:5)

1 个答案:

答案 0 :(得分:0)

@Slaw尝试将其更改为

contact = (ArrayType[]) new Comparable[MAX_LIST];.