Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last element of a list

Tags:

java

arraylist

I've been tasked to do the below in a newbie Java tutorial on ArrayList

// 1) Declare am ArrayList of strings
    // 2) Call the add method and add 10 random strings
    // 3) Iterate through all the elements in the ArrayList
    // 4) Remove the first and last element of the ArrayList
    // 5) Iterate through all the elements in the ArrayList, again.

Below is my code

import java.util.ArrayList;
import java.util.Random;

public class Ex1_BasicArrayList {

    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i = 0; i <= 10; i++){
            Random rand = new Random();
            String randy = String.valueOf(rand);
            list.add(randy );
        }
        for (int i = 0; i < list.size(); i++){
            System.out.print(list.get(i));
        }   
        list.remove(0);
        list.remove(list.size());

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

The code runs, but I get the below error message when it runs. Any ideas on what I'm doing wrong?

[email protected]@[email protected]@[email protected]@[email protected]@[email protected]@6bc7c054Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
    at java.util.ArrayList.rangeCheck(Unknown Source)
    at java.util.ArrayList.remove(Unknown Source)
    at apollo.exercises.ch08_collections.Ex1_BasicArrayList.main(Ex1_BasicArrayList.java:23)
like image 628
Kenneth Yong Avatar asked Jan 08 '15 22:01

Kenneth Yong


2 Answers

List indices go from 0 to list.size() - 1. Exceeding the upper bound results in the IndexOutOfBoundsException

list.remove(list.size() - 1);
like image 123
Reimeus Avatar answered Oct 17 '22 05:10

Reimeus


Your list has 11 elements, their indices are 0-10. When you call list.remove(list.size());, you are telling it to remove the element at index 11 (because the size of the list is 11), but that index is out of bounds.

The index of the last element of any list is always list.size() - 1.

like image 31
Zoltán Avatar answered Oct 17 '22 07:10

Zoltán