利用集合存储课程信息:
1.Course类
package com.collection; public class Course { public String id; public String name; public Course(String id,String name) { this.id=id; this.name=name; } }
2.ListTest类
package com.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * 备选课程类 */ public class ListTest { //List用于存放备选课程 public List CourseToSelect; public ListTest(){ this.CourseToSelect = new ArrayList(); } //用于往CourseToSelect添加备选课程 public void TestAdd(){ //创建一个课程对象,并通过调用add方法,添加到备选课程List中 Course c1 = new Course("1","数据结构"); CourseToSelect.add(c1); Course temp = (Course) CourseToSelect.get(0); System.out.println("添加了课程:"+temp.id+"_"+temp.name); Course c2 = new Course("2","c语言"); CourseToSelect.add(0, c2); Course temp2 = (Course) CourseToSelect.get(0); System.out.println("添加了课程:"+temp2.id+"_"+temp2.name); Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")}; CourseToSelect.addAll(Arrays.asList(course)); Course temp3 = (Course) CourseToSelect.get(2); Course temp4 = (Course) CourseToSelect.get(3); System.out.println("添加了两门课程:"+temp3.id+"_"+temp3.name+";"+temp4.id+"_"+temp4.name); CourseToSelect.add(c1); Course temp0 = (Course) CourseToSelect.get(0); System.out.println("添加了课程:"+temp0.id+"_"+temp0.name); Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")}; CourseToSelect.addAll(2, Arrays.asList(course2)); Course temp5 = (Course) CourseToSelect.get(2); Course temp6 = (Course) CourseToSelect.get(3); System.out.println("添加了两门课程:"+temp5.id+"_"+temp5.name+";"+temp6.id+"_"+temp6.name); } //取得List中元素的方法 public void testGet(){ int size = CourseToSelect.size(); System.out.println("有如下课程待选:"); for(int i = 0;i<size;i++) { Course cr = (Course) CourseToSelect.get(i); System.out.println("课程:"+cr.id+":"+cr.name); } } //通过迭代器遍历List中的元素 public void testIterator(){ //通过集合的iterator方法,取得迭代器的实例; Iterator it = CourseToSelect.iterator(); System.out.println("有如下课程待选(通过迭代器取得):"); while(it.hasNext()){ Course cr2 = (Course) it.next(); System.out.println("课程:"+cr2.id+":"+cr2.name); } } //通过for each遍历list中的元素 public void testForEach(){ System.out.println("有如下课程待选(通过for each取得):"); for(Object obj:CourseToSelect){ Course cr = (Course) obj; System.out.println("课程:"+cr.id+":"+cr.name); } } //修改List中的元素 public void testModify(){ CourseToSelect.set(6, new Course("7","毛概")); } //删除List中的元素 public void testRemove(){ /*Course cr = (Course) CourseToSelect.get(6); System.out.println("课程:"+cr.id+":"+cr.name+"我即将被删除"); CourseToSelect.remove(cr); //删除具体的元素*/ //CourseToSelect.remove(4); //删除索引4位置上的元素 Course[] courses = {(Course)CourseToSelect.get(4),(Course)CourseToSelect.get(5)}; CourseToSelect.removeAll(Arrays.asList(courses)); System.out.println("成功被删除"); testForEach(); } public static void main(String[] args){ ListTest lt = new ListTest(); lt.TestAdd(); lt.testGet(); lt.testIterator(); lt.testForEach(); lt.testModify(); lt.testForEach(); lt.testRemove(); } }