Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting program to use objects instead of numbers

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?

like image 647
NewHelpNeeder Avatar asked Mar 16 '26 01:03

NewHelpNeeder


1 Answers

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,
like image 125
Tim Bender Avatar answered Mar 18 '26 15:03

Tim Bender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!