If I have a LinkedList called List that has size equal to 0, can I add an element in position 4 of it, for example?
If I have a LinkedList called List that has size equal to 0, can I add an element in position 4 of it, for example?
No.
The method add
has the signature
public void add(int index, E element)
where index
is the index where the element will be inserted and element
is the element to insert.
This method throws the exception IndexOutOfBoundsException
if the index is outside the range (index < 0 || index > size())
.
In your case, 4 > 0
, resulting in an exception.