多对多 java类集应用

import java.util.*;

class Student
{
  private String name;
  private List allsubject;
 
  public Student()
  {
   allsubject=new ArrayList();
  }
  public Student(String name)
  {
   this();
   this.name=name;  
  }
 
  public String getName()
  {
 return name;
  }
  public void setName(String name)
  {
 this.name = name;
  }
  public List getAllsubject()
  {
 return allsubject; 
  }

  public void setAllsubject(List allsubject)
 {
 this.allsubject = allsubject;
 }
  public String toString()
  {
   return "姓名:"+this.getName();
  }

}

class Subject
{
  private String subjectName;
  private List allStudent;
 
  public Subject()
  {
   this.allStudent=new ArrayList();
  }
  public Subject(String subjectName)
  {
   this();
   this.subjectName=subjectName;
  }
  public String getSubjectName()
  {
 return subjectName;
  }

  public void setSubjectName(String subjectName)
  {
 this.subjectName = subjectName;
  }

  public List getAllStudent()
  {
 return allStudent;
  }

  public void setAllStudent(List allStudent)
  {
 this.allStudent = allStudent;
  }

  public String toString()
  {
 return "课程:"+this.getSubjectName();
  }
}

public class Demo4 {
 public static void main(String args[])
 {
  Student s1=new Student("李建平");
  Student s2=new Student("马云");
  Student s3=new Student("李彦宏");
  
  Subject sub1=new Subject("java");
  Subject sub2=new Subject("C++");
  Subject sub3=new Subject("c");
  Subject sub4=new Subject("vb");
  Subject sub5=new Subject("javascript");
  Subject sub6=new Subject(".net");
  
  s1.getAllsubject().add(sub1);
  s1.getAllsubject().add(sub2);
  s1.getAllsubject().add(sub3);
  s1.getAllsubject().add(sub4);
  
  sub1.getAllStudent().add(s1);
  sub1.getAllStudent().add(s2);
  sub1.getAllStudent().add(s3);
   
  System.out.println("选了"+sub1.getSubjectName()+"的同学:");
  printName(sub1);
  
  System.out.println("-------------------------------------");
  System.out.println(s1.getName()+"所选的课程");
  printSubject(s1);
 }
 public static void printName(Subject subject)
 {
  Iterator it=subject.getAllStudent().iterator();
  
  //System.out.println(subject);
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
 }
 public static void printSubject(Student stu)
 {
  Iterator it=stu.getAllsubject().iterator();
  
  //System.out.println(stu);
  while(it.hasNext())
  {
   System.out.println(it.next());
  }
 }
 

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值