newbie
newbie

Reputation: 111

What's wrong with my wildcard implementation?

I have 3 classes(PriorityQueue, Assignment, AssignmentLog) and 1 Interface(IPriorityQueue).

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

PriorityQueue class:

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();
}

My question is even though the IDE does not recognize any error, when I run the program it shows an exception:

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)

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

Please explain me what is wrong with my assignment. I'm still really new to wild card, so please give me some advice

Thank you

Upvotes: 1

Views: 123

Answers (1)

Abhyudaya Sharma
Abhyudaya Sharma

Reputation: 1282

You're down-casting an Object[] to T[]. Down casting in Java to a class which is not a subclass throws an instance of ClassCastException.

From the Javadoc for ClassCastException:

Thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

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

In the line priorityQueue = (T[])new Object[size];, when you try to cast the Object[] to T[], Java does a type check. Since Object does not extend T, the cast fails. However, you must remember that each class other than Object implicitly extends Object.

If you're looking to initialize an object of type T inside a generic function, take a look at Instantiating a generic class in Java.

Upvotes: 3

Related Questions