集合 List


List (有序列表) 是最基础的集合。

基本和数组相似,都是从下标0开始,不过添加和删除等操作比数组的执行效率更高,具体试下可以去 廖雪峰的教程 查看详解。

List接口可以通过 数组(ArraylList)链表(LinkedList) 实现
在这里插入图片描述

常用操作
List< E >作用
void add(E e)在末尾添加一个元素
void add(int index, E e)在指定索引添加一个元素
int remove(int index)删除指定索引的元素
int remove(Object e)删除某个元素
E get(int index)获取指定索引的元素
int size()元素的个数
boolean contains(Object e)是否包含某个元素
set(int index, E e)在指定索引改变一个元素
indexOf(E e) / lastIndexOf(E e)返回指定元素首次/最后一次出现的位置,不存在返回-1
subList(int fromIndex, int toIndex)生成子列表
isEmpty()是否为空
equals(List e)判断列表是否相同
toString()转换为字符串
toArray()转换为数组
创建
List<String> list = new ArrayList<>(); //创建空列表
List<Integer> list = List.of(1, 2, 5);	//创建指定列表,无法指定null,可add(null)
遍历
//E为元素类型

// for + get 遍历
for (int i=0; i<list.size(); i++)
	E s = list.get(i);

//get 只对 ArrayList 高效,所以可调用迭代器 iterator
for (Iterator<String> it = list.iterator(); it.hasNext(); ) {
	E s = it.next();

//如果只需从头到尾输出,不需其他操作,可用 for each
//for each 无法修改和赋值
for (E s : list)
	System.out.println(s);
覆写equals方法

对于自定义类,使用equals方法时,必须覆写。

equals()方法要求我们必须满足以下条件:

  • 自反性(Reflexive):对于非null的x来说
    x.equals(x) return true
  • 对称性(Symmetric):对于非null的x和y来说
    x.equals(y)==y.equals(x)
  • 传递性(Transitive):对于非null的x、y和z来说
    若x.equals(y)==y.equals(z),则x.equals(z)==x.equals(y)==y.equals(z)
  • 一致性(Consistent):对于非null的x和y来说,
    只要x和y状态不变,则x.equals(y)总是一致地返回true或者false
  • 对null的比较:x.equals(null) return false

覆写方法:

  • 先确定实例“相等”的逻辑,即哪些字段相等,就认为实例相等;
  • 用instanceof判断传入的待比较的Object是不是当前类型,如果是,继续比较,否则,返回false;
  • 对引用类型用Objects.equals()比较,对基本类型直接用==比较。
  • 使用Objects.equals()比较两个引用类型是否相等的目的是省去了判断null的麻烦。两个引用类型都是null时它们也是相等的。

如果不调用List的contains()、indexOf()这些方法,那么放入的元素就不需要实现equals()方法。

public class Person {
    public String name;
    public int age;
}

public boolean equals(Object o) {
    if (o instanceof Person) {
        Person p = (Person) o;
        return Objects.equals(this.name, p.name) && this.age == p.age;
    }
    return false;
}
ArrayList和LinkedList底层分析

以下摘录自 一篇文章搞定ArrayList和LinkedList所有面试问题

数组和链表的特性差异,本质是:连续空间存储和非连续空间存储的差异,主要有下面两点:

  • ArrayList:

    • 底层是Object数组实现的:由于数组的地址是连续的,数组支持O(1)随机访问;
    • 数组在初始化时需要指定容量;数组不支持动态扩容;但是它们的底层实际做了扩容;数组扩容代价比较大,需要开辟一个新数组将数据拷贝进去,数组扩容效率低;适合读数据较多的场合
    • 初始容量为 10,最大容量 Integer.MAX_VALUE-8( -8作为自己需要8 bytes存储大小的数组 )(Integer.MAX_VALUE=231-1)
    • 扩容后为原来容量的1.5倍
    • 底层数组存/取元素(get/set),时间复杂度是O(1),而查找,插入和删除元素时间复杂度为O(n)
  • LinkedList:

    • 底层使用一个Node数据结构,有前后两个指针,双向链表实现的
    • 相对数组,链表插入效率较高,只需要更改前后两个指针即可;另外链表不存在扩容问题,因为链表不要求存储空间连续,每次插入数据都只是改变last指针;另外,链表所需要的内存比数组要多,因为他要维护前后两个指针;它适合删除,插入较多的场景
ArrayList
public class ArrayList<E> extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
    private static final long serialVersionUID = 8683452581122892189L;
 
    /**
     * Default initial capacity.
     */
    //默认容量是10
    private static final int DEFAULT_CAPACITY = 10;
 
    /**
     * Shared empty array instance used for empty instances.
     */
    //当传入ArrayList构造器的容量为0时用这个数组表示:容器的容量为0
    private static final Object[] EMPTY_ELEMENTDATA = {};
 
    /**
     * Shared empty array instance used for default sized empty instances. We
     * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
     * first element is added.
     */
    //主要作为一个标识位,在扩容时区分:默认大小和容量为0,使用默认容量时采取的是“懒加载”
    //即等到add元素的时候才进行实际容量的分配,后面扩容函数讲解还会提到这
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
 
    /**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
 
    //ArrayList底层使用Object数组保存的元素的
    transient Object[] elementData; // non-private to simplify nested class access
 
    /**
     * The size of the ArrayList (the number of elements it contains).
     *
     * @serial
     */
    //记录当前容器中有多少元素
    private int size;
 
    //最常用的构造器之一,实际上就是创建了一个指定大小的Object数组来保存之后add的元素
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }
 
