import java.util.ArrayList;
import java.util.Collection;
public class CollectionDemo02 {
public static void main(String[] args) {
//首先创建集合对象
Collection<String> c = new ArrayList<>();
System.out.println(c.add("hello"));
//输出集合对象
System.out.println(c);
}
}
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;
}
}
在测试类里面
import java.util.Collection;
import java.util.ArrayList;
import java.util.Iterator;
public class CollectionDemo {
public static void main(String[] args) {
//创建Collection集合对象
Collection<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("林青霞",30);
Student s2 = new Student("张曼玉",35);
Student s3 = new Student("王祖贤",33);
//把学生添加到集合
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());
}
}
}
for (int i = 0;i<list.size();i++){
String s = list.get(i);
System.out.println(s);
}
_List集合存储学生对象并遍历
需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合。
思路:
定义学生类
创建List集合对象
创建学生对象
把学生添加到集合
遍历集合(迭代器方式,for循环方式)
定义学生类
public class Student {
private String name;
private int age;
public Student(){};
public Student(String name,int age){
this.name=name;
this.age=age;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
}
创建List集合对象。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
//创建List集合对象
List<Student> list = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("林青霞",36);
Student s2 = new Student("张曼玉",35);
Student s3 = new Student("王祖贤",40);
//把学生添加到集合
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循环方式
for ( int i = 0;i<list.size();i++){
Student s = list.get(i);
System.out.println(s.getName()+","+s.getAge());
}
}
}