ArrayList类

本文主要介绍Java中ArrayList的使用。包括声明和构造ArrayList,添加、设置、获取元素的方法,以及确保容量、调整大小等操作。还提及将ArrayList元素复制到数组,插入和移除元素等内容,最后建议若频繁在集合中间插入和移除元素,可考虑使用链表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.
Declare and construct an array list that holds Employee objects:
ArrayList<Employee> staff = new ArrayList<Employee>();

You can also pass an initial capacity to the ArrayList constructor:
ArrayList<Employee> staff = new ArrayList<Employee>(100);

2.
Add new elements:
staff.add(new Employee("Harry Hacker", . . .));
API:
boolean add(T obj)

3.
If you already know, or have a good guess, how many elements you want to store, then call the ensureCapacity method before filling the array list:
staff.ensureCapacity(100);

4.
The size method returns the actual number of elements in the array list. For example,
staff.size()

5.
You should only use trimToSize when you are sure you won't add any more elements to the array list.
API:
void trimToSize()

6.
To set the ith element, you use
staff.set(i, harry);
API:
void set(int index, T obj)
puts a value in the array list at the specified index, overwriting the previous contents.

To get an array list element, use
Employee e = staff.get(i);

for (Employee e : staff) {...}

7.
You can sometimes get the best of both worlds—flexible growth and convenient element access—with the following trick. First, make an array list and add all the elements.

ArrayList<X> list = new ArrayList<X>();
while (. . .)
{
   x = . . .;
   list.add(x);
}

When you are done, use the toArray method to copy the elements into an array.

X[] a = new X[list.size()];
list.toArray(a);

8.
CAUTION:
Use the add method instead of set to fill up an array, and use set only to replace a previously added element.

9.
Instead of appending elements at the end of an array list, you can also insert them in the middle.

int n = staff.size() / 2;
staff.add(n, e);

10.
Employee e = staff.remove(n);
API:
T remove(int index)
removes an element and shifts down all elements above it. The removed element is returned.

11.
If you store many elements and frequently insert and remove in the middle of a collection, consider using a linked list instead.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值