-3

I have an ArrayList having 30 elements includes null also at some positions, and I am sequentially accessing the ArrayList. Now I want to check whether index contains null element or not. How to avoid IndexOutOfBoundsException so that I can perform some business logic if null element found, list.size() > index won't help in this case.

PS : I don't want to remove null and want to keep position intact. Yes I can perform business logic in catch(IndexOutOfBoundsException){} block also but is there any other way other than try/catch block because I think it is not performant.

ved
  • 909
  • 2
  • 17
  • 43
  • 4
    You don't get IndexOutOfBoundsException for accessing indices of the List that contain null. You get it for accessing indices out of bounds (i.e. < 0 or >= list.size()) – Eran Apr 02 '16 at 13:56
  • you don't you use in the iteration loop `list.get(i) == null` to find `null`s in your arraylist? – Blip Apr 02 '16 at 13:57
  • Possible duplicate of [How to avoid ArrayIndexOutOfBoundsException or IndexOutOfBoundsException?](https://stackoverflow.com/questions/32568261/how-to-avoid-arrayindexoutofboundsexception-or-indexoutofboundsexception) –  Feb 15 '19 at 15:10

1 Answers1

0

The java indexoutofboundsexception

public class IndexOutOfBoundsException extends RuntimeException

Thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.


so as you can read, nothing to do with null elements/references there..

the point is, you are trying to read or write an element in the list that is not event reachabel because of the size of the list self.

you need to check if the index you are trying to manipulate is between 0 and list.size()

all other safety mechanisms are just overrated and unnecessary.

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97