Java generics and casting to a primitive type

后端 未结 3 677
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-04 00:01

I am currently trying to learn how to use Generics from a book. In this chapter it says to take a piece of data T and convert it to an integer. I am trying different things

3条回答
  •  天涯浪人
    2020-12-04 00:37

    try to observe below examples:

    public static void main(String[] args) {
        test0("13");
        test0(new Integer(13));
        test1();
        System.out.println(findValue(new Node("10")));
    }
    
    private static  void test0(T a) {
        LinkedList arr = new LinkedList();
        arr.add((T) a);
        System.out.println(arr.getFirst());
    }
    
    private static  void test1() {
        LinkedList arr = new LinkedList();
        arr.add((T) new Integer(13));
        System.out.println(arr.getFirst());
    }
    
    public static  int findValue(Node node) {
        T data = (T) node.data;
        int value = Integer.valueOf(data.toString());
        return value;
    }
    

    where Node is :

        public class Node {
    
        //this should be private
            public String data;
    
            public Node(String data) {
                this.data = data;
            }
    
        //use getter below to access private data
        public String getData() {
                return data;
            }
    
      }
    

    all this is possible because, unchecked casts from a known type to T is allowed (of course with warnings) and compiler believes you for the casting.

提交回复
热议问题