简体   繁体   中英

Parameters of a Java generic method

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!

您声明了Node<E>类,它已经接受了E任何继承类。

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));

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 .

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM