user3666471
user3666471

Reputation: 945

Access list of lists in a random way

I'm trying to create a list of lists and populate them as required, but I'm getting array out of bounds exception. My code is:

List<List<String>> seperatedData = new ArrayList<List<String>>();
int index;

while ((line = br.readLine()) != null) {
    String[] data = line.split(",");
    index = data[0].hashCode() % redCount;

    if(seperatedData.get(index) == null) {
            List<String> single = new ArrayList<String>();
            seperatedData.add(single);
            seperatedData.get(index).add(line);
    } else {
            seperatedData.get(index).add(line);
    }
}

Upvotes: 0

Views: 55

Answers (2)

T.G
T.G

Reputation: 1921

You cannot us a List this way: Lets say you have list with 5 elements and try, to add something to index 10. It is null, so you create new sub list and add it to collection. However it will not be added at tenth position, but it will be accessible at next index (in this case it will by 5, making 6 items total).

so code below is wrong

        seperatedData.add(single);
        seperatedData.get(index).add(line);

to fix it use Map

Map<Integer,List<String>> seperatedData = new HashMap<>();

and use it:

if(seperatedData.get(index) == null) {
            List<String> single = new ArrayList<String>();
            seperatedData.put(single);
            seperatedData.get(index).add(line);
    } else {
            seperatedData.get(index).add(line);
    }

now it should work fine;

Upvotes: 0

ortis
ortis

Reputation: 2223

The variable seperatedData is an empty List. So the first time if(seperatedData.get(index) == null) is executed you get an IndexOutOfBoundsException, not matter the value of index.

Upvotes: 1

Related Questions