0

I am quite new to java and I'm trying to create student record system. At the moment I'm storing my "registered student" in an ArrayList of Objects.

I would like to be able to modify the value of for e.g. the first name of a specific student. The ID of the student is also his position in the ArrayList.

Here is how I tried to do it but it doesnt seem to work:

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

This is the bit of code that is suppose to take the new value of the title in the modifying page and replace the old one but I get an IndexOutOfBound error.

Thanks.

1
  • 1
    IndexOutOfBound means that your id is beyond the length of the array. Keep in mind that the first index is 0 (not 1). Commented Nov 18, 2014 at 4:47

2 Answers 2

1

The documentation says,

/**
 * 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);
}

which means if the list has 5 elements (index 0 to 4). If your are trying to get 10th element (index 9) then it will throws IndexOutOfBoundsException. So in your code,

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

id will have a value greater than the size of the array list. Try to debug in IDE or just print the value of id you can easily find the issue.

Sign up to request clarification or add additional context in comments.

Comments

1

Better way to get Index value of list which you want to update then use public E set(int index, E element) method to replace value

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


StudentStoring.StudentList.set(index,comboTitle.getSelectedItem().toString());

1 Comment

That is not necessarily better, as it does not update an existing Student, but replaces it with a new one. Anyone else who has a reference to the object won't see the updates.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.