如果要是不給Student類設(shè)置Course泛型設(shè)置的話,該怎么寫呢?
最后的for each 循環(huán)要怎么寫:
public static void main(String[] args) {
SetTest st = new SetTest();
st.testAdd();
st.testForEach();
//創(chuàng)建一個(gè)學(xué)生對(duì)象
Student student = new Student("1","小明");
System.out.println("歡迎小明同學(xué)來選課" + "\n" +"請(qǐng)輸入要修的課程:");
//創(chuàng)建Scanner對(duì)象
Scanner console = new Scanner(System.in);
for(int i=1;i<4;i++){
System.out.println("請(qǐng)輸入要選的第"+i+"門課程的編碼");
String courseId = console.next();
for(Course cr:st.couresToSelect){
if(cr.id.equals(courseId)){
student.courses.add(cr);
}
}
}
//打印出學(xué)生所選的課程
for(Course cr:student.courses){
System.out.println(cr.id+":"+cr.name);
}
}
加粗的應(yīng)該寫什么代碼?
2017-08-30
不加Course泛型的話foreach循環(huán)應(yīng)該還是一樣的寫法,foreach(對(duì)象類型 對(duì)象名:需要遍歷的對(duì)象){...}
不過當(dāng)遍歷的對(duì)象中存在其他類型的數(shù)據(jù)的時(shí)候可能會(huì)出現(xiàn)類型轉(zhuǎn)換錯(cuò)誤,泛型的作用是規(guī)范類型
2017-08-30
for(Object cr:student.courses){
Course cd = (Course)cr;
System.out.println(cd.id+":"+cd.name);
}