十六、ArrayList集合

1、集合和数组的对比

  • 集合的特点:提供一种存储空间可变的存储模型,存储的数据容量可以发生改变
  • 集合和数组的区别:
    • 共同点:都是存储数据的容器
    • 不同点:数组的容量是固定的,集合的容量是可变的

2、ArrayList方法

方法名 说明
构造方法
public ArrayList() 创建一个空的集合对象
添加方法
public boolean add(E e) 将指定元素追加到此集合的末尾
public void add(int index,E element) 在集合中的指定位置插入指定元素
删除方法
public boolean remove(Object obj) 删除指定的元素,返回删除是否成功
public E remove(int index) 删除指定索引处的元素,返回被删除的元素
修改方法
public E set(int index,E element) 修改指定索引处的元素,返回被修改的元素
获取方法
public E get(int index) 返回指定索引处的元素
集合大小
public int size() 返回集合中的元素的个数

3、泛型简要

泛型使用<引用数据类型>来定义。用来约束集合中存储数据的数据类型;只参与编译,不参与运行

// 一般我们创建 ArrayList集合
ArrayList<Student> stuArr = new ArrayList<>();
// 上面这段代码:ArrayList中只能存储Student类的数据类型

4、案例

存储学生对象,把年龄小于18岁的学生遍历出来

public class StudentTest {
    public static void main(String[] args) {
        ArrayList<Student> stu = new ArrayList<>();

        stu.add(new Student("张三", "17"));
        stu.add(new Student("李四", "23"));
        stu.add(new Student("王五", "24"));

        System.out.println(stu);
        ArrayList<Student> sList = stuList(stu);

        System.out.println(sList);
    }

    public static ArrayList<Student> stuList(ArrayList<Student> stuArr){
        ArrayList<Student> newStuArr = new ArrayList<>();

        for(int i=0;i<stuArr.size();i++){
            Student stu = stuArr.get(i);
            String age = stu.getAge();
            if(Integer.parseInt(age) < 18){
                newStuArr.add(stu);
            }
        }
        return newStuArr;
    }
}
posted @ 2021-06-20 17:34  火烧云Z  阅读(45)  评论(0)    收藏  举报