ArrayList remove method -


i have @ arraylist source code,found remove method follows:

  /**  * removes element @ specified position in list.  * shifts subsequent elements left (subtracts 1  * indices).  *  * @param index index of element removed  * @return element removed list  * @throws indexoutofboundsexception {@inheritdoc}  */ public e remove(int index) {     if (index >= size)         throw new indexoutofboundsexception(outofboundsmsg(index));      modcount++;     e oldvalue = (e) elementdata[index];      int nummoved = size - index - 1;     if (nummoved > 0)         system.arraycopy(elementdata, index+1, elementdata, index,                          nummoved);     elementdata[--size] = null; // clear let gc work      return oldvalue; } 

why doesn't consider situation when index<0?

passing in negative index fail on following line:

e oldvalue = (e) elementdata[index]; 

specifically, access elementdata underlying array happen negative index. cause arrayindexoutofboundsexception thrown, documentation describes:

thrown indicate array has been accessed illegal index. index either negative or greater or equal size of array.

hence, arraylist#remove() implementation not need language handle case of negative indices.

however, might wondering why code does make following check if index larger size:

 if (index >= size)     throw new indexoutofboundsexception(outofboundsmsg(index)); 

the reason check made because possible index passed in within bounds of elementdata larger logical size of actual list/array. in other words, size of underlying array not (and not) need in lock step actual number of entries in list. rather, jvm grow or shrink elementdata array needed depending size , usage of list.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -