Shahir Deo wrote:
can anybody explain why cant i execute this
What happens when you try? Is there an error message? Copy/paste the exact, complete error message, and indicate clearly which line is causing it.
and suppose i want to add element at index 1 , how it is done.
Well, the docs for add() say:
Inserts the specified element at the specified position in this list (optional operation). Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).
index - index at which the specified element is to be inserted
element - element to be inserted
UnsupportedOperationException - if the add operation is not supported by this list
ClassCastException - if the class of the specified element prevents it from being added to this list
NullPointerException - if the specified element is null and this list does not permit null elements
IllegalArgumentException - if some property of the specified element prevents it from being added to this list
IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size())
If you add at index 3, that implies there are 3 elements “before” wherever you are adding. If you have a 2‑element list, you cannot add at position 3 because there cannot be 3 elements “before” wherever you are adding.