Collection子接口 其一:List接口List

接口存储结构:元素有序,且可重复,每个元素都有对应的索引
根据索引获取容器元素

实现类有:ArrayList、LinkedList、Vector

三个实现类的异同?

- 都实现了List接口,存储数据的特点相同、存储有序的、可重复的数据

- ArrayList  是List接口的主要实现类,线程不安全的,但是效率高,底层Object[] elementData存储

- LinkedList  双向链表结构存储,对于插入和删除频繁操作,效率比ArrayList高

- Vector  初代List接口实现类,线程安全,效率低。底层Object[]存储

List的接口常用方法【索引支持】

在指定索引位置添加元素

public void add(int index, E element)

    /**
* Inserts the specified element at the specified position in this
* list. 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 IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
rangeCheckForAdd(index); ensureCapacityInternal(size + 1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}

从参数的容器对象的索引位置开始到结尾,添加元素到调用此方法的容器对象

public boolean addAll(int index, Collection<? extends E> c)

    /**
* Inserts all of the elements in the specified collection into this
* list, starting at the specified position. Shifts the element
* currently at that position (if any) and any subsequent elements to
* the right (increases their indices). The new elements will appear
* in the list in the order that they are returned by the
* specified collection's iterator.
*
* @param index index at which to insert the first element from the
* specified collection
* @param c collection containing elements to be added to this list
* @return <tt>true</tt> if this list changed as a result of the call
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws NullPointerException if the specified collection is null
*/
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index); Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved); System.arraycopy(a, 0, elementData, index, numNew);
size += numNew;
return numNew != 0;
}

按索引获取元素

public E get(int index)

    /**
* Returns the element at the specified position in this list.
*
* @param index index of the element to return
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E get(int index) {
rangeCheck(index); return elementData(index);
}

返回元素的索引位置,如果是重复了多个元素,返回第一个的位置

public int indexOf(Object o)

    /**
* Returns the index of the first occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the lowest index <tt>i</tt> such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}

返回元素的索引位置,如果多个重复元素,返回最后一个出现的

public int lastIndexOf(Object o)

    /**
* Returns the index of the last occurrence of the specified element
* in this list, or -1 if this list does not contain the element.
* More formally, returns the highest index <tt>i</tt> such that
* <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
* or -1 if there is no such index.
*/
public int lastIndexOf(Object o) {
if (o == null) {
for (int i = size-1; i >= 0; i--)
if (elementData[i]==null)
return i;
} else {
for (int i = size-1; i >= 0; i--)
if (o.equals(elementData[i]))
return i;
}
return -1;
}

移除参数的索引上的元素,并返回元素

public E remove(int index)

    /**
* Removes the element at the specified position in this list.
* Shifts any subsequent elements to the left (subtracts one from their
* indices).
*
* @param index the index of the element to be removed
* @return the element that was removed from the list
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E remove(int index) {
rangeCheck(index); modCount++;
E oldValue = elementData(index); int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // clear to let GC do its work return oldValue;
}

修改指定索引位置的元素

public E set(int index, E element)

    /**
* Replaces the element at the specified position in this list with
* the specified element.
*
* @param index index of the element to replace
* @param element element to be stored at the specified position
* @return the element previously at the specified position
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public E set(int index, E element) {
rangeCheck(index); E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}

截取一段,返回指定起始位置到结束位置的元素到一个新的容器上 【返回子集合】

public List<E> subList(int fromIndex, int toIndex)

    /**
* Returns a view of the portion of this list between the specified
* {@code fromIndex}, inclusive, and {@code toIndex}, exclusive. (If
* {@code fromIndex} and {@code toIndex} are equal, the returned list is
* empty.) The returned list is backed by this list, so non-structural
* changes in the returned list are reflected in this list, and vice-versa.
* The returned list supports all of the optional list operations.
*
* <p>This method eliminates the need for explicit range operations (of
* the sort that commonly exist for arrays). Any operation that expects
* a list can be used as a range operation by passing a subList view
* instead of a whole list. For example, the following idiom
* removes a range of elements from a list:
* <pre>
* list.subList(from, to).clear();
* </pre>
* Similar idioms may be constructed for {@link #indexOf(Object)} and
* {@link #lastIndexOf(Object)}, and all of the algorithms in the
* {@link Collections} class can be applied to a subList.
*
* <p>The semantics of the list returned by this method become undefined if
* the backing list (i.e., this list) is <i>structurally modified</i> in
* any way other than via the returned list. (Structural modifications are
* those that change the size of this list, or otherwise perturb it in such
* a fashion that iterations in progress may yield incorrect results.)
*
* @throws IndexOutOfBoundsException {@inheritDoc}
* @throws IllegalArgumentException {@inheritDoc}
*/
public List<E> subList(int fromIndex, int toIndex) {
subListRangeCheck(fromIndex, toIndex, size);
return new SubList(this, 0, fromIndex, toIndex);
} static void subListRangeCheck(int fromIndex, int toIndex, int size) {
if (fromIndex < 0)
throw new IndexOutOfBoundsException("fromIndex = " + fromIndex);
if (toIndex > size)
throw new IndexOutOfBoundsException("toIndex = " + toIndex);
if (fromIndex > toIndex)
throw new IllegalArgumentException("fromIndex(" + fromIndex +
") > toIndex(" + toIndex + ")");
}

List支持的三种遍历方式

