Loading

java.util.ArrayList

@构造函数

new ArrayList<E>();//无参,最常用内部先指向一个空数组,第一次 add 时才分配容量 10(延迟分配)
new ArrayList<E>(100);//指定初始容量 100	直接分配 Object[100],避免频繁扩容
new ArrayList<E>(otherCollection); //用另一个集合的内容初始化,把 c 里的元素拷进来,容量 = 元素个数,常见另一个List

//常见使用方法,直接把list构造成 ArrayList
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3));


//常见使用方法2,先使用Set去重,再构造成List
Set<List<Integer>> set = new HashSet<>();

set.add(Arrays.asList(-1, 0, 1));
set.add(Arrays.asList(-1, 0, 1)); // 重复,不会再次加入

List<List<Integer>> ans = new ArrayList<>(set);
return ans;

@成员变量

/**
 * The array buffer into which the elements of the ArrayList are stored.
 * 存储ArrayList元素的数组缓冲区
 */
transient Object[] elementData;

@ArrayList 常用方法:

public int size();//返回容器中容纳的元素数
public boolean add(E o);//将指定的元素o添加到列表末尾
public E get(int index);//返回容器列表中指定位置的元素 #第一个的索引为0,即get(0)
public boolean remove(Object o);//从容器列表中删除指定对象元素实例
public E remove(int index);//从容器列表中删除指定索引的元素实例
public int indexOf(Object 0);//返回列表中指定元素的索引,无则返回-1
public E set(int index, E element);//替换指定位置的元素,不是插入。


/**
 * 返回一个迭代器,注意Itr是一个内部类
 */
public Iterator<E> iterator() {
        return new Itr();
    }

@内部类

private class Itr implements Iterator<E>;

@迭代器Iterator

  • 所有继承java.util.Collection的容器都有一个方法iterator(),该方法可以返回一个Iterator对象。
    ​ 方法的声明:
    ​ public Iterator iterator()
    ​ 迭代所用元素的声明:
    ​ Iterator e = a.iterator(); #其中a对象是容器类型。

@Iterator 常用方法:

E next();//返回所访问容器中的下一个元素,第一次调用next()方法时,它返回容器中的第一个元素。get(0)
Bollean hasNext();//判断容器中是否还有元素可以通过next()方法进行访问并返回。
void remove();//删除next指针刚刚跳过去的元素。所以在调用它之前必须调用一次next()方法。

和原生数组 int[] 区别

  1. 原生数组没有 set() 方法
  2. add[] 和 size都没有
  3. ArrayList 可以自动扩容(add方法)
posted @ 2026-09-16 20:35  wsttask  阅读(10)  评论(0)    收藏  举报