try { s. get(i); } catch (IndexOutOfBoundsException e) { s. add(i, new Object());//Add something to fill this position. } If the Arraylist in the i position is null (empty), the code catch the exception and you can add something to fill that position.
To check if ArrayList contains a specific object or element, use ArrayList. contains() method. You can call contains() method on the ArrayList, with the element passed as argument to the method. contains() method returns true if the object is present in the list, else the method returns false.
The get() method of ArrayList in Java is used to get the element of a specified index within the list. Parameter: Index of the elements to be returned.
An element in an ArrayList can be searched using the method java. util. ArrayList. indexOf().
The method arrayList.size()
returns the number of items in the list - so if the index is greater than or equal to the size()
, it doesn't exist.
if(index >= myList.size()){
//index not exists
}else{
// index exists
}
While you got a dozen suggestions about using the size of your list, which work for lists with linear entries, no one seemed to read your question.
If you add entries manually at different indexes none of these suggestions will work, as you need to check for a specific index.
Using if ( list.get(index) == null ) will not work either, as get() throws an exception instead of returning null.
Try this:
try {
list.get( index );
} catch ( IndexOutOfBoundsException e ) {
list.add( index, new Object() );
}
Here a new entry is added if the index does not exist. You can alter it to do something different.
This is what you need ...
public boolean indexExists(final List list, final int index) {
return index >= 0 && index < list.size();
}
Why not use an plain old array? Indexed access to a List is a code smell I think.
Usually I just check if the index is less than the array size
if (index < list.size()) {
...
}
If you are also concerned of index being a negative value, use following
if (index >= 0 && index < list.size()) {
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With