I have the following code:
ArrayList<Integer> arr = new ArrayList<Integer>(10);
arr.set(0,5);
I am getting an index out of bounds error, and I don’t know why. I have declared the ArrayList of size 10. Why do I get this error?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You declared an
ArrayList, that has the initial capacity of 10 elements, but you did not add an element to this list, i.e. the list is empty.setwill replace an existing element, but since there is no element in the list, the exception is thrown.You have to add elements before, using the
addmethod.Initial capacitymeans that the array that the list maintains internally is of size 10 at the beginning. While adding more elements to the list, the size of this internal array might change.