集合(Collection、数据结构、List
集合体系结构
-
Collection:单列集合,每个元素只包含一个值
-
List:有序、可重复、有索引
- ArrayList
- LinkedList
-
Set:无序、不重复、无索引
-
HashSet:无序、不重复、无索引
- LinkedHashSet:有序、不重复、无索引
-
TreeSet:按照大小默认升序排序、不重复、无索引
-
-
-
Map:双列集合,每个元素包含两个值(键值对)
Collection API如下
| 方法 | 说明 |
|---|---|
| public boolean add(E e) | 把给定的对象添加到当前集合中 |
| public void clear() | 清空集合中所有的元素 |
| public boolean remove(E e) | 把给定的对象在当前集合中删除 |
| public boolean contains(Object obj) | 判断当前集合中是否包含给定的对象 |
| public boolean isEmpty() | 判断当前集合是否为空 |
| public int size() | 返回集合中元素的个数 |
| public Object[] toArray() | 把集合中的元素,存储到数组中 |
迭代器Iterator
Collection集合获取迭代器
| 方法 | 说明 |
|---|---|
| Iterator iterator() | 返回集合中的迭代器对象,该迭代器对象默认指向当前集合的0索引 |
Iterator中的常用方法
| 方法 | 说明 |
|---|---|
| boolean hasNext() | 询问当前位置是否有元素存在,存在返回true ,不存在返回false |
| E next() | 获取当前位置的元素,并同时将迭代器对象移向下一个位置,注意防止取出越界 |
Iterator<String> it = lists.iterator();
while(it.hasNext()){
String ele = it.next();
System.out.println(ele);
}
foreach/增强for循环
格式:
for(String ele : list) {
System.out.println(ele);
}
Lambda表达式遍历集合
Collection结合Lambda遍历的API
| 方法 | 说明 |
|---|---|
| default void forEach(Consumer<? super T> action): | 结合lambda遍历集合 |
格式:
Collection<String> lists = new ArrayList<>();
...
lists.forEach(new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
});
集合中存储的是元素的什么信息?
集合中存储的是元素对象的地址
List集合
| 方法 | 说明 |
|---|---|
| void add(int index,E element) | 在此集合中的指定位置插入指定的元素 |
| E remove(int index) | E remove(int index) |
| E set(int index,E element) | 修改指定索引处的元素,返回被修改的元素 |
| E get(int index) | 返回指定索引处的元素 |
LinkedList特有功能
| 方法 | 说明 |
|---|---|
| public void addFirst(E e) | 在该列表开头插入指定的元素 |
| public void addLast(E e) | 将指定的元素追加到此列表的末尾 |
| public E getFirst() | 返回此列表中的第一个元素 |
| public E getLast() | 返回此列表中的最后一个元素 |
| public E removeFirst() | 从此列表中删除并返回第一个元素 |
| public E removeLast() | 从此列表中删除并返回最后一个元素 |