黑马程序员技术交流社区
标题:
一对多关系的实现 Java的类集运用
[打印本页]
作者:
小歪
时间:
2014-4-1 10:48
标题:
一对多关系的实现 Java的类集运用
本帖最后由 小歪 于 2014-4-1 10:48 编辑
一对多关系的实现 Java的类集运用
先简单说明下我们要做的操作,利用Java代码实现一对多关系,举例说明学生与学校之间的关系。
一个学校有多个学生,学生的个数属于未知的,
那么这样一来肯定无法用普通的对象数组表示,所以必须通过类集表示。
设计学生信息类:
//学生信息类
package onetomore;
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() //覆写toString方法,简单输出
{
return "学生姓名:"+this.name+",年龄:"+this.age;
}
}
复制代码
学校信息类:
//学校信息类
package onetomore;
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();
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;
}
}
复制代码
数据测试类:
//数据测试类
package onetomore;
import java.util.Iterator;
public class Main {
public static void main(String args[])
{
School sch=new School("兰州石化职业技术学院"); //实例化一个学校
Student st1=new Student("张三",18); //学生1
Student st2=new Student("李四",19); //学生2
Student st3=new Student("王五",20); //学生3
sch.getAllStudents().add(st1); //学生1添加到学校中
sch.getAllStudents().add(st2); //学生2添加到学校中
sch.getAllStudents().add(st3); //学生3添加到学校中
st1.setSchool(sch); //设置学生学校
st2.setSchool(sch);
st3.setSchool(sch);
//以下是通过学校查询学生
System.out.println("以下是通过学校查询学生:");
System.out.println(sch);
Iterator<Student> iter = sch.getAllStudents().iterator() ;
while(iter.hasNext())
{
System.out.println("\t————|"+iter.next());
}
//以下是通过学生查询学校
System.out.println("\n以下是通过学生查询学校:");
System.out.println(st1+"\n\t————|"+st1.getSchool());
}
}
复制代码
运行结果:
2.png
(114.92 KB, 下载次数: 33)
下载附件
2014-4-1 10:48 上传
作者:
许庭洲
时间:
2014-4-1 14:04
值得学习ing!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2