一個學校會有很多個班級,每個班級又會對應很多學生,可通過上級類中包含下級類的集合來實現.
/* ------學 -------校--------
* |
班級號A——————————班級體A
* | 學號——姓名
* | 學號——姓名
* | 學號——姓名
* | ...
* |
* | 班級號B——————————班級體B
* | ......
*/
import java.util.Collection;
import java.util.Iterator;import java.util.Set;
import java.util.TreeSet;
class Student implements Comparable<Student>{
private String id ;
private String name ;
public Student(String id, String name) {
super();
this.id = id;
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
if (getClass() != obj.getClass())
throw new ClassCastException(obj + "不能被轉成Student類對象");
Student other = (Student) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
throw new RuntimeException(name+"的id:"+id+"已被"+other.name+"所使用");
return true;
}
@Override
public String toString() {
return "Student [id=" + id + ", name=" + name + "]";
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int compareTo(Student o) {
int num = id.compareTo(o.id);
if(num == 0){
if( !(this.toString().equals(o.toString())))
throw new RuntimeException(name+"的id:"+id+"已被"+o.name+"所使用");
return 0 ;
}
return num ;
}
}
class Banji implements Comparable<Banji>{
private String name;
private Collection<Student> studentColl ; //Banji 裏定義學生集合
public Banji(String ronmName, Collection<Student> studentColl) {
super();
this.name = ronmName;
this.studentColl = studentColl;
}
Banji(String name){
this.name = name ;
this.studentColl = new TreeSet<Student>();
}
Banji(String name ,TreeSet<Student> studentColl){
this.name = name ;
this.studentColl = studentColl;
}
//提供相應的方法來管理學生集合
public boolean addStudent(Student stu){
return studentColl.add(stu);
}
public Student removeStudentByid(String id){
for(Iterator<Student> it = studentColl.iterator() ; it.hasNext() ;){
Student s = it.next();
if( s.getId().equals(id)){
it.remove();
return s;
}
}
return null;
}
@Override
public int compareTo(Banji o) {
// TODO Auto-generated method stub
return 0;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}