共计 2103 个字符,预计需要花费 6 分钟才能阅读完成。
java 中的集合框架
目录结构
创建学生类和课程类
课程类
/imooc_collection_map_demo/src/com/imooc/collection/Course.java
package com.imooc.collection;
// 课程类
public class Course {
public String id;
public String name;
public Course(String id, String name) {
this.id = id;
this.name = name;
}
}
学生类
/imooc_collection_map_demo/src/com/imooc/collection/Student.java
package com.imooc.collection;
// 学生类
import java.util.HashSet;
import java.util.Set;
public class Student {
public String id;
public String name;
public Set courses;
public Student(String id ,String name) {
this.id = id;
this.name = name;
this.courses = new HashSet();
}
}
添加课程
添加的方法
/imooc_collection_map_demo/src/com/imooc/collection/ListTest.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
// 用于存放备选课程的 List
public List coursesToSelect;
public ListTest() {
this.coursesToSelect = new ArrayList();
}
// 用于往 coursesToSelect 中添加备选课程
public void testAdd() {
// 创建一个课程对象,并通过调用 add 方法,添加到备选课程 list 中
Course cr1 = new Course(“1”, “ 数据结构 ”);
coursesToSelect.add(cr1);
Course temp = (Course) coursesToSelect.get(0);
System.out.println(“ 添加了课程:” + temp.id + “:” + temp.name);
Course cr2 = new Course(“2”, “c 语言 ”);
coursesToSelect.add(0, cr2);
Course temp2 = (Course) coursesToSelect.get(0);
System.out.println(“ 添加了课程:” + temp2.id + “:” + temp2.name);
}
public static void main(String[] args) {
ListTest lt = new ListTest();
lt.testAdd();
}
}
数组下标越界异常
/imooc_collection_map_demo/src/com/imooc/collection/ListTest.java
package com.imooc.collection;
import java.util.ArrayList;
import java.util.List;
public class ListTest {
// 用于存放备选课程的 List
public List coursesToSelect;
public ListTest() {
this.coursesToSelect = new ArrayList();
}
// 用于往 coursesToSelect 中添加备选课程
public void testAdd() {
// 创建一个课程对象,并通过调用 add 方法,添加到备选课程 list 中
Course cr1 = new Course(“1”, “ 数据结构 ”);
coursesToSelect.add(cr1);
Course temp = (Course) coursesToSelect.get(0);
System.out.println(“ 添加了课程:” + temp.id + “:” + temp.name);
Course cr2 = new Course(“2”, “c 语言 ”);
coursesToSelect.add(0, cr2);
Course temp2 = (Course) coursesToSelect.get(0);
System.out.println(“ 添加了课程:” + temp2.id + “:” + temp2.name);
Course cr3 = new Course(“3”, “test”);
coursesToSelect.add(-1,cr3);
Course cr3 = new Course(“3”, “test”);
coursesToSelect.add(4,cr3);
}
public static void main(String[] args) {
ListTest lt = new ListTest();
lt.testAdd();
}
}