JAVA集合框架之List Set接口

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012364631/article/details/78428977

List和Set接口直接继承了Collection接口,我们看看他们分别有什么属于自己的特殊方法:

List

这里写图片描述这里写图片描述

注意这个小三角符号,带有三角符号的说明是父接口的方法,没有三角符号的是自己定义的方法

add

所以,第二个add方法是List特有的方法,来看看他有什么特殊之处:
还记得父接口Collection中只有一个boolean add(E e);方法,
而List接口中定义了一个void add(int index, E element);

/**
     * Inserts the specified element at the specified position in this list
     * (optional operation).  Shifts the element currently at that position
     * (if any) and any subsequent elements to the right (adds one to their
     * indices).
     *
     * @param index index at which the specified element is to be inserted
     * @param element element to be inserted
     * @throws UnsupportedOperationException if the <tt>add</tt> operation
     *         is not supported by this list
     * @throws ClassCastException if the class of the specified element
     *         prevents it from being added to this list
     * @throws NullPointerException if the specified element is null and
     *         this list does not permit null elements
     * @throws IllegalArgumentException if some property of the specified
     *         element prevents it from being added to this list
     * @throws IndexOutOfBoundsException if the index is out of range
     *         (<tt>index &lt; 0 || index &gt; size()</tt>)
     */

从方法的注释可以看到,这个add方法要求 Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices

还有一个boolean addAll(int index, Collection

重载的方法

观察一下规律,对于父接口Collection中的许多通用方法,List接口都重载了一份,·这是因为List支持下标操作:
这里写图片描述

其他特有方法

这里写图片描述

操作 Collection List重载 List特有
add()
addAll()
add() addAll() set(i,obj)
remove()
removeAll()
removeIf()
remove
removeAll
replaceAll
contains()
containsAll()
Get
indexOf
lastIndexOf
其他 Iterator ListIterator
Sort
subList

ListIterator

Collection中有个Iterator()方法 返回Iterator
而List中又多了个ListIterator()方法 ,返回ListIterator
注意到:ListIterator也是个接口,继承了Iterator接口

这里写图片描述

其中hasPrevious() 和previous()对应于hasNext() next(),用于逆序遍历List
由于List可以通过index访问,所以相对于previous() next()返回泛型对象,previousIndex() nextIndex()返回下一个index
而set(E e)是:修改刚刚由next()或previous()返回的元素
add(E e)是 : 在下一个元素之前或上一个元素之后,插入一个元素

Set

这里写图片描述

Set具有与Collection完全一样的接口,因此没有任何额外的功能,不像前面有两个不同的List。实际上Set就是Collection,只是行为不同。也就是说,如果有人想要实现Set接口,那么他就必须满足Set的“约定”——不含重复元素,否则出了问题后果自负。

猜你喜欢

转载自blog.csdn.net/u012364631/article/details/78428977