public class Array {
public static void main(String[] args) {
List list = new ArrayList();
list.add("元素1");
list.add("元素2");
list.add("元素3");
list.add("元素4");
list.add("元素5");
list.add("元素6"); // 第一种 迭代器实现遍历
Iterator iterator = list.iterator(); while (iterator.hasNext()){
System.out.println(iterator.next());
} // 第二种 ForEach
for (Object object : list) {
System.out.println(object);
} // 第三种 For
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}

注意点: remove的重载

如何判断注入的是按元素删除?还是按索引删除?

- 按元素删除,建议使用 new Integer(10) 这样对基本类型数据包装再注入   arrayList.remove(new Integer(5));

- 按索引删除,默认注入数字值即可   arrayList.remove(3);


ArrayList的底层源码查看【未完待续...】

JDK8

底层elementData初始化为0

但是注释依赖没改,仍然称为10初始化容量

只有在第一次调用add后初始化10的容量,再往后大于10【右移1 除2】增加1.5倍容量

【Java】Collection子接口:其一 List 列接口的更多相关文章

  1. Java基础-Collection子接口之List接口

    Java基础-Collection子接口之List接口 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 我们掌握了Collection接口的使用后,再来看看Collection接口中 ...

  2. Java基础-Collection子接口之Set接口

    Java基础-Collection子接口之Set接口 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 学习Collection接口时,记得Collection中可以存放重复元素,也可 ...

  3. Collection子接口(List/Set/Queue/SortedSet)

    Collection基本的子接口: List:能够存放反复内容 Set:不能存放反复内容,全部反复的内容靠hashCode()和equals()两个方法区分 Queue:队列接口 SortedSet: ...

  4. Java面向对象之 接口: [修饰符] interface 接口名 {...};子接口:[修饰符] interface 接口名 extends 父接口,父接口2...{...}

    1.什么是接口? 类比抽象类,把功能或者特性类似的一类 抽象的更彻底,可以提炼出更加特殊的"抽象类"----接口 2.如何定义接口 语法:  [修饰符] interface 接口名 ...

  5. Java学习关于集合框架的基础接口--Collection接口

     集合框架(Collection  Framework)是Java最强大的子系统之一,位于java.util 包中.集合框架是一个复杂的接口与和类层次,提供了管理对象组的最新技术.Java集合框架标准 ...

  6. java Collection接口

    Collection 1——————Set子接口:无序,不允许重复. 2——————List子接口:有序,允许重复. Set和List对比: 1.set:检索元素的效率比较低,删除和插入效率比较高,删 ...

  7. 自顶向下理解Java集合框架(三)Map接口

    Map基本概念 数据结构中Map是一种重要的形式.Map接口定义的是查询表,或称查找表,其用于储存所谓的键/值对(key-value pair),其中key是映射表的索引. JDK结构中还存在实现Ma ...

  8. 数据结构-List接口-LinkedList类-Set接口-HashSet类-Collection总结

    一.数据结构:4种--<需补充> 1.堆栈结构:     特点:LIFO(后进先出);栈的入口/出口都在顶端位置;压栈就是存元素/弹栈就是取元素;     代表类:Stack;     其 ...

  9. Effective Java 第三版——41.使用标记接口定义类型

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  10. Java第二十天,Map集合(接口)

    Map接口 一.定义 Map集合是双列集合,即一个元素包含两个值(一个key,一个value),Collection集合是单列集合. 定义格式: public interface Map<K,V ...

随机推荐

  1. flutter3-weos手机OS系统|Flutter3.22+Getx仿ios桌面管理OA应用

    原创自研flutter3.x+getx仿制ios手机桌面UI管理系统模板Flutter3-OS. flutter3-osx基于最新跨平台技术Flutter3.22+Dart3.4+GetX+fl_ch ...

  2. 使用swiper完成轮播图

    swiper:https://www.swiper.com.cn/usage/index.html 安装swiper cnpm i -S swiper 在功能组件中定义Swiper组件并设置好插槽 & ...

  3. Linux高级命令

    重定向 重定向也称为输出重定向,用于将命令的输出保存到目标文件. 使用方法:> 文件名 或 >> 文件名.前者会覆盖文件内容,后者会追加内容到文件. 查看文件内容命令 cat: 显示 ...

  4. 实验6.交换机MAC地址表简单实验

    # 实验6.交换机Mac地址表 本实验用于验证和测试交换机的Mac地址表的特性. 实验组 测试 测试在PC1没有pingPC2时,此时mac表为空 当PC1ping一个其他的ip而不是PC2时,无论是 ...

  5. DPO: Direct Preference Optimization 直接偏好优化(学习笔记)

    学习参考:链接1   一.为什么要提出DPO 在之前,我们已经了解到基于人类反馈的强化学习RLHF分为三个阶段:全监督微调(SFT).奖励模型(RM).强化学习(PPO).但是RLHF面临缺陷:RLH ...

  6. Linux gpio子系统:gpio_direction_output 与 gpio_set_value的区别

    Linux gpio子系统:gpio_direction_output 与 gpio_set_value的区别 背景 最近改驱动程序,看到驱动代码中既有gpio_direction_output也有g ...

  7. Linux中的IDR机制

    # Linux中的IDR机制 背景 最近在学习 Linux的i2c子系统,看到代码中有关于IDR的调用.了解了一下有关的文档,发现是用来管理指针(对象实例). //based on linux V3. ...

  8. mtr和traceroute的区别,以及为什么traceroute不显示路径mtr却可以显示路径

    最近工作主要都是网络策略的开通和网络测试,在测试的过程当中发现当网络不通时,用traceroute来看路由路径的时候总是无法显示出来,于是就换了个工具-mtr,发现mtr可以正常显示出路由路径,帮助我 ...

  9. k8s实战 ---- pod 基础

    如果你对k8s还不了解,可以看下前文 k8s 实战 1 ---- 初识       (https://www.cnblogs.com/jilodream/p/18245222) 什么是pod,pod在 ...

  10. makedown 笔记

    前言 记录一下自己经常忘的makedown指令,不断更新. makedown 添加空格