//无参构造器,指向的是默认容量大小的Object数组,注意使用无参构造函数的时候并没有直接创建容量 
//为10的Object数组,而是采取懒加载的策略:使用DEFAULTCAPACITY_EMPTY_ELEMENTDATA(实际容量为0)
//作为标识,在真正add元素时才会开辟Object数组,即在扩容函数中有处理默认容量的逻辑,后面会有分析
    public ArrayList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }
 
   //省略一部分不常用代码函数
 
 
   //add是ArrayList最常用的接口,逻辑很简单,
   public boolean add(E e) {
     //主要用于标识线程安全,即ArrayList只能在单线程环境下使用,在多线程环境下会出现并发安全问 
     //题,modCount主要用于记录对ArrayList的修改次数,如果一个线程操作期间modCount发生了变化
     //即,有多个线程同时修改当前这个ArrayList,此时会抛出“ConcurrentModificationException”
     //异常,这又被称为“failFast机制”,在很多非线程安全的类中都有failFast机制:HashMap、 
     //LinkedList等。这个机制主要用于迭代器、加强for循环等相关功能,也就是一个线程在迭代一个容器 
     //时,如果其他线程改变了容器内的元素,迭代的这个线程会抛 
     //出“ConcurrentModificationException”异常
 
        modCount++;
 
        //add操作的核心函数,当使用无参构造器时并没有直接分配大小为10的Object数组,这里面有对应 
        //的处理逻辑
        add(e, elementData, size);
        return true;
    }
    private void add(E e, Object[] elementData, int s) {
        if (s == elementData.length)//如果使用无参构造器:开始时length为0,s也为0
            elementData = grow();//核心函数
        elementData[s] = e;
        size = s + 1;
    }
     private Object[] grow() {
        return grow(size + 1);//继续追踪
    }
    private Object[] grow(int minCapacity) {
        //使用数组复制的方式,扩容:将elementData所有元素复制到一个新数组中,这个新数组的长度是 
        //newCapacity()函数的返回值,之后再把这个新数组赋值给elementData,完成扩容
        //进入newCapacity()函数
        return elementData = Arrays.copyOf(elementData,
                                           newCapacity(minCapacity));
    }
     private int newCapacity(int minCapacity) {//返回的是扩容后数组的长度
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容后为原来容量的1.5倍
        if (newCapacity - minCapacity <= 0) {
            if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)//默认容量的处理
                return Math.max(DEFAULT_CAPACITY, minCapacity);
    
            //minCapacity是int类型,有溢出的可能,也就是ArrayList最大大小是Integer.MAX_VALUE
            if (minCapacity < 0) // overflow
                throw new OutOfMemoryError();
 
            return minCapacity;
        }
 
        //MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8,当扩容后大于MAX_ARRAY_SIZE ,返回 
       //hugeCapacity(minCapacity),其实就是Integer.MAX_VALUE
        return (newCapacity - MAX_ARRAY_SIZE <= 0)
            ? newCapacity
            : hugeCapacity(minCapacity);
    }
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE)
            ? Integer.MAX_VALUE
            : MAX_ARRAY_SIZE;
    }
 
