List,add(),迭代器
package run1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* 被选课程类
* @author Administrator
*
*/
public class ListTest {
/**
* 用于存放备选课程的list(容器)
*/
public List coursesToSelect; //被选课程属性
public ListTest(){ //添加构造方法
this.coursesToSelect = new ArrayList();
}
/**
* 用于添加课程的方法
*/
public void TextAdd(){
/**
* 创建一个课程对象,通过调用add方法添加到备选课程List中
*/
Course cr1 = new Course("1", "Java");
coursesToSelect.add(cr1);
/**
* List的get方法取出元素
* 对象存入集合都变Object类型,取出时需类型转换
*/
Course temp1 = (Course) coursesToSelect.get(0);
System.out.println("添加了课程:" + temp1.id+":" + temp1.name);
Course cr2 = new Course("2", "C++");
coursesToSelect.add(1,cr2);
Course temp2 = (Course) coursesToSelect.get(1);
System.out.println("添加了课程:" + temp2.id+":" + temp2.name);
//可以重复添加
coursesToSelect.add(2,cr1);
Course temp0 = (Course) coursesToSelect.get(2);
System.out.println("添加了课程:" + temp0.id+":" + temp0.name);
/**
*addAll()方法1
*/
Course[] course ={new Course("3","离散数学"),new Course("4","化学")};
coursesToSelect.addAll(Arrays.asList(course));
Course temp3 = (Course) coursesToSelect.get(3);
Course temp4 = (Course) coursesToSelect.get(4); f
System.out.println("添加了两门课程:" + temp3.id+":" + temp3.name
+";"+temp4.id+":" + temp4.name);
/**
*addAll()方法2
*/
Course[] course1 ={new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course1));
Course temp5 = (Course) coursesToSelect.get(2);
Course temp6 = (Course) coursesToSelect.get(3);
System.out.println("添加了两门课程:" + temp5.id+":" + temp5.name
+";"+temp6.id+":" + temp6.name);
}
/**
* 通过for循环遍历元素
*/
public void textGet(){
int size = coursesToSelect.size();
System.out.println("通过textGet方法输出List元素:" );
for(int i = 0; i < size; i++){
Course cr = (Course) coursesToSelect.get(i);
System.out.println("课程:" + cr.id+":" + cr.name);
}
/**
* 通过迭代器遍历元素
*/
}
public void testIterator(){
Iterator it = coursesToSelect.iterator();
System.out.println("通过迭代器遍历元素:" );
while(it.hasNext()){
Course cr = (Course) it.next();
System.out.println("课程:" + cr.id+":" + cr.name);
}
}
/**
* 通过for each遍历元素
* @param args
*/
public void testForEach(){
System.out.println("通过for each遍历元素:" );
for(Object obj : coursesToSelect){ //不能用Course类型
Course cr = (Course) obj;
System.out.println("课程:" + cr.id+":" + cr.name);
}
}
public static void main(String[] args){
ListTest lt = new ListTest();
lt.TextAdd();
lt.textGet();
lt.testIterator();
lt.testForEach();
}
}