java语言基础List集合

List与ArrayList

LIst集合
List集合是一个元素有序且可重复的集合,集合内的每个元素有对应顺序索引。

允许用索引访问指定索引位置的元素,索引默认按元素添加顺序,List集合有根据索引的方法。

实现
继承
ArrayList类
List接口
Collection接口

List接口方法

查询方法名 方法用途
get() 通过索引下标访问元素
indexOf() 元素在集合第一次出现的索引下标
lastIndexOf() 元素在集合最后一次出现的索引下标
size() 查询集合长度
subList() 索引下标起始位置截取元素形成新的集合(截取时包含截取时的索引,不包含结束时的索引)
更新方法名 方法用途
add() 1.直接添加元素在集合末尾 2.添加元素在指定索引位置
addAll() 1.直接添加集合的所有元素在集合末尾 2.添加集合的所有元素在指定索引位置
remove() 1.移除指定元素 2.移除指定索引位置的元素
set() 指引索引下标修改元素

Vector类和ArrayList类
Vector类和ArrayList类都是List接口的实现方法,Vector是古老的类,ArrayList是新的类。
Arraylist是线程不安全的,Vector是安全的。
即使为了保证list集合的线程安全,也不推荐使用Vector。

实现方法代码:

		//创建list集合
		List<String> list = new ArrayList<String>();
		
		//add()实现1
		list.add("a"); 		//索引下标为0,以此类推
		list.add("b");		
		list.add("c");		
		list.add("d");	
		list.add("c");
		System.out.println(list);
		
		

		//add()实现2
		list.add(2,"f");
		System.out.println(list); 
		
		//addAll()实现1
		List<String> l1 = new ArrayList<String>();
		l1.add("123");
		l1.add("456");
		list.addAll(l1);
		System.out.println(list);
		
		//addAll()实现2
		List<String> l2 = new ArrayList<String>();
		l2.add("789");
		l2.add("000");
		list.addAll(2,l2);
		System.out.println(list);

		//set()
		list.set(1, "ff");//指引下标修改
		System.out.println(list);

		//remove()
		list.remove("123");//移除指定元素
		System.out.println(list);
		list.remove(2);//移除指定索引位置的元素
		System.out.println(list);

		//访问
		System.out.println(list.indexOf("c"));//第一次出现的索引下标
		System.out.println(list.lastIndexOf("c"));//最后一次出现的索引下标
		System.out.println(list.get(1)); //通过索引下标访问
		List<String> sublist = list.subList(2, 4);
		//索引下标起始位置截取元素形成新的集合,
		//截取时包含截取时的索引,不包含结束时的索引,以上包含2不包含4
		System.out.println(sublist);
		System.out.println(list.size());//集合长度
	

		

输出结果
[a, b, c, d, c]
[a, b, f, c, d, c]
[a, b, f, c, d, c, 123, 456]
[a, b, 789, 000, f, c, d, c, 123, 456]
[a, ff, 789, 000, f, c, d, c, 123, 456]
[a, ff, 789, 000, f, c, d, c, 456]
[a, ff, 000, f, c, d, c, 456]
4
6
ff
[000, f]
8

发布了10 篇原创文章 · 获赞 3 · 访问量 821

猜你喜欢

转载自blog.csdn.net/sdutxkszy/article/details/105540291