user6611771
user6611771

Reputation:

How to implement CompareTo for arrays?

I have the following class

public class MinPQ<T> : IComparable<T>
{
    private T[] keys;
    ...
}

How to implement CompareTo method? I would like to do the following in my method

public void decreaseKey(int i, T key){
   if (keys[i].CompareTo(key) <= 0) {...} // or if(CompareTo(keys[i], key) <= 0)
}

Most of the time T will be int or double

Upvotes: -1

Views: 574

Answers (1)

Zolt&#225;n Tam&#225;si
Zolt&#225;n Tam&#225;si

Reputation: 12809

I assume that you mean how to declare the type T as comparable. If so, you can do it with the following generic constraint.

public class MinPQ<T> where T: IComparable<T>
{
    private T[] keys;
    ...
}

Upvotes: 3

Related Questions