List集合
java.util.List接口 extends Collection接口
List接口的特点:
1. 有序的集合,存储元素和取出元素的顺序是一致的(存储123 取出123)
2. 有索引,包含了一些带索引的方法
3. 允许存储重复的元素
List接口中带索引的方法(特有):
(1)public void add(int index, E element):将指定的元素,添加到该集合中的指定位置上。
例如: list.add(1,"b");
(2)public E get(int index):返回集合中指定位置的元素。
例如: String s = list.get(0);
(3)public E remove(int index):移除列表中指定位置的元素,返回的是被移除的元素。
例如: String removeE = list.remove(2);
(4)public E set(int index, E element):用指定元素替换集合中指定位置的元素,返回值的更新前的元素
例如: String setE = list.set(4,"A");
注意:
操作索引的时候,一定要防止索引越界异常
IndexOutOfBoundsException:索引越界异常,集合会报
ArrayIndexOutOfBoundsException:数组索引越界异常
StringIndexOutOfBoundsException:字符串索引越界异常
List集合遍历有3种方式:
1. 使用普通的for循环
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
System.out.println(s);
}
2. 使用迭代器
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
3. 使用增强for
for (String s : list) {
System.out.println(s);
}
ArrayList集合
底层是数组实现的,查询快,增删慢,接口大小可变,是不同步的实现(多线程)。
多线程意味着效率高,速度快
LinkedList集合
java.util.LinkedList集合 implements List接口
LinkedList集合的特点:
1. 底层是一个链表结构:查询慢,增删快,是不同步的实现(多线程)
2. 里边包含了大量操作首尾元素的方法
注意:使用LinkedList集合特有的方法,不能使用多态
LinkedList<String> linked = new LinkedList<>();
(1)public void addFirst(E e):将指定元素插入此列表的开头。
例如: linked.addFirst("www");
(2)public void addLast(E e):将指定元素添加到此列表的结尾。此方法等效于add()。
例如: linked.addLast("com");
(3)public void push(E e):将元素推入此列表所表示的堆栈。此方法等效于addFirst(E)。
例如: linked.push("www");
(4)public E getFirst():返回此列表的第一个元素。
例如: String first = linked.getFirst();
(5)public E getLast():返回此列表的最后一个元素。
例如: String last = linked.getLast();
(6)public E removeFirst():移除并返回此列表的第一个元素。
例如: String first = linked.removeFirst();
(7)public E removeLast():移除并返回此列表的最后一个元素。
例如: String last = linked.removeLast();
(8)public E pop():从此列表所表示的堆栈处弹出一个元素。此方法等效于removeFirst()。
例如: String first = linked.pop();
(9)public boolean isEmpty():如果列表不包含元素,则返回true。
例如: if (!linked.isEmpty()) {}
注意:
1. // linked.clear(); // 清空集合中的元素,再获取集合中的元素会抛出NoSuchElementException 没有元素异常
Vector集合(了解)
1.0版本最早期的集合,底层是数组,接口大小可变,是同步的实现(单线程)。
单线程意味着速度低,效率慢 1.2版本后可实现List接口
Set集合
java.util.Set接口 extends Collection接口
Set接口的特点:
1. 不允许存储重复的元素
2. 没有索引,没有带索引的方法,也不能使用普通的for循环遍历
HashSet集合
java.util.HashSet集合 implements Set接口
HashSet特点:
1. 不允许存储重复的元素
2. 没有索引,没有带索引的方法,也不能使用普通的for循环遍历
3. 是一个无序的集合,存储元素和取出元素的顺序有可能不一致
4. 底层是一个哈希表结构(查询的速度非常的快)
Set<Integer> set = new HashSet<>();
1. 使用迭代器遍历set集合
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
Integer n = it.next();
System.out.println(n);
}
2. 使用增强for遍历set集合
for (Integer i : set) {
System.out.println(i);
}