Juliet Carlos
Juliet Carlos

Reputation: 1

Array out of bounds for array list comparison

I get the following error Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 5, Size: 5

for(int i=0;i<list.size();i++)
        {
            if(cmp(volume.get(i),volume.get(i+1))>0)
            {
                sorted[i]=list.get(i);
            }
            else 
            {
                sorted[i]=list.get(i+1);
            }
            System.out.println(sorted[i].toString());   
        }

Upvotes: 0

Views: 586

Answers (3)

suvojit_007
suvojit_007

Reputation: 1728

The problem is when i = list.size()-1 , you're trying to access element at list.size() and that's causing the Exception.

for(int i=0;i<list.size();i++) //<----------problem 
        {
            if(cmp(volume.get(i),volume.get(i+1))>0) //<----------problem 
            {
                sorted[i]=list.get(i);
            }

Simply change for(int i=0;i<list.size();i++) to for(int i=0;i<list.size()-1;i++)

In order to print all the Strings just add an additional statement after the for loop.

for(int i=0;i<list.size()-1;i++)
        {
            if(cmp(volume.get(i),volume.get(i+1))>0)
            {
                sorted[i]=list.get(i);
            }
            else 
            {
                sorted[i]=list.get(i+1);
            }
            System.out.println(sorted[i].toString());   
        }

  System.out.println(sorted[list.size()-1].toString());  //<----to print the last String

Upvotes: 0

Dang Nguyen
Dang Nguyen

Reputation: 1209

This will aware of the out of bounds exception for your work

if(list.size() == 1){
    //handle case the list only contain one element here
} else {
    for(int i=0; i < list.size()-1; i++) { //<===list.size()-1
    ...
        if(list.size() == i+1) {
            //handle final loop here (System.out.println(list[i+1]))
        }
}

EDIT

your work will have IndexOutOfBoundsException again when the list.size() is 1

If you want to print all value should check the latest loop and print the value out, or you can wait until all the loop is done then print it out.

EDIT #2

Update code

Upvotes: 1

Chanuka Sandeepa
Chanuka Sandeepa

Reputation: 720

replace

list.size();

as

list.size()-1;

list.size(); returns the length of the list. imagine list.size() returns 5. first time of loop there is a value in the list at the index of 0. but at the end i become 5 and there isn't index 5 in the list.

Upvotes: 0

Related Questions