Java 集合操作之List 类

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18948359/article/details/87741989

简述

List 子接口是 Collection 中最为常用的一个子接口。其功能是允许重复项的有序集合。List 接口是一个有序集合,在集合中每个元素都有其对应的顺序索引,并且能通过索引来访问指定位置的集合元素。

List 接口对Collection接口进行了一些功能上的扩充:

No. 方法名称 类型 描述
1 public E get(int index) 普通 取得索引编号内容
2 public E set(int index,E element) 普通 修改指定索引编号内容
3 public ListIterator<E> listIterator() 普通 为ListIterator接口实例化

List 属于接口,所以要使用此接口方法,必须使用其子类ArrayList实现操作。

ArrayList

ArrayList 基础使用

ArrayList 是 List 接口下最为常用的一个子类。

import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {

	public static void main(String[] args) {
		// 新建一个子类
		List<String> all = new ArrayList<>();

		System.out.println("长度:" + all.size() + ",是否为空:" + all.isEmpty() + "。");
		all.add("Hello");
		all.add("Hello");// 重复
		all.add("World");
		System.out.println("长度:" + all.size() + ",是否为空:" + all.isEmpty() + "。");

		for (int i = 0; i < all.size(); i++) {
			String str = all.get(i); // 取得索引数据
			System.out.println(str); // 循环输出
		}
	}
}
长度:0,是否为空:true。
长度:3,是否为空:false。
Hello
Hello
World

为Collection接口实例化

ArrayList是List接口子类,而List又是Collection子接口,自然可以通过ArrayList为Collection接口实例化。以下的输出结果与上面一段代码的输出结果相同:

import java.util.ArrayList;
import java.util.Collection;

public class ArrayListTest {

	public static void main(String[] args) {
		// 使用 Collection 新建一个子类
		Collection<String> all = new ArrayList<>();

		System.out.println("长度:" + all.size() + ",是否为空:" + all.isEmpty() + "。");
		all.add("Hello");
		all.add("Hello");// 重复
		all.add("World");
		System.out.println("长度:" + all.size() + ",是否为空:" + all.isEmpty() + "。");

		// 由于 Collection 没有 get 方法,所有使用对象数组输出
		Object[] obj = all.toArray();	
		for (int i = 0; i < obj.length; i++) {
			System.out.println(obj[i]);
		}
	}
}

Vector

在最早 JDK 1.0 的时候就已经提供有 Vector 类,并且这个类大量使用。但是在 JDK 1.2 的时候由于类集框架的引入,对于整个集合的操作就有新的标准,让 Vector 类多实现了一个 List 接口。

import java.util.List;
import java.util.Vector;
 
public class Demo {
	
	public static void main(String[] args) throws Exception {
		List<String> all = new Vector<>();
		System.out.println("元素数量:" + all.size() + ",是否为空链表:" + all.isEmpty());
		all.add("Hello");
		all.add("Hello");
		all.add("world");
		System.out.println("元素数量:" + all.size() + ",是否为空链表:" + all.isEmpty());
		for (int i = 0; i < all.size(); i++) {
			System.out.println(all.get(i));
		}
 
	}
}

ArrayList 与 Vector 的区别:

No. 区别 ArrayList Vector
1 推出时间 JDK1.2(new) JDK1.0(old)
2 性能 异步处理 同步处理
3 数据安全 非线程安全 线程安全
4 输出 Iterator,ListIterator,foreach Iterator,ListIterator,foreach,Enumeration

猜你喜欢

转载自blog.csdn.net/qq_18948359/article/details/87741989