Tuytuy
Tuytuy

Reputation: 169

Modify value of variable inside an Object (java)

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.

Upvotes: 0

Views: 242

Answers (2)

xrcwrn
xrcwrn

Reputation: 5325

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());

Upvotes: 1

Jaya Ananthram
Jaya Ananthram

Reputation: 3463

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.

Upvotes: 1

Related Questions