代码呈现
import java.util.ArrayList;
public class ArrayListTest {
public static void main(String[] args) {
//创建集合
ArrayList<String> list = new ArrayList();
//添加元素
list.add("A");
list.add("B");
list.add("C");
list.add("D");
//遍历集合
System.out.print("[");
for (int i = 0; i < list.size(); i++) {
if (i == list.size() - 1) {
System.out.print(list.get(i));
}else {
System.out.print(list.get(i) + ", ");
}
}
System.out.println("]");
}
}
代码呈现
import java.util.ArrayList;
public class ArrayListTest2 {
public static void main(String[] args) {
//创建一个集合
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
//遍历
System.out.print("[");
for (int i = 0; i <list.size() ; i++) {
if (i == list.size() - 1){
System.out.print(list.get(i));
}else {
System.out.print(list.get(i) + ", ");
}
}
System.out.println("]");
}
}
代码呈现
student类
public class Student {
//私有化成员变量
//空参构造方法
//待全部参数的构造方法
//get set方法
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
代码
import java.util.ArrayList;
public class ArrayListTest4 {
public static void main(String[] args) {
//创建集合
ArrayList<Student> list = new ArrayList();
//创建学生对象
Student s1 = new Student("zhangsan",23);
Student s2 = new Student("lisi",22);
Student s3 = new Student("wangwu",21);
//添加元素
list.add(s1);
list.add(s2);
list.add(s3);
//遍历集合
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
System.out.println(stu.getName()+", "+stu.getAge());
}
}
}
代码呈现
student类用上一题的类
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListTest5 {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList();
//键盘录入并添加到集合
Scanner sc = new Scanner(System.in);
for (int i = 0; i <3 ; i++) {
Student s = new Student();
System.out.println("请输入学生姓名");
String name = sc.next();
System.out.println("请输入学生年龄");
int age = sc.nextInt();
//把name 和 age 赋值给集合
s.setName(name);
s.setAge(age);
//把学生对象添加到集合
list.add(s);
}
System.out.println(list.size());
}
}