4

I want to achieve the following.

I have a generic class Node<K,T,V> which looks as follows:

public class Node<K,T,V>{

/**
 * @return the key
 */
public K getKey() {
    return key;
}
/**
 * @param key the key to set
 */
public void setKey(K key) {
    this.key = key;
}
// etc...

Now I want to have a class Tree which operates on Nodes with arbitrary parametrized types:

public class Tree <Node<K,V,T>> {
   public void insert(Node<K,V,T> node){
      K key = node.getKey();
      // do something...
   }
// ... etc...
}

This, however, does not work, since Eclipse tells me the line public class Tree <Node<K,V,T>> does not look good :) If I change it to

public class Tree <Node> {

It tells me that the type Node is hiding the type Node. How can I achieve that from the Tree class I can properly access the types K, V and T?

I'm pretty sure this question has been answered a bazillion times. I did, however, not find anything at all - so sorry for that!!!

Cheers.

2
  • 3
    Welcome to SO. Don't apologize for a good question ;-) Commented Jul 9, 2014 at 10:39
  • Thank you @ChristianSt.! And @Shail016, thank you for the solution. I went for the second solution. It does not read as nicely as my initial try, but it works! Commented Jul 9, 2014 at 10:51

1 Answer 1

6

you can change your tree to :

class Tree<K, T, V> {
    public void insert(Node<K, T, V> node) {
        K key = node.getKey();
        // do something...
    }
    // ... etc...
}

or if you want to bind it to Node,

class Tree2<N extends Node<K, T, V>, K, T, V> {
    public void insert(N node) {
        K key = node.getKey();
        // do something...
    }
    // ... etc...
}
Sign up to request clarification or add additional context in comments.

2 Comments

I was going to write the second one but was too slow, nicely done :) Although it'd be better to maintain the <K,V,T> parameter order.
thanks, edited the order for Node<K,T,V> as defined by the op

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.