Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Arraylist got java.lang.IndexOutOfBoundsException?

I'm a general 3D artist, switched from my career and started to learn programming. I've got a problem with c106a handout #5.

The code works, but I've still got some error log here.

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 4, Size: 4
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
at UniqueNames.showUnique(UniqueNames.java:23)
at UniqueNames.main(UniqueNames.java:39)

Why does Arraylist, which can stretch its capacity on its own, still get an OutOfBoundsException?

Here's my full code:

import acm.io.*;
import acm.program.ConsoleProgram;
import acm.util.*;
import java.io.*;
import java.util.ArrayList;
import java.lang.*;

public class UniqueNames extends ConsoleProgram{

  static ArrayList<String> meString = new ArrayList<String>();
  static String input ;

    public static void storeUnique(String input){
        if (!meString.contains(input))
           {
            meString.add(input);
            }
    }

    public static void showUnique(ArrayList<String> meString){
        System.out.println("Unique name list contains:");
        for(int i=0 ;i<= meString.size() ;i++){
            System.out.println(meString.get(i));
          }
      }

    public static void main(String[] args){

             try{
                InputStreamReader stream = new InputStreamReader(System.in);
                BufferedReader br = new BufferedReader(stream);
                   while (true){
                       System.out.println("Enter name:");
                       String input = br.readLine();
                       if (input.equals("")) break;
                       storeUnique(input);
                      }  

                  {showUnique(meString);}  
                }
             catch(IOException e){
                }
    }
}
like image 976
Vittori Avatar asked Aug 26 '13 14:08

Vittori


People also ask

Can the IndexOutOfBoundsException occur to an ArrayList?

The index of an ArrayList is zero-based. Thus, to replace the first element, 0 must be the index passed as a parameter. The IndexOutOfBoundsException will occur if the provided index is out of bounds.

What does Java lang IndexOutOfBoundsException mean?

Class IndexOutOfBoundsExceptionThrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range. Applications can subclass this class to indicate similar exceptions.

Why is my ArrayList out of bounds?

The ArrayIndexOutOfBounds exception is thrown if a program tries to access an array index that is negative, greater than, or equal to the length of the array. The ArrayIndexOutOfBounds exception is a run-time exception. Java's compiler does not check for this error during compilation.


3 Answers

The following lines:

for (int i = 0; i <= meString.size(); i++) {
    System.out.println(meString.get(i));
}

should be:

for (int i = 0; i < meString.size(); i++) {
    System.out.println(meString.get(i));
}

This is because the index of the list starts from zero.

Index: 4, Size: 4 explains a little more. When you call get(4), an exception occurs because your list only has a size of 4. get(4) would attempt to access the 5th element in the list.

Valid elements you can access would be get(0), get(1), get(2), get(3).

like image 57
Suresh Atta Avatar answered Oct 17 '22 11:10

Suresh Atta


You asked, "Why does Arraylist, which can stretch its capacity by its own still get an OutOfBoundsException ???"
The answer is: an ArrayList only stretches its capacity when:

  1. You add an object to it ( .add(Object o) ).
  2. You add the contents of another collection to it ( .addAll(Collection c) ).
  3. You ensure its size ( .ensureCapacity(int minCapacity) ).

The trouble you're having is that you are trying to access an object in an index of the list that doesn't exist. While an ArrayList will dynamically resize when you change the contents, it won't do it when you are simply trying to access the contents.
That is the difference.
To avoid accessing an index that doesn't exist:

  1. Take Surresh Atta's suggestion: Use i < meString.size() instead of i <= meString.size() because the index starts with 0 instead of 1.
  2. Take Ankit's suggestion and just use the enhanced for loop: for(String str : meString).
like image 41
James Dunn Avatar answered Oct 17 '22 13:10

James Dunn


Use the above answer, or you can use a foreach loop:

for (String str: meString) {
    System.out.println(str);
}
like image 28
Ankit Avatar answered Oct 17 '22 13:10

Ankit