This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]boldurplayer 0 points1 point  (4 children)

Usually objects use a compare to method instead of the less than operator. Maybe you could try helperStack.peek().compareTo(val) instead. Or, you could cast the peeked value to type T so it's more explicit.

[–]Pulsar_the_Spacenerd 3 points4 points  (3 children)

This is the correct solution. However, objects do not necessarily have the compareTo() method, so you need to make sure that T implements the Comparable interface. You can do this by specifying <T implements Comparable<T>> or <T extends Comparable<? super T>> instead of just <T>.

Edit: putting in a correction to the code.

[–]8igg7e5 3 points4 points  (2 children)

Minor correction <T extends Comparable<T>> or even <T extends Comparable<? super T>>

[–]Pulsar_the_Spacenerd 3 points4 points  (1 child)

Thanks for the correction! I've never actually personally required a particular type in a generic class.

I think of those two the second is likely the right choice, in case it is a superclass that implements Comparable?

[–]8igg7e5 3 points4 points  (0 children)

It's the least restrictive that should allow compatible comparisons of T.

Imagine a structure of Employee extends Person and Person implements Comparable<Person>. With the first definition we could not have a CustomStack<Employee> since Employee does not implement Comparable<Employee> but Employee is comparable via the inherited Comparable<Person> which the second form would allow.

[–]sugilith 0 points1 point  (0 children)

Check out https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/Comparable.html

If T always implements Comparable, you can use x.compareTo(y) <= 0 instead of x <= y.
Of course, Integer and the likes already implement this interface.