Collection 和Map
Collection:List(序列)实现类ArrayList, Queue(队列)实现类LinkdeList(链表) 有序可重复 Set(集)(HashSet)无序不可重复
Map:实现类HashMap 映射<key,value>Entry键值对
//课程类
public class Course {
public String name;
public String id;
public Course(String id,String name){
this.id=id;
this.name=name;
}
}
//学生类
import java.util.HashSet;
import java.util.Set;
public class Student {
public String name;
public String id;
public Set course;//不懂
public Student(String name ,String id){
this.id=id;
this.name=name;
this.course=new HashSet();///不懂
}
}
//LIst增加遍历数据
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* 增加课程
* list的遍历 for循环 迭代器 for each
* 都放0 自动往下挤
* 4种增加方法
*/
public class ListTest {
public List courseToList;//待选课程 一个List类型的集合
public ListTest(){
this.courseToList=new ArrayList();
}
public void testAdd(){
Course cr1=new Course("1","数剧结构");//调用构造方法 创建了一个课程对象
courseToList.add(cr1);//用add方法增加一个课程
Course temp=(Course)courseToList.get(0);//创建一个Course类型的对象temp 用来接收从courseToList中取出来的数据 因为取出来没有类型 故强转 用get方法
System.out.println(temp.id+temp.name);//对象调用属性
Course cr2=new Course("2", "c语言");
//两个add方法
courseToList.add(0, cr2);//指定位置
Course temp2=(Course)courseToList.get(0);//不同对象接收不同
System.out.println(temp2.id+temp2.name);
Course[] course={new Course("3","历史"),new Course("4","司法" )};//创建Course的数组并赋值
courseToList.addAll(Arrays.asList(course));//工具类Arrays 括号内是collection的实例
Course temp3=(Course)courseToList.get(2);
System.out.println(temp3.id+temp3.name);
Course[] course2={new Course("4","司法" )};
courseToList.addAll(0, Arrays.asList(course2));//制定位置插入一组
Course temp4=(Course)courseToList.get(0);
System.out.println(temp4.id+temp4.name);
}
//查询待选课程courseToList的课程 用get方法 for遍历
public void get(){
for(int i=0;i<courseToList.size();i++){//size 确定数组的长度
Course cr=(Course) courseToList.get(i);
System.out.println(cr.id+cr.name );
}
}
/**
* 通过迭代器
* iterator 迭代器的 意思 迭代器只作为遍历用 不能存东西
*/
public void testIterator(){
//通过collection的iterator的方法 获得这个集合的迭代器
Iterator it=courseToList.iterator();
System.out.println("00000000000000000000000000000000000000");
while(it.hasNext()){
Course cr=(Course) it.next();
System.out.println(cr.id+cr.name);
}
}
/**
* 通过for each 进行集合的遍历
* 因为数据存入集合中被忽略类型 位object
* 迭代器的简便写法
*/
public void testForEach(){
System.out.println("1111111111111111111111111111111111111111111111");
for(Object obj:courseToList){
Course cor=(Course) obj;
System.out.println(cor.id+cor.name);
}
}
public static void main(String[] args) {
ListTest lt=new ListTest();
lt.testAdd();
lt.get();
lt.testIterator();
lt.testForEach();
}
}