package collection_map;import java.util.ArrayList;import java.util.Arrays;import java.util.Iterator;import java.util.List;public class TestNow { public List coursesToSelect; public TestNow(){ this.coursesToSelect=new ArrayList(); } public void testAdd(){ Course cr1=new Course("1","數(shù)據(jù)結(jié)構(gòu)"); coursesToSelect.add(cr1); Course temp=(Course)coursesToSelect.get(0);//0是因為,List與數(shù)組一樣,起始位置也是0 //又因為對象存入集合都會變成object類型,取出時需要類型轉(zhuǎn)換,這里的(Course)就是強制類型轉(zhuǎn)換 System.out.println("添加了課程:"+temp.id+":"+temp.name); Course cr2=new Course("2","JAVA基礎(chǔ)"); coursesToSelect.add(1,cr2); Course temp2=(Course)coursesToSelect.get(0); System.out.println("在后邊添加了課程:"+cr2.id+":"+cr2.name); Course cr3[]={new Course("3","線性代數(shù)"),new Course("4","高中化學")}; coursesToSelect.addAll(2,Arrays.asList(cr3)); Course temp3=(Course)coursesToSelect.get(2); Course temp4=(Course)coursesToSelect.get(3); System.out.println("用數(shù)組添加了兩門課程:"+temp3.id+":"+temp3.name+"以及" +temp4.id+":"+temp4.name ); } public void testGet(){ int size=coursesToSelect.size(); for(int i=0;i<size;i++) { Course tempt=(Course)coursesToSelect.get(i); System.out.println(tempt.id+":"+tempt.name); } } public void testIterator(){ Iterator ir=coursesToSelect.iterator(); System.out.println("通過迭代器訪問:"); while(ir.hasNext()) { Course cs=(Course)ir.next(); System.out.println(cs.id+":"+cs.name); } } public void testForEach(){ System.out.println("有如下課程待選(通過for each訪問)"); for(Object obj:coursesToSelect) { Course cs=(Course) obj; System.out.println("課程:"+cs.id+":"+cs.name); } } public void testModify(){ coursesToSelect.set(0, new Course("1","被換啦哈哈哈"));//就是這里 } public static void main(String[] args) { TestNow tn=new TestNow(); tn.testAdd(); tn.testGet(); tn.testIterator(); tn.testForEach(); tn.testModify(); }在標注的地方那行代碼不知道為什么起作用,1還是數(shù)據(jù)結(jié)構(gòu)}
有個小問題希望得到幫助
慕工程6005648
2016-11-21 20:21:20