ArrayList練習 將學生物件新增到集合中,並遍歷輸出
阿新 • • 發佈:2018-12-25
package CollectionDemo001;
/*
* 用集合儲存5個學生物件,並把學生物件進行遍歷
* 分析:
* A: 建立學生類
* B: 建立集合物件
* C: 建立學生物件
* D: 把學生新增到集合裡
* E: 把集合轉換成陣列
* F: 遍歷陣列
*/
import java.util.ArrayList;
import java.util.Collection;
public class ArrayListDemo003 {
public static void main(String[] args) {
//建立集合物件
Collection c = new ArrayList();
//建立學生物件
Student st1 = new Student("林青霞", 27);
Student st2 = new Student("風清揚", 30);
Student st3 = new Student("阿黃", 30);
Student st4 = new Student("劉毅", 31);
Student st5 = new Student("獨孤求敗", 100);
//將學生物件,新增到集合裡
c.add(st1);
c.add(st2); //向上轉型
c.add(st3);
c.add(st4);
c.add(st5);
//System.out.println(c);
//把集合轉換成陣列
Object[] obj = c.toArray();
//開始遍歷
for(int i=0;i<obj.length;i++){
Student s = (Student)obj[i]; //向下轉型
System.out.println(s.getName()+"--->"+s.getAge());
}
System.out.println("===============================");
for(int i=0;i<obj.length;i++){
Student s = (Student)obj[i]; //轉型時,要注意,
System.out.println(s);
}
}
/*
* 用集合儲存5個學生物件,並把學生物件進行遍歷
* 分析:
* A: 建立學生類
* B: 建立集合物件
* C: 建立學生物件
* D: 把學生新增到集合裡
* E: 把集合轉換成陣列
* F: 遍歷陣列
*/
import java.util.ArrayList;
import java.util.Collection;
public class ArrayListDemo003 {
public static void main(String[] args) {
//建立集合物件
Collection c = new ArrayList();
//建立學生物件
Student st1 = new Student("林青霞", 27);
Student st2 = new Student("風清揚", 30);
Student st3 = new Student("阿黃", 30);
Student st4 = new Student("劉毅", 31);
Student st5 = new Student("獨孤求敗", 100);
//將學生物件,新增到集合裡
c.add(st1);
c.add(st2); //向上轉型
c.add(st3);
c.add(st4);
c.add(st5);
//System.out.println(c);
//把集合轉換成陣列
Object[] obj = c.toArray();
//開始遍歷
for(int i=0;i<obj.length;i++){
Student s = (Student)obj[i]; //向下轉型
System.out.println(s.getName()+"--->"+s.getAge());
}
System.out.println("===============================");
for(int i=0;i<obj.length;i++){
Student s = (Student)obj[i]; //轉型時,要注意,
System.out.println(s);
}
}
}
=================================================================================
下面是學生類
package CollectionDemo001;
public class Student {
//成員變數
private String name;
private int age;
//構造方法
public Student(String name, int age) {
super();
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;
}
@Override
public String toString() {
return "name=" + name + "------> age=" + age;
}
}