1. 程式人生 > >Java中一對多映射關系

Java中一對多映射關系

system 組類型 關系 clas per i++ 技術 分享 定義

通過栗子,一個人可以有多輛汽車

定義人 這個類

人可以有很多輛汽車,類中車屬性用數組

class Person{ 
    private String name;
    private String phone;
    private Car[] car; 
    public Person() {}
    public Person(String name, String phone) {
        this.name = name;
        this.phone = phone;
    }
    public String getName() {
        
return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Car[] getCar() { return car; } public void setCar(Car[] car) {
this.car = car; } public String getInfo(){ return "姓名"+name+",電話"+phone; } }

然後定義汽車 這個類

class Car{ 
    private String name;
    private double price;
    private Person person;
    public Car() {}
    public Car(String name,double price) {
        this.name = name;
        this
.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getInfo() { return "品牌:"+name+" 價格:"+price; }

之後,在測試類中,分別實例Person類和Car類

人這個對象只new一個

汽車可以無限個,這裏象征性實例三個

        Person p = new Person("阿三","33333333");
        Car c1 = new Car("寶馬",400000);
        Car c2 = new Car("寶來",100000);
        Car c3 = new Car("寶駿",800

對象實例化之後,設置彼此的關系,即一個人對應三臺車,每臺車都對應一個人

通過set方法傳值

        p.setCar(new Car[]{c1,c2,c3}); 
        c1.setPerson(p);
        c2.setPerson(p);
        c3.setPerson(p);

測試

通過人,查詢其下的車輛信息

System.out.println(p.getInfo()+"擁有的車輛");
for(int i=0;i<p.getCar().length;i++) {
    System.out.println(p.getCar()[i].getInfo()); //數組類型用for循環打印
}

運行

技術分享圖片

通過車,查找所屬人信息

System.out.println(c1.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());
System.out.println(c2.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());
System.out.println(c3.getInfo()+" 這輛車的所屬人:"+c1.getPerson().getInfo());

運行

技術分享圖片

Java中一對多映射關系