ArrayList 是什么
数组的长度是固定的,无法适应数据变化的需求,因此Java提供了 ArrayList 集合类来解决这个问题。ArrayList 是大小可变的数组的实现,比数组使用起来更加灵活,它的容量能动态增长。关于 Java 集合的更多介绍可以看 Java 集合框架介绍 。
主要方法
- 创建 ArrayList 实例。ArrayList是一个泛型类,全路径为
java.util.ArrayList <E>
,E 可以替换成任意的数据类型,例如 String、Integer、Character等。ArrayList 对象不能存储基本类型,只能存储引用类型的数据。因此不能使用 int,double 等基本数据类型
ArrayList<Integer> list = new ArrayList<Integer>();
// 在 JDK 7 之后,右侧泛型的尖括号之内可以留空,即如下写法
ArrayList<Integer> list = new ArrayList<>();
- 添加元素。在使用add方法添加元素时,创建ArrayList实例的时候定义什么泛型就只能添加什么类型的元素。
// 添加元素到集合尾部
public boolean add(E e)
// 添加元素到指定位置
public void add(int index, E element)
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(3);
list.add(4);
// 索引从 0 开始,1 就是添加到第二个位置
list.add(1, 2);
// 1,2,3,4
- 删除元素。ArrayList类中有两个remove方法,一个删除指定索引下标的元素,一个删除相同元素的元素。其中,如果泛型类是Integer类型,调用remove方法时默认会选择删除指定索引下标的remove方法
public E remove(int index)
public boolean remove(Object o)
ArrayList<String> list = new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
// 1,2,3,4
list.remove(2);
// 1,2,4
list.remove("4");
// 1,3
常用功能
遍历
List<String> list = new ArrayList<>();
list.add("2");
list.add("a");
list.add("4");
list.add("d");
list.add("c");
// 增强for循环
for (String s : list) {
System.out.print(s + "\t");
}
// lambda表达式遍历
list.forEach(s -> System.out.print(s + "\t"));
// 4. 方法引用
list.forEach(System.out::println);
// 2, 4, a, c, d
排序
- 简单泛型,使用JDK提供的方法类进行排序
List<String> list = new ArrayList<>();
list.add("2");
list.add("a");
list.add("4");
list.add("d");
list.add("c");
Collections.sort(list);
// [2, 4, a, c, d]
- 根据泛型对象某个属性进行排序
// 实体类
public class Student implements Comparable<Student>{
private String name;
private Integer age;
@Override
public int compareTo(Student o) {
return this.name.compareTo(o.getName());
}
}
ArrayList<Student> list = new ArrayList<>();
list.add(new Student("aaa", 15));
list.add(new Student("ccc", 19));
list.add(new Student("eee", 25));
list.add(new Student("ddd", 13));
list.add(new Student("bbb", 30));
// 从小到大
list.sort(Comparator.comparingInt(Student::getAge));
// 从大到小
// list.sort((o1, o2) -> {
// 由大到小排序
// return o2.getAge() - o1.getAge();
// });
System.out.println(list);
// [(name=ddd, age=13), (name=aaa, age=15), (name=ccc, age=19), (name=eee, age=25), (name=bbb, age=30)]
// 按名字排序,在泛型类中实现 Comparable 接口后,直接用 Collections 方法中的排序方法
Collections.sort(list);
// 或者使用 stream 流实现排序
List<Student> sort = list.stream().sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList());
// [(name=aaa, age=15), (name=bbb, age=30), (name=ccc, age=19), (name=ddd, age=13), (name=eee, age=25)]
去重
ArrayList<String> list = new ArrayList<>();
list.add("aaa");
list.add("ccc");
list.add("aaa");
list.add("bbb");
list.add("ddd");
list.add("ccc");
// HashSet
Set<String> hashSet = new HashSet<>(list);
List newList = new ArrayList(hashSet);
// stream 流
List<String> newList = list.stream().distinct().collect(Collectors.toList());
// [aaa, ccc, bbb, ddd]