List集合_常用方法
List接口介绍
1 public class Demo01List {
2 public static void main(String[] args) {
3 //创建一个List集合对象,多态
4 List<String> list=new ArrayList<>();
5 //使用add方法往集合中添加元素
6 list.add("a");
7 list.add("b");
8 list.add("C");
9 list.add("D");
10 //打印集合
11 System.out.println(list); //不是地址,重写了toString方法
12 }
13 }
编译结果:

1.
//public void add(int index, E element): 将指定的元素,添加到该集合中的指定位置上。
list.add(3,"h"); //指定索引处3添加h
System.out.println(list);
编译结果:

2.
//public E remove(int index): 移除列表中指定位置的元素, 返回的是被移除的元素。
//移除元素
String removeE = list.remove(2); //返回的是被移除的元素
System.out.println(list);
System.out.println(removeE);
编译结果:

3.
// public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值的更新前的元素。
//把最后的D替换成d
String s = list.set(3, "d"); //返回的是被替换的元素
System.out.println(s);
System.out.println(list);
编译结果:

get方法通过遍历来表现
遍历的三种方法:
//List集合遍历有3种方式
//使用普通的for循环
for(int i=0; i<list.size(); i++){
//public E get(int index):返回集合中指定位置的元素。
String l = list.get(i);
System.out.println(l);
}
System.out.println("-----------------");
//使用迭代器
Iterator<String> it = list.iterator();
while(it.hasNext()){
String m = it.next();
System.out.println(m);
}
System.out.println("-----------------");
//使用增强for
for (String n : list) {
System.out.println(n);
}
编译结果:
a
b
h
d
-----------------
a
b
h
d
-----------------
a
b
h
d
注意事项:
操作索引的时候,一定要防止索引越界异常
IndexOutOfBoundsException:索引越界异常,集合会报
ArrayIndexOutOfBoundsException:数组索引越界异常
StringIndexOutOfBoundsException:字符串索引越界异常

浙公网安备 33010602011771号