关闭

黑马程序员_java集合在类之间存在包含体现

144人阅读 评论(0) 收藏 举报
------- android培训java培训、期待与您交流! ----------


一个学校会有很多个班级,每个班级又会对应很多学生,可通过上级类中包含下级类的集合来实现.


/*       ------学 -------校--------
 *      |  班级号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;
}

}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2450次
    • 积分:131
    • 等级:
    • 排名:千里之外
    • 原创:11篇
    • 转载:0篇
    • 译文:0篇
    • 评论:3条
    文章存档
    最新评论