代码:
//"张三" "李四" "张三丰" "张无忌" "张帅玮" "赵六" "钱七"
//请遍历集合,请将张开头,且名字为3个字的遍历出来。
ArrayList<String> list = new ArrayList<>();//创建了一个空的集合,里面没有任何元素
list.add("张三");
list.add("李四");
list.add("张三丰");
list.add("张无忌");
list.add("张帅玮");
list.add("赵六");
list.add("钱七");
//当代码执行到这里时,所有的数据都已经存储到集合中了。
for (int i = 0; i < list.size(); i++) {
String name = list.get(i);//name依次表示集合中的每一个名字
if(name.startsWith("张") && name.length() == 3){
System.out.println(name);
}
}
11.存储自定义学生对象并进行遍历
ArrayList<Student> list = new ArrayList<>();
Student s1 = new Student("张三",23);
Student s2 = new Student("李四",24);
Student s3 = new Student("王五",25);
list.add(s1);
list.add(s2);
list.add(s3);
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
student.show();
}
扩展练习:
只要打印年龄大于等于24岁的。
ArrayList<Student> list = new ArrayList<>();
Student s1 = new Student("张三",23);
Student s2 = new Student("李四",24);
Student s3 = new Student("王五",25);
list.add(s1);
list.add(s2);
list.add(s3);
for (int i = 0; i < list.size(); i++) {
Student student = list.get(i);
//遍历到的当前学生的年龄
int age = student.getAge();
if(age >= 24){
student.show();
}
}