修改Object内的变量值(java)

时间:2014-11-18 04:45:28

标签: java object arraylist

我对java很新,我正在尝试创建学生记录系统。 目前我正在ArrayList Object中存储我的“注册学生”。

我希望能够修改例如for的值。特定学生的名字。学生的身份证也是他在ArrayList中的位置。

以下是我尝试这样做的方法,但似乎没有效果:

StudentStoring.StudentList.get(id)
    .setTitle(comboTitle.getSelectedItem().toString());

这是一段代码,假设在修改页面中获取标题的新值并替换旧的,但我收到IndexOutOfBound错误。

感谢。

2 个答案:

答案 0 :(得分:1)

文档说,

/**
 * Returns the element at the specified position in this list.
 *
 * @param  index index of the element to return
 * @return the element at the specified position in this list
 * @throws IndexOutOfBoundsException {@inheritDoc}
 */
public E get(int index) {
    rangeCheck(index);

    return elementData(index);
}

表示列表中有5个元素(索引0到4)。如果你试图获得第10个元素(索引9),那么它将抛出IndexOutOfBoundsException。所以在你的代码中,

StudentStoring.StudentList.get(id).setTitle(comboTitle.getSelectedItem().toString());

id的值大于数组列表的大小。尝试在IDE中调试或只打印id的值,您可以轻松找到问题。

答案 1 :(得分:1)

获取要更新的列表的索引值的更好方法,然后使用public E set(int index, E element)方法替换值

Student s=new Student();
 s.setId(id); 
 s.setTitle(comboTitle.getSelectedItem().toString());


StudentStoring.StudentList.set(index,comboTitle.getSelectedItem().toString());
相关问题