Why does arraylist class implement List as well as extend AbstractList?

后端 未结 8 2043
青春惊慌失措
青春惊慌失措 2020-12-05 02:29

The implementation of java.util.ArrayList implements List as well as extends AbstractList. But in java docs you can see that AbstractL

相关标签:
8条回答
  • 2020-12-05 03:18

    Then wouldn't it be redundant to implement List as well as extend AbstractList?

    Yes, it is 100% redundant. However, Java implementors added interfaces very consistently in all public implementation of the collections library:

    • LinkedList<E> and ArrayList<E> extend AbstractList<E> which implements List<E>, and then implement List<E> themselves.
    • HashSet<E> and TreeSet<E> extend AbstractSet<E> which implements Set<E>, and then implement Set<E> themselves.
    • HashMap<K,V> and TreeMap<E> extend AbstractMap<K,V> which implements Map<K,V>, and then implement Map<K,V> themselves.

    My understanding is that they did so for documentation purposes: the authors wanted to show that ArrayList<E> is primarily a List<E>; the fact that ArrayList<E> extends AbstractList<E> is a less significant detail of its implementation. Same goes for the other public collection types.

    Note that Arrays.ArrayList<E> class is not publicly visible, so its authors did not care to include List<T> explicitly.

    As far as the failed conversion goes, this should come as no surprise, because the inner class Arrays.ArrayList<E> and the public class ArrayList<E> are unrelated to each other.

    0 讨论(0)
  • 2020-12-05 03:26

    just wanna to complement answers to question 2

    java.util.ArrayList<String> a=Arrays.asList(stra);
    

    compiler just knows the return type of Arrays.asList is List, but does not know its exact implementation which may not be java.util.ArrayList. So you got this compile time error.

    Type mismatch: cannot convert from List to ArrayList

    you can force an upper cast explicitly like this,

    java.util.ArrayList<String> a =(java.util.ArrayList<String>)Arrays.asList(stra);
    

    The code will compile successfully, but a runtime exception will happen,

    java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList

    this is because java.util.Arrays$ArrayList (the type of implemenation which Arrays.asList returns) is not a subtype of java.util.ArrayList.

    0 讨论(0)
提交回复
热议问题