package day3;
import java.util.*;
public class Listtes {
public static void main(String[] args) {
list();
linkedList();
}
/*
java.util.LinkedList集合 implements List接口
LinkedList集合的特点:
1.底层是一个链表结构:查询慢,增删快
2.里边包含了大量操作首尾元素的方法
注意:使用LinkedList集合特有的方法,不能使用多态
- public void addFirst(E e):将指定元素插入此列表的开头。
- public void addLast(E e):将指定元素添加到此列表的结尾。
- public void push(E e):将元素推入此列表所表示的堆栈。
- public E getFirst():返回此列表的第一个元素。
- public E getLast():返回此列表的最后一个元素。
- public E removeFirst():移除并返回此列表的第一个元素。
- public E removeLast():移除并返回此列表的最后一个元素。
- public E pop():从此列表所表示的堆栈处弹出一个元素。
- public boolean isEmpty():如果列表不包含元素,则返回true
*/
public static void linkedList() {
//add method
LinkedList<Integer> a = new LinkedList<Integer>();
Collections.addAll(a,1,2,3);//一次性往集合中添加元素
a.addFirst(123);
a.addLast(321);//等价于a.push();
System.out.println(a);
//get method
if (!a.isEmpty()){
System.out.println(a.getFirst());
System.out.println(a.getLast());
}
//remove method
Integer first = a.removeFirst();
Integer last = a.removeLast();
System.out.println(first);
System.out.println(last);
}
/*
java.util.List接口 extends Collection接口
List接口的特点:
1.有序的集合,存储元素和取出元素的顺序是一致的(存储123 取出123)
2.有索引,包含了一些带索引的方法
3.允许存储重复的元素
List接口中带索引的方法(特有)
- public void add(int index, E element): 将指定的元素,添加到该集合中的指定位置上。
- public E get(int index):返回集合中指定位置的元素。
- public E remove(int index): 移除列表中指定位置的元素, 返回的是被移除的元素。
- public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值的更新前的元素。
注意:
操作索引的时候,一定要防止索引越界异常
IndexOutOfBoundsException:索引越界异常,集合会报
ArrayIndexOutOfBoundsException:数组索引越界异常
StringIndexOutOfBoundsException:字符串索引越界异常
*/
private static void list() {
List<Integer> a = new ArrayList<>();
Collections.addAll(a,3,1,5);
System.out.println(a);
a.add(1,2);//将2插入集合中第二个位置
System.out.println(a);
a.remove(1);
System.out.println(a);//将第二个位置的元素移除
Integer removed = a.set(0, 2);//将第一个位置替换成2
System.out.println(removed);//打印被替换的元素
System.out.println(a);//打印替换后的集合
/*
三种遍历集合的方式:
1、普通for
2、增强for
3、迭代器
*/
//普通for
for (int i = 0; i < a.size(); i++) {
System.out.println(a.get(i));
}
//增强for
for (int i : a){
System.out.println(i);
}
//迭代器
Iterator<Integer> it = a.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
}
java—List集合
于 2022-01-10 22:25:25 首次发布