For an assignment, I have been asked to "Create a class called TreeMap
that uses the BinarySearchTree
class to implement a map". We are given a collection of interfaces and classes to extend and implement.
The first step of the assignment asks to "Create an inner class called TreeEntry
to store the entries. Include a constructor and any mandatory methods".
The interfaces we are given include BinaryTree<T>
, Entry<K, V>
, Map<K, V>
and more.
A class we are given is BinarySearchTree<T extends Comparable<T>> implements Iterable<T>
and many more.
I am struggling to determine how to declare my TreeMap
. Should it extend BinarySearchTree
, or implement Map
, or both?
So far, what I have come up with is public class TreeMap<K, V> implements Map<Comparable<K>, V>
and will then create the TreeMap
nested class, but then I do not see where I would "use the BinarySearchTree
class to implement the map"? Do I create a new BinarySearchTree<TreeEntry<K, V>>
inside my TreeMap
class?
EDIT
This is what I have written so far:
public class TreeMap<K, V> implements Map<Comparable<K>, V> {
private class TreeEntry<K, V> implements Entry<K, V>, Comparable<K> {
private K key;
private V value;
public TreeEntry(K key, V value) {
this.key = key;
this.value = value;
}
@Override
public int compareTo(K otherKey) {
if (this.key.equals(otherKey)) {
return 0;
}
else if (this.key > otherKey) {
return 1;
}
else {
return -1;
}
}
@Override
public K getKey() {
// TODO Auto-generated method stub
return null;
}
@Override
public V getValue() {
// TODO Auto-generated method stub
return null;
}
@Override
public V setValue(V value) {
// TODO Auto-generated method stub
return null;
}
}
}
I believe I am not implementing Comparable<K>
correctly as I am getting an error for the line else if (this.key > otherKey)
saying that The operator > is undefined for the argument type(s) K, K
Using the BinarySearchTree as an implementation is currently an assignment. It could be your current idea or somebody's suggestion on how to do it. If you inherit from it and at a later point, when thousands of customers use your TreeMap and you decide that BinarySearchTree is not the perfect implementation, then you will not be able to change it anymore.
This is because somebody might have used it as
BinarySearcTree<X,Y> map = new TreeMap<>();
Now what? You're stuck with your inheritance of BinarySearchTree. But if you "only" implement Map, then you can at any time change the implementation of the class without causing problems to clients.