//最后看下ArrayList的failFast机制
//fail-fast 机制是java集合(Collection)中的一种错误机制。当多个线程对同一个集合的内容进行操作时,就可能会产生fail-fast事件。
//例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件。在详细介绍fail-fast机制的原理之前,先通过一个示例来认识fail-fast。
private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        //在迭代之前先保存modCount的值,modCount在改变容器元素、容器大小时会自增
        int expectedModCount = modCount;
 
        // prevent creating a synthetic constructor
        Itr() {}
 
        public boolean hasNext() {
            return cursor != size;
        }
 
        @SuppressWarnings("unchecked")
        public E next() {
           //使用迭代器遍历元素的时候先检查modCount的值是否等于预期的值,进入该函数
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }
    
      //可以发现:在迭代期间如果有线程改变了容器,此时会抛出“ConcurrentModificationException”
       final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
LinkedList
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    //LinkedList的size是int类型,但是后面会看到LinkedList大小实际只受内存大小的限制
    //也就是LinkedList的size大小可能发生溢出,返回负数
    transient int size = 0;
 
    /**
     * Pointer to first node.
     */
    //LinkedList底层使用双向链表实现,并保留了头尾两个节点的引用
    transient Node<E> first;//头节点
 
    /**
     * Pointer to last node.
     */
    transient Node<E> last;//尾节点
 
 
//省略一部分无关代码,LinkedList内部类Node
private static class Node<E> {
        E item;//元素值
        Node<E> next;//后继节点
        Node<E> prev;//前驱节点,即Node是双向链表
 
        Node(Node<E> prev, E element, Node<E> next) {//Node的构造器
            this.item = element;
            this.next = next;
            this.prev = prev;
        }
    }
 
//LinkedList无参构造器:什么都没做
public LinkedList() {}
 
//LinkedList的大部分接口都是基于这几个接口实现的:
//1.往链表头部插入元素
//2.往链表尾部插入元素
//3.在指定节点的前面插入一个节点
//4.删除链表的头结点
//5.删除除链表的尾节点
//6.删除除链表中的指定节点
 
private void linkFirst(E e) {//1.往链表头部插入元素
        final Node<E> f = first;
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;//failFast机制
    }
 
    /**
     * Links e as last element.
     */
    void linkLast(E e) {//2.往链表尾部插入元素
        final Node<E> l = last;
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;//failFast机制
    }
 
    /**
     * Inserts element e before non-null Node succ.
     */
    void linkBefore(E e, Node<E> succ) {//3.在指定节点(succ)的前面插入一个节点
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;//failFast机制
    }
 
    /**
     * Unlinks non-null first node f.
     */
    private E unlinkFirst(Node<E> f) {//4.删除链表的头结点
        // assert f == first && f != null;
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;//failFast机制
        return element;
    }
 
    /**
     * Unlinks non-null last node l.
     */
    private E unlinkLast(Node<E> l) {//5.删除除链表的尾节点
        // assert l == last && l != null;
        final E element = l.item;
        final Node<E> prev = l.prev;
        l.item = null;
        l.prev = null; // help GC
        last = prev;
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;//failFast机制
        return element;
    }
 
    /**
     * Unlinks non-null node x.
     */
    E unlink(Node<E> x) {//6.删除除链表中的指定节点
        // assert x != null;
        final E element = x.item;
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;
 
        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }
 
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }
 
        x.item = null;
        size--;
        modCount++;//failFast机制
        return element;
    }
 
 
  //LinkedList常用接口的实现
  public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);//调用  4.删除链表的头结点  实现
    }
 
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);//调用  5.删除除链表的尾节点  实现
    }
 
   public void addFirst(E e) {
        linkFirst(e);//调用  1.往链表头部插入元素  实现
    }
 
   public void addLast(E e) {
        linkLast(e);//调用  2.往链表尾部插入元素  实现
    }
 
  public boolean add(E e) {
        linkLast(e);//调用  2.往链表尾部插入元素  实现
        return true;
    }
 
public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);//调用  6.删除除链表中的指定节点  实现
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);//调用  6.删除除链表中的指定节点  实现
                    return true;
                }
            }
        }
        return false;
    }
 
 
//省略其他无关函数
 
 
//迭代器中的failFast机制
private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned;
        private Node<E> next;
        private int nextIndex;
 
        //在迭代之前先保存modCount的值,modCount在改变容器元素、容器大小时会自增
        private int expectedModCount = modCount;
 
        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }
 
        public boolean hasNext() {
            return nextIndex < size;
        }
 
        public E next() {
            使用迭代器遍历元素的时候先检查modCount的值是否等于预期的值,进入该函数
            checkForComodification();
            if (!hasNext())
                throw new NoSuchElementException();
 
            lastReturned = next;
            next = next.next;
            nextIndex++;
            return lastReturned.item;
        }
    
      //可以发现:在迭代期间如果有线程改变了容器,此时会抛出“ConcurrentModificationException”
      final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值