List 是一个有序、可重复的集合,集合中每个元素都有其对应的顺序索引。List 集合允许使用重复元素,可以通过索引来访问指定位置的集合元素。List 集合默认按元素的添加顺序设置元素的索引,第一个添加到 List 集合中的元素的索引为 0,第二个为 1,依此类推。
List 实现了 Collection 接口,它主要有两个常用的实现类:ArrayList 类和 LinkedList 类。
ArrayList类
ArrayList 类实现了可变数组的大小,存储在内的数据称为元素。它还提供了快速基于索引访问元素的方式,对尾部成员的增加和删除支持较好。使用 ArrayList 创建的集合,允许对集合中的元素进行快速的随机访问,不过,向 ArrayList 中插入与删除元素的速度相对较慢。
ArrayList 类的常用构造方法有如下两种重载形式:
ArrayList():构造一个初始容量为 10 的空列表。
ArrayList(Collection<?extends E>c):构造一个包含指定 Collection 元素的列表,这些元素是按照该 Collection 的迭代器返回它们的顺序排列的。
ArrayList 类除了包含 Collection 接口中的所有方法之外,还包括 List 接口中提供的如表 1 所示的方法。
表 1 ArrayList类的常用方法
方法名称 | 说明 |
---|---|
E get(int index) | 获取此集合中指定索引位置的元素,E 为集合中元素的数据类型 |
int index(Object o) | 返回此集合中第一次出现指定元素的索引,如果此集合不包含该元素,则返回 -1 |
int lastIndexOf(Object o) | 返回此集合中最后一次出现指定元素的索引,如果此集合不包含该元素,则返回 -1 |
E set(int index, Eelement) | 将此集合中指定索引位置的元素修改为 element 参数指定的对象。此方法返回此集合中指定索引位置的原元素 |
List subList(int fromlndex, int tolndex) | 返回一个新的集合,新集合中包含 fromlndex 和 tolndex 索引之间的所有元素。包含 fromlndex 处的元素,不包含 tolndex 索引处的元素 |
注意:当调用 List 的 set(int index, Object element) | 方法来改变 List 集合指定索引处的元素时,指定的索引必须是 List 集合的有效索引。例如集合长度为 4,就不能指定替换索引为 4 处的元素,也就是说这个方法不会改变 List 集合的长度。 |
import java.util.ArrayList;
import java.util.List;
public class ArrayListTest01 {
public static void main(String[] args) {
Product product01 = new Product(1,"饼干",3);
Product product02 = new Product(2,"牛奶",4);
Product product03 = new Product(3,"面包",4);
List list = new ArrayList<>();
list.add(product01);
list.add(product02);
list.add(product03);
System.out.println("商品信息");
for (Object p:list
) {
System.out.println(p);
}
}
}
LinkedList类
LinkedList 类采用链表结构保存对象,这种结构的优点是便于向集合中插入或者删除元素。需要频繁向集合中插入和删除元素时,使用 LinkedList 类比 ArrayList 类效果高,但是 LinkedList 类随机访问元素的速度则相对较慢。这里的随机访问是指检索集合中特定索引位置的元素。
表 2 LinkList类中的方法
方法名称 | 说明 |
---|---|
void addFirst(E e) | 将指定元素添加到此集合的开头 |
void addLast(E e) | 将指定元素添加到此集合的末尾 |
E getFirst() | 返回此集合的第一个元素 |
E getLast() | 返回此集合的最后一个元素 |
E removeFirst() | 删除此集合中的第一个元素 |
E removeLast() | 删除此集合中的最后一个元素 |
import java.util.LinkedList;
public class LinkedListTest01 {
public static void main(String[] args) {
LinkedList<String> products = new LinkedList<>();
String p1 =new String("商品1");
String p2 =new String("商品2");
String p3 =new String("商品3");
String p4 =new String("商品4");
String p5 =new String("商品5");
products.add(p1);
products.add(p2);
products.add(p3);
products.add(p4);
products.add(p5);
String p6 =new String("商品6");
products.addLast(p6);
System.out.println("----------------商品信息----------------------");
for (Object o:products
) {
System.out.print(o+"\t");
}
}
}
ArrayList 类和 LinkedList 类的区别
ArrayList 与 LinkedList 都是 List 接口的实现类,因此都实现了 List 的所有未实现的方法,只是实现的方式有所不同。
ArrayList 是基于动态数组数据结构的实现,访问元素速度优于 LinkedList。LinkedList 是基于链表数据结构的实现,占用的内存空间比较大,但在批量插入或删除数据时优于 ArrayList。
对于快速访问对象的需求,使用 ArrayList 实现执行效率上会比较好。需要频繁向集合中插入和删除元素时,使用 LinkedList 类比 ArrayList 类效果高。
不同的结构对应于不同的算法,有的考虑节省占用空间,有的考虑提高运行效率,对于程序员而言,它们就像是“熊掌”和“鱼肉”,不可兼得。高运行速度往往是以牺牲空间为代价的,而节省占用空间往往是以牺牲运行速度为代价的。
学习资料
学习资料地址:http://c.biancheng.net/view/6847.html