java - ClassCastException when casting from Object[] to Comparable[] -
this question has answer here:
edit: noticed post flagged duplicate; read through other, similar, question didn't treat same problem mine. i'm working class guaranteed of type comparable, yet can't cast it.
i have following class, implementation of interface queue. make sure type heappriorityqueue object works implements comparable, method e.compareto(e other) available.
i create instance of heappriorityqueue in main method. patient class implements comparable
heappriorityqueue<patient> queue = new heappriorityqueue<>(); at compilation however, exception classcastexception points towards last line in code below
public class heappriorityqueue<e extends comparable<e>> implements queue<e> { private final int default_capacity = 10; private int size; private e[] array; public heappriorityqueue() { size = 0; array = (e[]) new object[default_capacity + 1]; } } the exception:
exception in thread "main" java.lang.classcastexception: [ljava.lang.object; cannot cast [ljava.lang.comparable;
i'm working class guaranteed of type comparable, yet can't cast it.
new object[default_capacity + 1]; doesn't guarantee instead of fact it's object array. object array can't safely cast comparable array.
you'd have use like:
class<e> clazz; array = (e[]) array.newinstance(clazz, size);
Comments
Post a Comment