Why incompatible type?


  • 2
    P

    List<List<Integer>> result= new LinkedList<LinkedList<Integer>>();
    Why this is incompatible type?


  • 1
    T

    That's just how generics works, consider:

    List<? extends List> result = new LinkedList<LinkedList>();

    but then you won't be able to .add() anything to the list.

    Here's a counterexample why your <LinkedList> is dangerous:

    LinkedList<LinkedList<?>> result0 = new LinkedList<>();
    List<List<?>> result = result0; // invalid assignment (same as constructing the object)
    ArrayList<?> put = new ArrayList<>();
    result.add(put);
    LinkedList<?> get = result0.get(0); // ClassCastException
    

    And a cleaner version:

    Collection<Integer> ints = ...;
    Collection<Number> nums = ints; // similarly unsafe
    nums.add(3.14); // boxed to Double
    Integer val = ints.iterator().next(); // ClassCastException
    

    Don't mind the <?> it's just to make sure everything has a generic argument.
    The best is to use interfaces where possible and let Java 7 figure it out generics for you with <>.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.