Shadowing of type parameters

后端 未结 1 1358
花落未央
花落未央 2021-01-14 07:28

I have a very basic question regarding type parameters which I came across while solving a problem.

I have a class with a string array which I am sorting using a cus

相关标签:
1条回答
  • 2021-01-14 08:09

    The problem is with generic type that is called String. It's collision between generic type parameter and actual class String.

    Because the type parameter String is unbounded, the Java compiler replaces it with Object hence arguments of method compare works as Object and object class doesn't have compareTo method hence you have to cast.

    Try below example that works fine.

    class SortComparator<T> implements Comparator<String>
    {
    
        @Override
        public int compare(String o1, String o2) {
            // TODO Auto-generated method stub
            return  o1.compareTo(o2);
        }
    
    }
    

    Please have a look at Java documentation on Erasure of Generic Types

    During the type erasure process, the Java compiler erases all type parameters and replaces each with its first bound if the type parameter is bounded, or Object if the type parameter is unbounded.

    Below Example copied directly from above Java documentation for more clarity.

    Consider the following generic class that represents a node in a singly linked list:

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

    Because the type parameter T is unbounded, the Java compiler replaces it with Object:

    public class Node {
    
        private Object data;
        private Node next;
    
        public Node(Object data, Node next) {
            this.data = data;
            this.next = next;
        }
    
        public Object getData() { return data; }
        // ...
    }
    
    0 讨论(0)
提交回复
热议问题