public class Course { int id; String name; public Course(int id,String name){ this.id=id; this.name=name; } }
import java.util.HashSet;
import java.util.Set;
public class SetTest {
public Set settest;
public void SetTest(){
settest=new HashSet();
}
/**
* 添加课程信息
*/
public void testAdd(){
Course cu1=new Course(0,"离散数学");
settest.add(cu1);
Course cu2=new Course(1,"数据结构");
settest.add(cu2);
Course cu3=new Course(2,"近代史");
settest.add(cu3);
Course cu4=new Course(3,"数据库");
settest.add(cu4);
Course cu5=new Course(5,"大学英语");
settest.add(cu5);
}
/**
* 用for each方法循环遍历输出课程信息
*/
public void testForEach(){
System.out.println("有如下待选课程:");
//判断是否为空
while(settest.isEmpty()){
for(Object ob:settest){
Course cu=(Course) ob;
System.out.println(cu.id+":"+cu.name);
}
}
}
public static void main(String[] args) {
SetTest set=new SetTest();
set.testAdd();
set.testForEach();
}
}
运行结果如下:
Exception in thread "main" java.lang.NullPointerException
at collection.SetTest.testAdd(SetTest.java:16)
at collection.SetTest.main(SetTest.java:45)
Its_forever
相关分类