集合(Collection(List))

2018-03-29  本文已影响0人  CelloRen
|Collection
   ||List
   ||Set
   ||Queue

我们来看看List的JDK,因为他继承Collection,我们关心它与Set、Collection的区别(和Collection相同的部分就略过不写注释,可参照Collection):

//We can know List is interface and extends Collection
public interface List<E> extends Collection<E> {
///// Query Operations
   int size();
   boolean isEmpty();
   boolean contains(Object o);
   Iterator<E> iterator();
   Object[] toArray();
   <T> T[] toArray(T[] a);
///// Modification Operations
   //Return true if added, appends the element to the end of this list
   boolean add(E e);
   
   //Return true if removed, remove the first occurrence from this list
   boolean remove(Object o);

///// Bulk Modification Operations
   boolean containsAll(Collection<?> c);

   //Return true if all added, appends all the elements of c to this list 
   boolean addAll(Collection<? extends E> c);
   
   //Return true if all added, insert all the elements of c to this list at index
   boolean addAll(int index, Collection<? extends E> c);

      /**In my view, the two operations is hard to achieve based on LinkedList**/
   boolean removeAll(Collection<?> c);
   boolean retainAll(Collection<?> c);

   default void replaceAll(UnaryOperator<E> operator) {}

   //Sort the list according to the comparator c
   default void sort(Comparator<? super E> c) {
        Object[] a = this.toArray();
        Arrays.sort(a, (Comparator) c);
        ListIterator<E> i = this.listIterator();
        for (Object e : a) {
            i.next();
            i.set((E) e);
        }
    }

    void clear();

///// Comparison and hashing
   boolean equals(Object o);
   int hashCode();

///// Positional Access Operations
   //Return the element at index position
   E get(int index);
   
   //Replace the element at index position with the new element, return the previous
   E set(int index, E element);

   //Insert the element at index
   void add(int index, E element);

   //Return the element removed, remove the element at index 
   E remove(int index);
///// Search Operations
   //Return the index of first occurrence that is equal to 0,
   // return -1 if there is no such an element
   int indexOf(Object o);

   //Return the index of last occurrence that is equal to 0,
   // return -1 if there is no such an element
   int indexOf(Object o);

///// List Iterators
   ListIterator<E> listIterator();
   ListIterator<E> listIterator(int index);
}

 ///// View
    List<E> subList(int fromIndex, int toIndex);
  default Spliterator<E> spliterator() {
}

List的实现基础如果是链表,一些方法实现很麻烦,像这两个操作:

boolean removeAll(Collection<?> c);
boolean retainAll(Collection<?> c);

从一个链表删除,它和另一个链表的交集,如果是无序的话,时间复杂度很高;
同理,保留交集,删除其他的, 也麻烦。
所以LinkedList源码里没有这两个方法。
由此也可以初步地引出ArrayList和LinkedList的区别:一个的底层是数组,一个的底层是链表

上一篇 下一篇

猜你喜欢

热点阅读