我的通配符实现有什么问题?

时间:2019-02-27 04:03:22

标签: java wildcard

我有3个类(PriorityQueue,Assignment,AssignmentLog)和1个接口(IPriorityQueue)。

public interface IPriorityQueue<T extends Comparable<? super T>> {
void add(T newEntry);
T remove();
T peek();
boolean isEmpty();
int getSize();
void clear(); }

PriorityQueue类:

public class PriorityQueue<T extends Comparable<? super T>> implements IPriorityQueue<T> {

private T[] priorityQueue;
private int frontIndex = 0;
private int backIndex = 0;
private static final int DEFAULT_SIZE= 50;...
}

Assignment.java:

public class Assignment implements Comparable<Assignment> {
private String course;
private String task;
private Date dueDate;
@Override
public int compareTo(Assignment other) {
    return -dueDate.compareTo(other.dueDate);
}}

AssignmentLog.java:

public class AssignmentLog {
private IPriorityQueue<Assignment> log;

public AssignmentLog(){
    log = new PriorityQueue<>();
}

public void addProject(Assignment newAssignment){
    log.add(newAssignment);
}

public Assignment getProject(){
    return log.peek();
}

我的问题是,即使IDE无法识别任何错误,当我运行程序时它也会显示异常:

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 PriorityQueue.<init>(PriorityQueue.java:13)
    at PriorityQueue.<init>(PriorityQueue.java:9)
    at AssignmentLog.<init>(AssignmentLog.java:5)
    at Main.main(Main.java:13)

第13行:public PriorityQueue(int size){ priorityQueue = (T[])new Object[size]; }
第10行:public PriorityQueue(){ this(DEFAULT_SIZE); }
第5行:public AssignmentLog(){ log = new PriorityQueue<>(); }
第13行:AssignmentLog myHomework = new AssignmentLog();

请向我解释我的作业有什么问题。我仍然是通配符的新手,所以请给我一些建议

谢谢

1 个答案:

答案 0 :(得分:3)

您正在将Object[]下放到T[]。在Java中向下转换为不是子类的类将引发ClassCastException的实例。

JavadocClassCastException

  

抛出该错误,以表明代码已尝试将对象强制转换为不是实例的子类。例如,以下代码生成ClassCastException:

     
Object x = new Integer(0);
System.out.println((String)x);

priorityQueue = (T[])new Object[size];行中,当您尝试将Object[]强制转换为T[]时,Java会进行类型检查。由于Object不扩展T,因此强制转换失败。但是,您必须记住,Object以外的每个类都隐式扩展了Object

如果要在通用函数中初始化T类型的对象,请查看Instantiating a generic class in Java