package 学生管理系统;
import java.util.ArrayList;
import java.util.List;
/*
* 进行泛型化编程
* @autor:pcb
* */
public class TestGeneric {
//进行泛型化编程,规定类型。
public List <CourseClass> courses;
public TestGeneric() {
this.courses = new ArrayList<CourseClass>();
}
public void testAdd() {
CourseClass cr1 = new CourseClass("1","大学语文");
courses.add(cr1);
//泛型集合中不能添加规定意外的对象
//courses.add("能否添加一些奇怪的东西");
CourseClass cr2 = new CourseClass("2","Java基础");
courses.add(cr2);
}
public void testForEach() {
//进行泛型之后,可直接利用它规定的类型及其子类型直接进行访问
for(CourseClass cr:courses) {
System.out.println(cr.id+":"+cr.name);
}
}
//泛型集合可以添加泛型的子类型的对象实例
public void testChild() {
ChildCourse ccr = new ChildCourse();
ccr.id = "3";
ccr.name = "我是子类的课程实例对象";
courses.add(ccr);
}
//泛型必须使用包装类型进行创建,例如:int和integer
public void testBaic() {
List<Integer> list = new ArrayList<Integer>();
list.add(1);
System.out.println("基本类型必须使用包装类作为泛型!"+list.get(0));
}
public static void main(String[] args) {
TestGeneric tg = new TestGeneric();
tg.testAdd();
tg.testForEach();
tg.testChild();
tg.testForEach();
tg.testBaic();
//tg.testForEach();
}
}
2.我们开始进行管理系统的创建,创建一个学生类和一个课程类
package 学生管理系统;
import java.util.HashSet;
import java.util.Set;
public class StudentsClass implements Comparable <StudentsClass> {
public String id;
public String name;
public Set<CourseClass> courses;
public StudentsClass(String id,String name){
this.id=id;
this.name=name;
this.courses=new HashSet<CourseClass>();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof StudentsClass))
return false;
StudentsClass other = (StudentsClass) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
public int compareTo(StudentsClass o) {
return this.id.compareTo(o.id);
}
}
package 学生管理系统;
public class CourseClass {
public String id;
public String name;
public CourseClass(String id,String name){
this.id=id;
this.name=name;
}
public CourseClass() {
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof CourseClass))
return false;
CourseClass other = (CourseClass) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
3,利用List进行增加课程,删除课程,修改课程等的操作
package 学生管理系统;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ListTest {
//创建
public List coursesToSelect;
//构造器
public ListTest(){
this.coursesToSelect = new ArrayList();
}
public void testAdd(){
//加课
CourseClass cr1 = ne