Reputation: 811
I know Comparable is an interface, but I saw some codes like ArrayList<Comparable>
, public Comparable f()
,public void f(Comparable a)
.
It seems like Comparable is a class. How do those codes above implement?
import java.util.*;
public class MinHeap
{
public MinHeap()
{
elements = new ArrayList<Comparable>();
elements.add(null);
}
....
}
public class BinarySearchTree
{
...
public void add(Comparable obj)
{
Node newNode = new Node();
newNode.data = obj;
newNode.left = null;
newNode.right = null;
if (root == null) root = newNode;
else root.addNode(newNode);
}
...
}
Upvotes: 1
Views: 5879
Reputation: 2566
What those uses of Comparable mean is that they accept an object of any class that implements the Comparable interface.
But Comparable is still an interface. You can't specifically create an object of type Comparable, but you can assign an instance of a class that implements it to a variable of that type. For example, if there is a class Foo that implements Comparable, e.g.
public class Foo implements Comparable<Foo> {
public int compareTo(Foo o) {...}
}
then I can treat objects of class Foo as Comparables. If I have an array list like:
List<Comparable> list = new ArrayList<Comparable>();
I can put Foo objects in it, because they implement Comparable, e.g.
list.add(new Foo());
Upvotes: 5