鉴于Java中数组用来存储数据的局限性,我们通常使用List替代数组
List集合类中元素有序、且可重复,集合中的每个元素都有其对应的顺序索引。
List容器中的元素都对应一个整数型的序号记载其在容器中的位置,可以根据序号存取容器中的元素。
JDK API中List接口的实现类常用的有:
ArrayList
:作为List接口的主要实现类;线程不安全的,效率高;底层使用Object[]、
LinkedList
:底层使用双向链表存储 ,对于频繁的插入、删除操作,使用此类效率比ArrayList高
Vector
:作为List接口的古老实现类,线程安全的,效率低;底层使用Object[])
ArrayList
、LinkedList
、Vector
三者的异同
同:三个类都是实现了list接口,存储数据的特点相同:存储有序的、可重复的数据
不同
不同:见上
ArrayList
的源码分析ArrayList liet = new ArrayList()
底层创建了长度是10的object[]数组elementData
JDK 7的情况下
list.add(123); l/elementData[e] = new Integer(123)
... list.add(11)
;
//如果此次的添加导致底层elementData数组容量不够,则扩容。 默认情况下,扩容为原来的容量的1.5倍,同时需要将原有数组中的数据复制到新的数组中。
结论:建议开发中使用带参的构造器:
JDK8 中ArrayList的变化
ArrayList liet = new ArrayList()
底层的object[]数组elementData初始化为{},并没有创建长度为10的数组
list.add(123)
;//第一次调用add()时,底层才创建了长度为10的数组,并将数据123添加到elementData
后续添加和操作与 7 一样
LinkedList
的源码分析LinkedList list = new LinkedList()
内部生命力Node类型的first和last属性,默认值为null,
list.add()
将123封装到Node中,创建了Node对象
Node定义:体现了LinkedList的双向链表的说法
Vector的源码分析: jdk7和jdk8中通过Vector()构造器创建对象时,底层都创建了长度为10的数在扩容方面,默认扩容为原来的数组长度的2倍。
void add(int index,object ele)
:在index位置插入eLe元素
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add("AA");
list.add(new Person("Tom",20));
list.add(456);
?
System.out.println(list);
?
//void add(int index,object ele):在index位置插入eLe元素
list.add(1,"BB");
?
boolean addAll(int index,collection eLes)
:从index位置开始将eles中的所有元素添加进来
//boolean addAll(int index,collection eLes):从index位置开始将eles中的所有元素添加进来
List list1 = Arrays.asList(1, 2, 3);
list.addAll(list1);
object get(int index)
:获取指定index位置的元素
//object get(int index):获取指定index位置的元素
System.out.println(list.get(1));
int indexof(object obj)
:返回obj在集合中首次出现的位置
//int indexof(object obj):返回obj在集合中首次出现的位置
int index = list.indexOf(456);
System.out.println(index);
int lastIndexof(0bject obj)
:返回obj在当前集合中末次出现的位置object
//int lastIndexof(0bject obj):返回obj在当前集合中末次出现的位置object
int index1 = list.lastIndexOf(456);
System.out.println(index1);
remove(int index)
:移除指定index位置的元素,并返回此元素
//remove(int index):移除指定index位置的元素,并返回此元素
Object remove = list.remove(0);
System.out.println(remove);//删除位置上的元素
System.out.println(list);
object set(int index,object ele)
:设置指定index位置的元素为eLe
//object set(int index,object ele):设置指定index位置的元素为eLe
list.set(1,"cc");
list sublist(int fromIndex, int toIndex)
:返回从fromIndex到toIndex位置的子集合
//list sublist(int fromIndex, int toIndex):返回从fromIndex到toIndex位置的子集合
List subList = list.subList(2, 4);
遍历
//方式一:iterator迭代器 Iterator iterator = list.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next()); } //方式二:增强for循环 for(Object obj:list){ System.out.println(obj); } //方式三:普通for循环 for(int i =0;i < list.size();i++){ System.out.println(list.get(i)); }
原文:https://www.cnblogs.com/flypigggg/p/14614271.html