Question

In the tree class I'm suppose to compare two node, for you know searching and adding items. I have some issues with how to make it comparable. When one adds data(generic, anything) to the tree one calls the Tree class which then makes a new Node object. How can I declare the variable data/element in the Node class so that it is of type E (anything) and still Comparable? Seriously, I've tried back and forth without concluding with anything.

Was it helpful?

Solution

Not everything is Comparable. Your requirement is self-contradictory. You can constrain E to be comparable by declaring the generic parameter like:

< E extends Comparable<E> >

This way, the consumer of the class can use all classes that implement Comparable interface with it. You'll be able to access the compareTo method on things typed E.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top