Java類集學習(六)應用範例(一對多的關係)

使用類集可以表示出以下關係:一個學校可以包含多個學生,一個學生屬於一個學校。這是一個典型的一對多的關係。

學生含有的屬性:姓名,年齡,對應的學校;

學校的屬性:學校名稱,對應的學生集合。

分析存儲結構圖:


先定義一個學生類:

public class Student {
	private String name;
	private int age;
	private School school;//一個學生有一個學校屬性
	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;
	}
	public School getSchool() {
		return school;
	}
	public void setSchool(School school) {
		this.school = school;
	}
//	重寫equals方法(list存儲的話不需要重寫)
	public boolean equals(Object obj){
		if(this == obj){
			return true;
		}
		if(!(obj instanceof Student)){
			return false;
		}
		Student stu = (Student) obj;
		if(this.name.equals(stu.name) && this.age==stu.age){
			return true;
		}else{
			return false;
		}
	}
//	重寫HashCode(list存儲的話不需要重寫)
	public int hashCode(){
		return this.name.hashCode()*this.age;
	}
//	重寫toString
	public String toString(){
		return "姓名:"+this.name+",年齡:"+this.age;
	}
}

定義學校類:

public class School {
	private String name;
	private List<Student> allStudent;//一個學校對應多個學生
	public School(){
		this.allStudent = new ArrayList<Student>();//無參構造實例化list集合
	}
	public School(String name){
		this();//調用無參構造
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public List<Student> getAllStudent() {
		return allStudent;
	}
	public void setAllStudent(List<Student> allStudent) {
		this.allStudent = allStudent;
	}
//	重寫toString
	public String toString(){
		return "學校名稱:"+this.name;
	}
}

測試程序:

public class Demo01 {
	public static void main(String[] args) {
//		實例化學校對象
		School sch1 = new School("清華大學");
		School sch2 = new School("北京郵電大學");
//		實例化學生對象
		Student stu1 = new Student("張三",20);
		Student stu2 = new Student("李四",21);
		Student stu3 = new Student("王五",22);
		Student stu4 = new Student("趙六",23);
//		在學校中加入學生
		sch1.getAllStudent().add(stu1);
		sch1.getAllStudent().add(stu2);
		sch2.getAllStudent().add(stu3);
		sch2.getAllStudent().add(stu4);
//		一個學生屬於一個學校
		stu1.setSchool(sch1);
		stu2.setSchool(sch1);
		stu3.setSchool(sch2);
		stu4.setSchool(sch2);
		System.out.println(sch1);
		Iterator<Student> iter = sch1.getAllStudent().iterator();
		while(iter.hasNext()){
			System.out.println(iter.next());
		}
		System.out.println(sch2);
		for(Student students : sch2.getAllStudent()){
			System.out.println(students);
		}
	}
}

輸出結果:

學校名稱:清華大學
姓名:張三,年齡:20
姓名:李四,年齡:21
學校名稱:北京郵電大學
姓名:王五,年齡:22
姓名:趙六,年齡:23
1、分析存儲及其關係結構;2、定義類和各個屬性,通過兩個類中的屬性保存彼此引用關係


發佈了36 篇原創文章 · 獲贊 4 · 訪問量 10萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章