hales1915
hales1915

Reputation: 9

getMax() operater "<" cannot be applied to <T>

I am very new to linked lists and nodes so I am completely stuck on my getMax() method in Java.

So I am trying to get the largest value in the list but I can't use "<" in my if statment, what am I supposed to use instead? Do I need to do compareTo? But then I don't know what I would be comparing.

This is the code I have so far:

public T getMax()
    {
        T largestValue = null;
        Node<T> currNode = this.firstNode;
        while (currNode.next != null)
        {
            if(largestValue < currNode.next.data)


        }

Upvotes: 0

Views: 90

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 103500

You (presumably; your snippet is too short) have no bounds on T, so T could be anything. Notably, it could be, say, InputStream, which is not inherently comparable. Therefore, it is not possible to apply any sort of "is this particular instance of T 'below' this other instance of T" operation on this, as there is no guarantee this operation even makes sense.

You need to make that make sense.

In java, that'll be the job of Comparable, or, you separate out the notion of 'the kind of thing I operate on' and 'code that can determine, given 2 things, which one is lower'.

The former means you want T to be bound. You also messed up your handling of next. I'll fix both.

public class MyClassThingie<T extends Comparable<T>> {
    public T getMax() {
        T largestValue = null;
        Node<T> currNode = this.firstNode;
        while (currNode != null) {
            if (largestValue == null || largestValue.compareTo(currNode.data) < 0) largestValue = currNode.data;
            currNode = currNode.next;
        }
        return largestValue;
        // you may want to spec out that your method returns null if there are 0 elements.
    }
}

If you want the other model, have a constructor that accepts a Comparator<T>; see the source of e.g. TreeSet for some examples.

Note that T extends Comparable<T> means: T is some type for which the following holds: It implements Comparable<T>. In other words, it is a thing that is capable of comparing itself to other things of its own kind. String is such a type. So is Integer. (Integer implements Comparable<Integer>; String implements Comparable<String>).

Upvotes: 4

Related Questions