javaarraysloopsindexoutofboundsexception

java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0 , I don't understand?


I'm getting this error while im sure the array is not null, here is the code :

            REPORT.info("Removing meta_field id {} from metamodel id {}", Integer[]{oldMetaFieldId, metamodelId);

            App.get(MetamodelFieldService.class).remove(metamodelId, new Integer[]{oldMetaFieldId});

I put the report just before the call of the method "remove" to make sure the variable oldMetaFieldId is not null, and it is not I checked the logs :

2023-06-20 15:12:21,776  INFO [main] FusionChampsFiches - Removing meta_field id [1007] from metamodel id 215

Here is the implementation of the "remove" method :

  public void remove(Integer metamodelId, Integer[] metaFieldIdList) {
    for (Integer metaFieldId : metaFieldIdList) {
      MetamodelField ex = new MetamodelField();
      ex.setMetamodelId(metamodelId);
      ex.setMetaFieldId(metaFieldId);
      List<MetamodelField> entityList = getDao().findByExample(ex);

      entityList.get(0);
      remove(entityList.get(0));
    }
    MetaModelCache.getCache().clear(getApplicationSession());
  }

I don't understand why i'm getting this error

java.lang.IndexOutOfBoundsException: Index 0 out of bounds for length 0


Solution

  • In addition to a List being null, it might also be empty (contain nothing). In this case that is exactly the problem. There is nothing in the List, so you can't get the first element (there isn't one). One solution, check for empty. Like,

    List<MetamodelField> entityList = getDao().findByExample(ex);
    if (!entityList.isEmpty()) {
        entityList.get(0);
        remove(entityList.get(0));
    }
    

    Or use an Iterator. Like,

    List<MetamodelField> entityList = getDao().findByExample(ex);
    Iterator<MetamodelField> iter = entityList.iterator();
    if (iter.hasNext()) {
        MetamodelField mf = iter.next();
        iter.remove();
    }