1

I'm trying to implement TreeMap class, and I'm having a problem while putting elements in the TreeMap. Here's the code:

public class TreeMap<K,V> implements Map<K,V> {

    private Comparator<K> comparator;
    private int size;
    private Node<K,V> head;

    public TreeMap(Comparator<K> comparator){
        this.comparator = comparator;
        size = 0;
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public V put(K key, V value) {
        return rootPut(head, key, value);
    }

    private V rootPut(Node<K,V> node, K key, V value){
        if(isEmpty()){
            node = new Node<>(key, value);
            size++;
            return null;
        }
        int compare = comparator.compare(head.key, key);

        if(compare == 0){
            V auxValue = node.value;
            node.value = value;
            size++;
            return auxValue;
        } else if(compare > 0){
            return rootPut(node.right, key, value);
        } else{
            return rootPut(node.left, key, value);
        }
    }
}

The problem is that when I execute this line:

node = new Node<>(key, value);

node is always null. I've already tried debugging the code, but the problem persists.

The other methods I didn't include here because they work.

gla3dr
  • 2,179
  • 16
  • 29
Joaco Terniro
  • 115
  • 1
  • 2
  • 13

1 Answers1

0

You have:

if(isEmpty()){
    node = new Node<>(key, value);

surely this should be

if(isEmpty()){
    head = new Node<>(key, value);

NB: This does not fix all of your bugs but it does fix the my head is always null problem.

OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213
  • But isn't the same?? Which is the difference?? – Joaco Terniro Sep 25 '15 at 14:25
  • @JoacoTerniro - No! `node` is a local copy of whatever `head` contained when the method was called so is probably `null`. `head` is the **instance variable** in the object. By using `head = new...` you change the `head` value of your tree - as you want. Using `node = ...` you change nothing. – OldCurmudgeon Sep 25 '15 at 14:27
  • Ohh okay, im relatevly new in java and i didn't know that. Thank you very much! – Joaco Terniro Sep 25 '15 at 14:50
  • @JoacoTerniro - Some good explanations [here](http://stackoverflow.com/q/40480/823393). – OldCurmudgeon Sep 25 '15 at 15:02