list列表
List列表的主要特征是其元素以线性方式存储,集合中允许存放重复对象。List接口的主要实现类包括:
- ArrayList:代表长度可变的数组。允许对元素进行快速的随机访问(即检索位于特定索引位置的元素),但是向ArrayList中插入与删除元素较慢。
- 在实现中采用了链表数据结构,对顺序访问进行了优化,向其中插入与删除元素较快,随机访问速度则较慢LinkList单据具有addFirst()、addLast()、getFirst()、getLast()、removeFirst()、rmoveLast()方法。
- Vector 底层数据结构是数组,查询块,增删慢 线程安全效率低
List集合的特有功能概述和测试
- void add(int index,E element): 在指定索引处添加元素
- E remove(int index):移除指定索引处的元素 返回的是移除的元素
- E get(int index):获取指定索引处的元素
- E set(int index,E element):更改指定索引处的元素 返回的而是被替换的元素
List集合的特有遍历功能
public static void main(String[] args) {
List list = new ArrayList();
list.add(new Student("周星驰",20));
list.add(new Student("周星驰2", 20));
list.add(new Student("周星驰3", 20));
list.add(new Student("周星驰4", 20));
list.add(new Student("周星驰5", 20));
list.add(new Student("周星驰6", 20));
list.add(new Student("周星驰7", 20));
list.add(new Student("周星驰8", 20));
list.add(new Student("周星驰9", 20));
list.add(new Student("周星驰10", 20));
//迭代器遍历
Iterator iterator = list.iterator();
while (iterator.hasNext()){
Student student = (Student) iterator.next();
System.out.println(student.getName()+"==="+student.getAge());
}
System.out.println("------------------");
//for循环遍历
for (int i = 0; i < list.size(); i++) {
Object o = list.get(i);
Student student= (Student) o;
System.out.println(student.getName() + "===" + student.getAge());
}
}
list集合排序
List只能对集合中的对象按照索引位置进行排序,如果希望按其他方式排序,可以借助Comparator接口和Collection类。Collection类是Java集合类库中的辅助类,它提供了操纵集合的各种静态方法,其中sort()方法用于对List中的对象进行排序:
1、sort(List list) :对List中对象进行自然排序。
2、sort(List list,Comparator comparator) :对List中对象进行自定排序。
在这里插入代码片
```public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add(10);
list.add(20);
list.add(30);
list.add(40);
list.add(4);
list.add(60);
list.add(40);
list.add(50);
list.add(60);
list.add(40);
list.add(50);
list.add(60);
//void sort (Comparator < ? super E > c)
//分类列表使用提供的 Comparator比较元素。
//
//void forEach (Consumer < ? super E > action)
//执行特定动作的每一个元素的 Iterable直到所有元素都被处理或操作抛出异常。
// Comparator 比较器,是一个接口,
list.sort(new Comparator() {
@Override
public int compare(Object a, Object b) {
Integer aa = (Integer) a;
Integer bb = (Integer) b;
return bb - aa; //根据差值 的正 负 0 就会排列集合中的元素
}
});
//第二种
list.sort((a, b) -> {
Integer aa = (Integer) a;
Integer bb = (Integer) b;
return bb - aa;
});
System.out.println(list);
//第三种
// Consumer
//JDK1.8 提供的新语法 Lmabda 表达式
list.forEach(System.out::println);
System.out.println("---------------");
list.forEach(new Consumer() {
@Override
public void accept(Object o) {
System.out.println(o);
}
});
}