JAVA练习4—ArrayList

如何创建ArrayList?

ArrayList的实例化方法:(附代码)

ArrayList:是长度可变的数组(动态数组)。动态的增加和减少元素;实现了ICollection和IList接口;灵活的设置数组的大小

ArrayList<String> list =new ArrayList<>();

学生类:

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());
	
	}
  }
}

其它

全局变量:

在整个类范围定义的所有方法都可见。

局部变量:

在方法内部定义的称之为局部变量

局部变量没有默认值,必须经过初始化,才可以使用

访问修饰符不能用于局部变量。

复制行快捷键:Ctrl+Alt+下键;

删除行快捷键:Ctrl+D




阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