简体   繁体   中英

java.lang.IndexOutOfBoundsException: Invalid index 5, size is 5

This error occurs sometimes and sometimes it works properly. I really can't understand what the problem is.

int length = CitiesInfos.citiesOnTheRoad.length;
for (int i = 0; i < length; i++)
{
    HashMap<String,String> temp=new HashMap<String, String>();
    temp.put(FIRST_COLUMN, CitiesInfos.citiesOnTheRoad[i]);

    if (CitiesInfos.roadWorkArrayList.get(i)!=null)
    {
        temp.put(SECOND_COLUMN, CitiesInfos.weatherArrayList.get(i).getCelcius() + ", " +
                 CitiesInfos.weatherArrayList.get(i).getWeatherStatus());
    }
    else
    {
        temp.put(SECOND_COLUMN, " ");
    }
}

This is the line to which logCat directs. What can the problem be?

increment variable i loops from 0 to citiesOnTheRoad.length - 1 , however, you also use i as an index to two other ArrayList variables: weatherArrayList and roadWorkArrayList , how are you certain they are the correct size?

I added a check that will prevent the crash you are receiving, but I caution you to take a closer look at your code instead of putting this band-aid on it.

    int length = CitiesInfos.citiesOnTheRoad.length;
    for (int i = 0; i < length; i++)
    {
        HashMap<String,String> temp=new HashMap<String, String>();
        temp.put(FIRST_COLUMN, CitiesInfos.citiesOnTheRoad[i]);
        if(i < CitiesInfos.roadWorkArrayList.size() 
            && i < CitiesInfos.weatherArrayList.size() 
            && CitiesInfos.roadWorkArrayList.get(i)!=null)
        {
            temp.put(SECOND_COLUMN, CitiesInfos.weatherArrayList.get(i).getCelcius() + ", " + CitiesInfos.weatherArrayList.get(i).getWeatherStatus());
        }
        else
        {
            temp.put(SECOND_COLUMN, " ");
        }
}

As James Wierzba has mentioned, you are using the same control variable for the array lists in the loop and that is your problem.

You need to ensure that there are enough items before you try to retrieve an element.

A few suggestions:

it seems you are storing related data in two arrays, you are better of grouping this data together inside a class eg City.

You could then have the cities on the road array contain a number of city objects each storing information about the weather in that city.

I would also suggest that you do not have your arrays as public variables, you should have them as private or protected and use getters/setters to access them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM