案列一,集合的遍历
package com.itheima.Demo3_遍历集合;
/** 创建一个存储字符串的集合,存储3个字符串元素,使用程序实现在控制台遍历该集合*/
import java.util.ArrayList;
/**
* @author ChenY@itheima.com
* @date 2022/7/13 11:40
*/
public class Test1 {
public static void main(String[] args) {
ArrayList<String> aStr = new ArrayList<>();
aStr.add("itheima");
aStr.add("100");
aStr.add("years");
/** 遍历集合中的字符串*/
for (int i = 0; i < aStr.size(); i++) {
String str = aStr.get(i);
System.out.print(str+" ");
}
}
}
案例二 键盘录入Student类信息存到 集合中去
package com.itheima.Demo4键盘录入存储学生对象;
/**
* @author ChenY@itheima.com
* @date 2022/7/13 14:48
*/
public class Student {
/** 定义成员变量*/
private String name;
private int age;
/** 定义构造方法*/
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
/** 定义set和get方法*/
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;
}
}
package com.itheima.Demo4键盘录入存储学生对象;
import java.util.ArrayList;
import java.util.Scanner;
/**
* @author ChenY@itheima.com
* @date 2022/7/13 14:52
*/
public class Test {
public static void main(String[] args) {
/** 创建集合对象和学生对象*/
ArrayList<Student> aList = new ArrayList<>();
addStudent(aList);
addStudent(aList); /** 因为集合是可变的 不是固定的参数*/
addStudent(aList);
addStudent(aList);
/** 遍历出集合中的元素*/
for (int i = 0; i < aList.size(); i++) {
Student stu = aList.get(i);
System.out.println(stu.getName()+", "+stu.getAge());
}
}
/** 为了提高代码的复用性 将重复键盘录入的 code封装成方法*/
/** 目的是将键盘录入的学生信息存入集合中去 可以直接将集合作为数据类型 每输入一个学生信息就会 放进集合中去*/
public static void addStudent(ArrayList<Student> aList){
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生的姓名");
String aName = sc.next();
System.out.println("请输入学生的年龄");
int aAge = sc.nextInt();
/** 创建学生对象 通过满参构造 将键盘录入的学生信息的参数 传递个构造方法的形参 目的是为了完成对象的初始化*/
Student stu = new Student(aName,aAge);
/** 将这个学生对象添加到集合中去*/
aList.add(stu);
}
}
总结 将键盘录入的重复code 写成方法,在方法里 创建Student类对象,将键盘录入的信息通过 参数传递给 类的构造函数 然后new 对象 初始化 最后通过add()追加到 集合中去
addStudent(aList); 引用类型的变量 按引用调用 传递的地址 集合可变
当然也可以通过循环实现
for (int i = 0; i < 4; i++) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入学生的姓名");
String aName = sc.next();
System.out.println("请输入学生的年龄");
int aAge = sc.nextInt();
Student stu = new Student(aName,aAge);
aList.add(stu);
}