5

I'm trying to figure out the whole Java generics topic.

More specifically this issue:

public class Node<E>{
    private E data;
    public Node(E data){
        this.data=data;
    }
    public E get(){
        return this.data;
    }
    public void set(E data){
        this.data=data;
    }
}

How can I add an "extends" wildcard specifying that the set method can receive E or any inheriting class of E (in which case the Node will hold a upcasted version of the parameter).

Or will it work even if I leave it the way it is?

(I might be a bit confused with the invariant aspect of generic types.)

Thanks!

3
  • 3
    It will already do what you want... Commented Jul 3, 2013 at 7:31
  • I downvoted the question. It is easily answerable if you do a tiny bit of work yourself. You don't even need google, just use ctrl-space in any Java IDE and see for yourself. Commented Jul 3, 2013 at 8:01
  • @Dariusz You're free to do whatever you wish. The thing is, sometimes code will "work" even if you don't really know why or how well it works. That's why I asked here. Commented Jul 3, 2013 at 12:11

4 Answers 4

3

Your class is already doing what you require. Lets demonstrate by example. Lets say you have created Node (Number is super class of Integer, Long etc);

Node<Number> numberNode = new Node<Number>(1);

You can call set method by passing its subclasses also

numberNode.set(new Integer(1));
numberNode.set(new Long(1));
Sign up to request clarification or add additional context in comments.

Comments

3

You declared your class Node<E> where it already accepts any inheriting class of E.

2 Comments

is this different with passing collections as generics? Because when we write someMethod(ArrayList<E>) then only arrayLists with type E can be passed.
@PrasadKharkar Good spotted! Yes they are different.
0

If you use

public void set(E extends SomeType){
 this.data=data;
 }

then you can pass any object that implements or extends SomeType Remeber that SomeType can also be an interface here, even if it is strange, we need to write E extends SomeType.

Comments

0

Or will it work...?

Or have you tried it out if it works?

        final Node<Number> n =  new Node<Number>(new Integer(666));
        System.out.println(n.get());
        n.set(new Integer(777));
        System.out.println(n.get());

Comments

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.