原创

Java中集合(List)


  • 上次说到Collection接口是List和Set的顶级父接口,这次说说List。

  • 打开List的源码可以看到:

/**
 * An ordered collection (also known as a <i>sequence</i>).  The user of this
 * interface has precise control over where in the list each element is
 * inserted.  The user can access elements by their integer index (position in
 * the list), and search for elements in the list.<p>
 *
 * Unlike sets, lists typically allow duplicate elements.  More formally,
 * lists typically allow pairs of elements <tt>e1</tt> and <tt>e2</tt>
 * such that <tt>e1.equals(e2)</tt>, and they typically allow multiple
 * null elements if they allow null elements at all.  It is not inconceivable
 * that someone might wish to implement a list that prohibits duplicates, by
 * throwing runtime exceptions when the user attempts to insert them, but we
 * expect this usage to be rare.<p>
  • 这两段其实可以作为面试题回答的一部分:(List 和 Set 有何不同?)

  1. 第一段明确讲到,List是有序的列表,用户可以通过控制元素的索引来精确控制每个元素。

  2. 第二段也很明了,List允许重复(相等)元素,并且通常也允许null元素。

然后看这一段:

 * The <tt>List</tt> interface provides a special iterator, called a
 * <tt>ListIterator</tt>, that allows element insertion and replacement, and
 * bidirectional access in addition to the normal operations that the
 * <tt>Iterator</tt> interface provides.  A method is provided to obtain a
 * list iterator that starts at a specified position in the list.<p>
  • 大致意思是List接口提供了一个专有的迭代器:ListIterator。,他支持元素的插入和替换,双向访问,Iterator不具有的功能。还支持从指定位置开始获得ListIterator。

  • 我们看一下:ListIterator

列表迭代器 其实就是多个几个索引的方法:得到前/后一个元素/索引,是否有前/后一个元素/索引。

  • 我们看一下List接口的方法:

List接口

  • 不难看出: 多出来的方法基本是和索引有关的(因为他是有序的嘛,当然就可以指定下标)

  1. 添加: add(int index, E element),addAll(int index, Collection<? extends E> c),set(int index, E element)

  2. 获取: get(int index),indexOf(Object o), lastIndexOf(Object o),listIterator(),remove(int index),subList(int fromIndex, int toIndex)

  • AbstractList类实现了List接口的部分方法

数据结构
基础
javase
  • 作者:管理员(联系作者)
  • 发表时间:2020-03-19 10:26
  • 版权声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证)
  • 公众号转载:请在文末添加作者公众号二维码
  • 微信公众号

    评论

    留言