集合
程序中可能通过数组来保存多个对象,因为数组长度是不可变的。JDK中提供了一些特殊的类,这些类可以存储任何对象,并且长度可变,在java中这些类被为集合。集合类位于java.util包中。
Collection接口
方法声明 | 功能描述 |
---|---|
boolean add(Object o) | 向集合中添加一个元素 |
boolean addAll(Collection c) | 增加一个集合(多个元素) |
void clear() | 清空集合 |
boolean remove(Object o) | 删除集合中的一个对象(元素) |
boolean removeAll(Collection c) | 删除一个集合(多个元素) |
boolean isEmpty() | 是不是空的 |
boolean contains(Object o) | 判断集合有没有这个元素 |
boolean containsAll(Collection c) | 判断集合中有没有参数集合 |
Iterator iterator() | 返回一个遍历迭代器 |
int size() | 返回集合的元素个数 |
List接口
方法声明 | 功能描述 |
---|---|
void add(int index,Object element) | |
boolean addAll(int index,Collection c) | |
Object get(int index) | |
Object remove(int index) | |
Object set(int index,Object element) | |
int indexOf(Object o) | |
int lastIndexOf(Object o) | |
List subList(int fromIndex,int toIndex) | |
ArrayList和LinkedList区别
ArrayList检索数据快。(用量较大);
LinkedList添加数据快。
遍历比for循环速度快。
简单使用
List<Integer> list = new ArrayList<>();
list.add(12);
list.add(0, 22);
System.out.println(list);
list.addAll(List.of(1, 2, 3, 4, 5, 2, 3, 3, 41));
System.out.println(list);
//移除元素2
Integer i = 2;
boolean f = list.remove(i);
System.out.println(f);
System.out.println(list);
//移除第二个元素 下标从零开始。
System.out.println(list.remove(1));
System.out.println(list);
System.out.println("=================================");
//判断集合中有没有41
System.out.println(list.contains(41));
//判断集合和集合 List.of():快速声明一个数组
System.out.println(list.containsAll(List.of(1, 2, 3)));
Collections.reverse(list);
//查看集合的大小
System.out.println(list.size());
for (int a1 : list) {
System.out.printf("list[%d]=%d ", list.indexOf(a1), a1);
}
System.out.println();
for (int j = 0; j < list.size(); j++) {
System.out.printf("list[%d]=%d ", j, list.get(j));
}
System.out.println();
//使用迭代器遍历
Iterator<Integer> it = list.listIterator();
while (it.hasNext()) {
System.out.println(it.next());
}