Acor74u
Acor74u

Reputation: 17

Polymorphic binary search tree type mismatch error

I am making a polymorphic binary search tree for an assignment consisting of NonEmptyTree and EmptyTree objects. Each NonEmptyTree has a comparable key and a value associated to it (as well as a right and left Tree objects).

I am writing a lookup method that takes a key object and returns the value associated with it.

NonEmptyTree:

package tree;

@SuppressWarnings("unchecked")
public class NonEmptyTree<K extends Comparable<K>, V> implements Tree<K, V> {

    private K key;
    private V value;
    private Tree left, right;

    public NonEmptyTree(K key, V value) {
            this.key = key;
            this.value = value;
            left = right = EmptyTree.getInstance();//Singleton class
    }

    public V lookup(K keyToLookFor) throws NullPointerException{
        if (keyToLookFor.compareTo(key) > 0)
            return right.lookup(keyToLookFor);
        else if (keyToLookFor.compareTo(key) < 0)
            return left.lookup(keyToLookFor);
        else
            return value;
    }
}

EmptyTree:

    public V lookup(K keyToLookFor) {
        return null;
    }

when I try to return right.lookup or left.lookup, eclipse gives a type mismatch error and asks me to cast it to type V and I have no idea why. We are not allowed to use casting in this project so I could really use some help

Upvotes: 1

Views: 531

Answers (1)

muued
muued

Reputation: 1676

You need to restrict the types of the left and right members:

private Tree<K,V> left, right;

This way the calls to left.lookup and right.lookup will return the same V as the containing class.

Upvotes: 1

Related Questions