I am asked to convert a program to use generic types in my array.
I have no idea where to start. I tried to convert the array to generic but I keep getting problems.
I tried to just convert the array to generic one by using queArray = (T[]) (new Comparable[maxSize]); but after I modified all variables to suppose to use generic types I keep getting errors.
What do I have to change here?
You want to declare that T must implement Comparable. This allows you to explicitly state that the PriorityQ can only support classes which can be compared for ordering. This is done like so:
class PriorityQ<T extends Comparable<T>>
Now queArray should be newed as an array of T since the PriorityQ is ordering instances of type T:
queArray = new T[maxSize];
Lastly, use the Comparable.compareTo method for your comparisons:
if( item .compareTo(queArray[j]) > 0 ) // if new item larger,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With