代码
提交代码
import java.util.ArrayList;
import java.util.List;
public class ArrayListDemo6 {
static class ImoocStudent {
private String nickname;
private String position;
public ImoocStudent() {
}
public ImoocStudent(String nickname, String position) {
this.setNickname(nickname);
this.setPosition(position);
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
@Override
public String toString() {
return "ImoocStudent{" +
"nickname='" + nickname + '\'' +
", position='" + position + '\'' +
'}';
}
}
public static void main(String[] args) {
// 实例化一个空列表
List<ImoocStudent> arrayList = new ArrayList<>();
// 实例化3个慕课网学生对象
ImoocStudent imoocStudent1 = new ImoocStudent("Colorful", "服务端工程师");
ImoocStudent imoocStudent2 = new ImoocStudent("Lillian", "客户端工程师");
ImoocStudent imoocStudent3 = new ImoocStudent("小慕", "架构师");
// 新增元素
arrayList.add(imoocStudent1);
arrayList.add(imoocStudent2);
arrayList.add(imoocStudent3);
System.out.println(arrayList);
// 删除元素
arrayList.remove(imoocStudent2);
System.out.println("删除 imoocStudent2 后:arrayList 内容为:" + arrayList);
arrayList.remove(1);
System.out.println("删除列表中索引位置为 1 的元素后,arrayList 内容为:" + arrayList);
// 实例化一个新的慕课网学生对象
ImoocStudent imoocStudent4 = new ImoocStudent("小李", "UI设计师");
// 修改元素
arrayList.set(0, imoocStudent4);
System.out.println("修改后:arrayList 内容为" + imoocStudent4);
// 查询元素,将 get() 方法得到的 Object 类型强制转换为 ImoocStudent 类型
ImoocStudent student = arrayList.get(0);
System.out.println("索引位置 0 的学生的昵称为:" + student.getNickname());
System.out.println("索引位置 0 的学生的职位为:" + student.getPosition());
}
}
运行结果