Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameters of a Java generic method

Tags:

java

generics

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!

like image 483
Paz Avatar asked Jul 03 '13 07:07

Paz


2 Answers

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));
like image 174
sanbhat Avatar answered Sep 22 '22 16:09

sanbhat


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

like image 45
Suresh Atta Avatar answered Sep 20 '22 16:09

Suresh Atta