Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble swapping values as keys in generic java BST class

Tags:

java

generics

I was given a generic binary search tree class with the following declaration:

public class BST<K extends Comparable<K>, V>

I was asked to write a method that reverses the BST such that the values become the keys and keys become values. When I call the following method (defined in the class given)

reverseDict.put(originalDict.get(key), key); 

I get the following two error messages from Netbeans:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous sym type: BST.put

And also:

no suitable method found for put(V,K) method BST.put(BST<K,V>.Node,K,V) is not applicable (actual and formal argument lists differ in length) method BST.put(K,V) is not applicable (actual argument V cannot be converted to K by method invocation conversion) where V,K are type-variables:

V extends Object declared in method <K,V>reverseBST(BST<K,V>)

K extends Comparable<K> declared in method <K,V>reverseBST(BST<K,V>)

From what the error messages are telling me, since my values do not extend Comparable I am unable to use them as keys. If I am right, how can I get around that without changing the class given (maybe a cast)?

like image 387
Andy Avatar asked Aug 24 '26 00:08

Andy


1 Answers

I think the problem is that you need a V extends Comparable<V> in order to use it as key, but you have only a V without bounds. I think you need to write a static method like..

public static <A extends Comparable<A>, B extends Comaparable<B>> 
    BST<B,A> invert(BST<A,B> bst) {...}

.. in order to ensure that additional condition.

like image 145
Landei Avatar answered Aug 26 '26 14:08

Landei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!