4、集合与数组同属于容器范围内,但是二者有明显不同,最显著不同是,集合存储的元素,不必为同一种类型,而且集合存储元素的数量是可变的。
------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------
List接口有三个常用实现类——ArrayList、LinkedList、Vector,Set接口有两个常用实现类——HashSet、TreeSet。
遍历一个Collection的最佳方式是使用Iterator接口,这个借口有三个方法,hasNext(),next,remove()。
一、List
List的特点是向这个容器中添加元素是有序的,而且允许添加多个相同的元素。
包括add(index, element)、addAll (index,Collection)、remove(index)、set (index, element)、get(index)、subList(from, to).、listIterator();
(1)ArrayList
ArrayList底层实现为数组,但是其内部实现的数组大小是可变的,并且选择性的实现了List接口中的方法。可以存储任意类型的元素,甚至包括null类型。除了实现List接口中的方法外,还提供了操作其用来存储List数据的内部Array大小的方法。
ArrayList的特点是向这个容器中添加元素是有序的,而且允许添加多个相同的元素。
ArrayList中常见方法有add ,clear,size,remove等方法。
ArrayList的遍历:
ArrayList<String> al1 = new ArrayList<String>();
al1.add("abc");
al1.add("789");
al1.add("ddd");
Iterator it = al1.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
(2)LinkedList
底层实现为链表结构,增删速度很快,但是查询慢。
LinkedList中独有的方法有addFirst(),addLast(),getFirst(),getLast(),removeFirst(),removeLast(),在以上方法中,带有First的方法,都是在表头进行操作,而带有Last的方法,都是从尾部进行操作。
例如,addFirst(),是在链表的头部插入一个元素:
LinkedList al2 = new LinkedList();
al2.add("111");
al2.add("222");
al2.add("333");
al2.addFirst("000");
System.out.println(al2);
对LinkedList的遍历,基本与ArrayList相同。
(3)Vector
Vector类在出现在jdk1.0版本,底层实现为数组。由于该类操作效率低,已经被ArrayList所取代。
List接口下三个实现类的比较:
ArrayList:底层实现为数组结构,查询速度很快,但是增删慢
LinkedList:底层实现为链表结构,增删速度很快,但是查询慢
Vector:与ArrayList一样,底层实现是数组,该类出现比ArrayList早,现在基本已经被ArrayList取代。相比ArrayList,Vector是线程同步的的,而ArrayList线程不同步,但是由于Vector增删改查太慢,现在已经基本不再需要Vector了。