〖Java類集〗_範例講解:一對多關聯性筆記

來源:互聯網
上載者:User

〖Java類集〗_範例講解:一對多關聯性筆記

執行個體要求:

使用類集可以表示出以下的關係:一個學校可以包含多個學生,一個學生屬於一個學校,那麼這就是一個典型的一對多的關係,此時就可以通過類集進行關係的表示。

3、本執行個體主要採用的知識

1、類的設計
2、類集

4、具體內容

一個學校有多個學生,那麼學生的個數屬於未知數,那麼這樣一來肯定無法用普通的對象數組表示。所以必須通過類集表示。

代碼:

School.java

import java.util.List;import java.util.ArrayList;public class School{    private String name;    private List<Student> allStudents;    public School(){        this.allStudents = new ArrayList<Student>();    }    public School(String name){        this();        this.setName(name);    }    public void setName(String name){        this.name = name;    }    public String getName(){        return this.name;    }    public List<Student> getAllStudents(){        return this.allStudents;    }    public String toString(){        return "學校名稱:"+this.name;        }}

Student.java

public class Student{    private String name ;    private int age ;    private School school; // 一個學生屬於一個學校    public Student(String name,int age){        this.setName(name) ;        this.setAge(age) ;    }    public void setSchool(School school){        this.school = school ;    }    public School getSchool(){        return this.school ;    }    public void setName(String name){        this.name = name ;    }    public void setAge(int age){        this.age = age ;    }    public String getName(){        return this.name;    }    public int getAge(){        return this.age ;    }    public String toString(){        return "學生姓名:" + this.name + ";年齡:" + this.age ;    }};

TestDemo.java

import java.util.Iterator;public class TestDemo{    public static void main(String[] args){        School sch = new School("清華大學");        Student s1 = new Student("張三",21);        Student s2 = new Student("李四",22);        Student s3 = new Student("王五",23);        sch.getAllStudents().add(s1);        sch.getAllStudents().add(s2);        sch.getAllStudents().add(s3);        s1.setSchool(sch);        s2.setSchool(sch);        s3.setSchool(sch);        System.out.print(sch);        Iterator<Student> iter = sch.gerAllStudents().iterator();        while(iter.hasNext()){            System.out.println("\t|- "+iter.next());        }    }}

5、總結

1、明白類集的關係,那麼這種關係將稱為日後標準程式的開發的基礎。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.