清澄白河
2017-05-19 15:00
按照老师说的输入的提示:
这个提示是数组下标越界的意思吧,但是我是按照视频里代码输入的,包括导入包都没有错误,不知道为什么出现这个提示。
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
不知道为什么?
Course cr1 = new Course("1","数据结构");
Course temp = (Course) coursesToSelect.get(0);
coursesToSelect.add(cr1);
顺序错了,代码执行是按照写的顺序来的,你还没加进去就要取出来,肯定不对,把 coursesToSelect.add(cr1); 跟
Course temp = (Course) coursesToSelect.get(0);调换一下顺序就可以了。
写的代码如下:
package com.imooc.collection;
/**
* 课程类
* @author Administrator
*
*/
public class Course {
public String id;
public String name;
public Course(String id,String name){
this.id = id;
this.name = name;
}
}
=================================================
package com.imooc.collection;
import java.util.HashSet;
import java.util.Set;
/**
* 学生类
* @author Administrator
*
*/
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();
}
}
======================================
package com.imooc.collection;
import java.util.List;
import java.util.ArrayList;
/**
* 备选课程类
* @author Administrator
*
*/
public class ListTest {
/**
* 用于存放备选课程的list
*/
public List coursesToSelect;
public ListTest(){
this.coursesToSelect = new ArrayList();
}
/**
* 用于往coursesToSelect中添加备选课程
*/
public void testAdd(){
//创建一个课程对象,并且通过调用add方法,添加到备选课程list中
Course cr1 = new Course("1","数据结构");
Course temp = (Course) coursesToSelect.get(0);
coursesToSelect.add(cr1);
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();
}
}
Java入门第三季
409792 学习 · 4340 问题
相似问题