0

I am getting IndexOutOfBoundsException when loop is running in second time Postman error

Code

public Object example() {
    String userId = getLoggedInUserId();
    User u = userDao.getUserById(userId);
    List<String> categoryIds = u.getCategoryAccess();
    List<Category> categoryList = categoryDao.getUserCategoriesById(categoryIds);
    List<SubCategory> subCategoryList = categoryDao.getUserSubCategoriesById(categoryIds);

    List<String> subCategoriesIds = new ArrayList<>();
    for(int i =0;i<subCategoryList.size();i++)
    {
        subCategoriesIds.add(subCategoryList.get(i).getId());
    }
    List<Items> itemsList = categoryDao.getUserItemsBySubCategoryIds(subCategoriesIds);

    List<Category> FirstLoop = new ArrayList<>();

    for (int j = 0;j<categoryList.size();j++)
    {
        FirstLoop.add(categoryList.get(j));

        List<SubCategory> SecondLoop = new ArrayList<>();

        for(int k=0;k<subCategoryList.size();k++)
        {
            if(categoryList.get(j).getId().equals(subCategoryList.get(k).getCategoryId()))
            {
                SecondLoop.add(subCategoryList.get(k));
                FirstLoop.get(j).setSubCategory(SecondLoop);
            }

            List<Items> ThirdLoop = new ArrayList<>();

            for(int l =0;l<itemsList.size();l++)
            {
                if(subCategoryList.get(k).getId().equals(itemsList.get(l).getSubCategoryId()))
                {
                    ThirdLoop.add(itemsList.get(l));
                    SecondLoop.get(k).setItems(ThirdLoop);
                }
            }
        }
    }
    return FirstLoop;
}

IndexOutOfBoundsException

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
    at java.util.ArrayList.rangeCheck(Unknown Source) ~[na:1.8.0_261]
    at java.util.ArrayList.get(Unknown Source) ~[na:1.8.0_261]
    at com.website.website.service.CartService.example(CartService.java:233) ~[classes!/:0.1.2]
    at com.website.website.controller.CartController.example(CartController.java:102) ~[classes!/:0.1.2]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_261]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_261]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_261]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_261]

Postman error

{
    "timestamp": "2020-12-25T10:55:00.602+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "Index: 1, Size: 1",
    "path": "/api/Cart/example"
}
Bashir
  • 2,057
  • 5
  • 19
  • 44

0 Answers0