简体   繁体   中英

Generic List with comparable interface

This is my code. I am getting a run time error when i try to compile it. It gives me an error in the 9th line(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];
     }

It gives me this error.

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)

@Slaw 尝试将其更改为

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM