今日内容
1.ArrayList集合
2.使用ArrayList集合做一个学生管理系统
数组和集合的区别
数组:长度是固定的
集合:长度随着元素的个数发生改变
集合的创建和使用
ArrayList是API中提供的一个类,用来表示集合。ArrayList底层也是数组来实现的,当往集合中存储元素时,会自动对底层的数组进行扩容的。
创建ArrayList集合对象
//<String> 元素的类型为String类型
ArrayList<String> list=new ArrayList<>();
ArrayList集合常用方法
public boolean add(E e) //添加元素
public boolean add(int index, E e) //在指定的索引位置添加元素
public boolean remove(Object obj) //删除元素 移除此列表中首次出现的指定元素(对象)(如果存在)
public E remove(int index) //删除元素
public E set(int index,E e) //修改元素
public E get(int index) //获取元素
public int size() //获取集合中元素的个数
在集合中存储Student对象
先自己定义好Student类(这里省略了),有name和age属性。
//创建集合,用来存储Student对象
ArrayList<Student> list=new ArrayList<>();
//创建3个Student对象
Student s1=new Student("孙悟空",500);
Student s2=new Student("猪悟能",300);
Student s3=new Student("沙悟净",200);
//把对象添加到list集合中去
list.add(s1);
list.add(s2);
list.add(s3);
//遍历list集合中的元素
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
System.out.println(stu.getName()+","+stu.getAge());
}