java_day11练习题
练习1
一、需求说明:自定义一个学生类,给出成员变量name和age,使用Collection集合存储自定
义对象并遍历,遍历集合的时候,在控制台输出学生对象的成员变量值。
1.2.操作步骤描述
1.创建学生类。
2.创建集合对象。
3.创建元素对象。
4.把元素添加到集合。
5.遍历集合。
package com.scy11;
public class Student {
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;
}
}
package com.scy11;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
Collection<Student> c = new ArrayList<Student>();
Student s1 = new Student("林青霞",20);
Student s2 = new Student("张曼玉",35);
Student s3 = new Student("王祖贤",50);
c.add(s1);
c.add(s2);
c.add(s3);
Iterator<Student> it = c.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
练习2
一、需求说明:自定义一个学生类,给出成员变量name和age,使用List集合存储自定义对象并
遍历,遍历集合的时候,在控制台输出学生对象的成员变量值。要求使用两种方式进行遍历(迭代
器、普通for)。
2.2.操作步骤描述
1.创建学生类。
2.创建集合对象。
3.创建元素对象。
4.把元素添加到集合。
5.遍历集合。
public class ListDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student("林青霞",20);
Student s2 = new Student("张曼玉",10);
Student s3 = new Student("王祖贤",25);
list.add(s1);
list.add(s2);
list.add(s3);
Iterator<Student> it = list.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+"---"+s.getAge());
}
System.out.println("-------------------");
for (int i=0;i<list.size();i++){
Student s = list.get(i);
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
练习3
一、需求说明:自定义一个学生类,给出成员变量name和age,使用List集合存储自定义对象并
使用增强for进行遍历,遍历集合的时候,在控制台输出学生对象的成员变量值。
3.2.操作步骤描述
1.创建学生类。
2.创建集合对象。
3.创建元素对象。
4.把元素添加到集合。
5.遍历集合。
package com.scy11;
import java.util.ArrayList;
import java.util.List;
public class ForTest {
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
Student s1 = new Student("林青霞",30);
Student s2 = new Student("张曼玉",36);
Student s3 = new Student("王祖贤",32);
studentList.add(s1);
studentList.add(s2);
studentList.add(s3);
for (Student s:studentList){
System.out.println(s.getName()+"---"+s.getAge());
}
}
}
练习4
二、需求说明:自定义一个学生类,给出成员变量name和age,使用List集合存储自定义对象并行遍历,遍历集合的时候,在控制台输出学生对象的成员变量值。要求使用三种方式进行遍历(迭代器、普通for、增强for)。
4.2.操作步骤描述
1.创建学生类。
2.创建集合对象。
3.创建元素对象。
4.把元素添加到集合。
5.遍历集合。
package com.scy11;
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListDemo {
public static void main(String[] args) {
List<Student> array = new ArrayList<Student>();
Student s1 = new Student</