Make a Java class generic, but only for two or three types

后端 未结 7 470
清歌不尽
清歌不尽 2021-01-11 19:17

(I was astonished not to be able to find this question already on stackoverflow, which I can only put down to poor googling on my part, by all means point out the duplicate.

7条回答
  •  孤城傲影
    2021-01-11 19:39

    So here is the why (worked it out at work)

    Generics are always from a subclass, although it looks like

    Public class Thing {}
    

    will allow any type in there, really what it's saying is that it will allow any subtype of Object. I.e.

    Public class Thing {}
    

    This is effectively working as inheritance, and indeed, the Oracle Website shows us this happening when the syntactic sugar is removed:

    In the following example, the generic Node class uses a bounded type parameter:

    public class Node> {
    
        private T data;
        private Node next;
    
        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    
        public T getData() { return data; }
        // ...
    }
    

    The Java compiler replaces the bounded type parameter T with the first bound class, Comparable:

    public class Node {
    
        private Comparable data;
        private Node next;
    
        public Node(Comparable data, Node next) {
            this.data = data;
            this.next = next;
        }
    
        public Comparable getData() { return data; }
        // ...
    }
    

    ...and so the answer turns out that the reason you can't limit the types in this way is because it effectively turns into multiple Inheritance, which is nasty, and which I'm happy to avoid....

提交回复
热议问题