ArrayList基本知识
概念:ArrayList是长度可变的数组,集合对象
使用方法:
ArrayList stringList = new ArrayList();
↑
此处为类型
补充:
1.删除:在ArrayList中使用remove命令
2.添加:在ArrayList中使用add命令
ArrayList 使用for循环和foreach循环
以学生类为例的调用:
for:for (int i = 0; i < studentList.size(); i++) {
Stud a = studentList.get(i);
System.out.println(a.getName() + “今年” + a.getAge() + “岁是” + a.getClassname() + “的学生。”);
}
foreach:for (Stud a : studentList) {
System.out.println(“他叫” + a.getName() + “今年” + a.getAge() + “岁是” + a.getClassname() + “的学生。”);
}
关于全局变量和局部变量
1.在整个类范围内定义的,所有方法都可见的,称为全局变量;
2.在方法内部定义的,称为局部变量
- public class Student {
- private String name;
- private String className;
- private int age;
- private int grade;
- public Student() {}
- public Student(String name, String className, int age, int grade) {
- this.name = name;
- this.className = className;
- this.age = age;
- this.grade = grade;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getClassName() {
- return className;
- }
- public void setClassName(String className) {
- this.className = className;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getGrade() {
- return grade;
- }
- public void setGrade(int grade) {
- this.grade = grade;
- }
- }
测试类:
- import java.util.ArrayList;
- public class Test {
- public static void main(String[] args) {
- ArrayList<Student> studentList = new ArrayList<>();
- Student s1 = new Student("xz","1班",19,60);
- Student s2 = new Student("xw","2班",20,70);
- Student s3 = new Student("xp","3班",19,65);
- Student s4 = new Student("xy","4班",20,90);
- Student s5 = new Student("xx","5班",19,84);
- studentList.add(s1);
- studentList.add(s2);
- studentList.add(s3);
- studentList.add(s4);
- studentList.add(s5);
- //查询数据
- for(int i=0;i<studentList.size();i++) {
- Student s = studentList.get(i);
- System.out.println("姓名:"+s.getName()+"今年"+s.getAge()+"岁,在"+s.getClassName()+"成绩是"+s.getGrade());
- }
- studentList.remove(studentList.size()-1);//删除最后一行数据。
- System.out.println();
- for(Student stu : studentList) {
- System.out.println("姓名:"+stu.getName()+"今年"+stu.getAge()+"岁,在"+stu.getClassName()+"成绩是"+stu.getGrade());
- }
- }
- }
本文介绍ArrayList的基本概念及使用方法,通过具体的学生信息管理案例演示了如何使用for循环和foreach循环进行数据操作,并解释了全局变量与局部变量的区别。
7952

被折叠的 条评论
为什么被折叠?



