Java练习之学生选课

使用集合来创建一个简单的学生选课系统。

先创建学生类和课程类,将课程信息定义成HashSet集合。

public class Course {

	public String id;
	
	public String name;

	public Course(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}
}
public class Student {

	public String name;
	
	public String id;
	
	public Set courses;

	public Student(String name, String id) {
		super();
		this.name = name;
		this.id = id;
		this.courses = new HashSet();
		
	}
}

创建ListTest类,实现课程的添加和删除。

public class ListTest {

	public List coursesToSelect; //存放备选课程的List

	public ListTest() {
		
		this.coursesToSelect = new ArrayList();
	}
	
//添加课程
	public void testAdd()
	{
		
		coursesToSelect.add(new Course("1","数据结构"));//创建一个课程对象,并添加到课程list中
	
		coursesToSelect.add(new Course("2","计算机网络"));//创建一个课程对象,并添加到课程list中
		
		Course[] course = { new Course("3","组成原理"),new Course("4","操作系统")};
		
		coursesToSelect.addAll(Arrays.asList(course));
		
	//	coursesToSelect.set(3, new Course("4","高等数学"));

		coursesToSelect.removeAll(Arrays.asList(course));
		
	}
	public void testIterator()
	{
        Iterator it = coursesToSelect.iterator();
		
        System.out.println("通过迭代器访问集合元素:");
		while(it.hasNext())
		{
			Course cou = (Course)it.next();
			System.out.println(cou.id+","+cou.name);
		}
		
	}
	public void testForEach()
	{
		System.out.println("通过ForEach方法访问集合元素:");
		for(Object obj : coursesToSelect)
		{
			Course cor = (Course)obj;
			
			System.out.println(cor.id+","+cor.name);
			
		}
	}

	
	 public static void main(String[] args)
	 {
		 ListTest lt = new ListTest();
		 
		 lt.testAdd();
		// lt.testForEach();
		 lt.testIterator();
	 }
}

泛型测试:只能传递Course类型的数据:

public class TestGeneric {
	
	public List<Course> courses;

	public TestGeneric() {
		super();
		this.courses = new ArrayList<Course>();
	}
	
	public void testAdd()
	{
		courses.add(new Course("1","高等数学"));
		
		courses.add(new Course("2","概率论与数理统计"));
	}
	
	public void testForEach()
	{
		for(Course cor:courses)
		{
			System.out.println(cor.id+","+cor.name);
		}
	}

	public static void main(String[] args)
	{
		TestGeneric tg = new TestGeneric();
		
		tg.testAdd();
		
		tg.testForEach();
		
	}
}

泛型中可添加Course的子类ChildCourse中的数据

public class ChildCourse extends Course {
	
	public ChildCourse(String id , String name)
	{
		this.id = id;
		
		this.name = name;
	}

}

//在ListTestf的testAdd方法中,可添加ChildCourse类型的数据

courses.add(new ChildCourse("3","线性代数"));

猜你喜欢

转载自blog.csdn.net/weixin_42139212/article/details/84490034