[Java SE]数组超界异常分析(IndexOutOfBoundsException/ArrayIndexOutOfBoundsException)

import org.junit.Test;

import java.util.ArrayList;

/**
 * @author: Johnny
 * @date: 2021/11/12  11:17:24
 * @description: 测试数组超界异常 IndexOutOfBoundsException ArrayIndexOutOfBoundsException
 *  https://blog.csdn.net/be_happy_mr_li/article/details/53302411
 */

public class ArrayExceptionTest {
    @Test
    public void test004() {
        ArrayList<String> array = new ArrayList<String>();
        array.add(0,"hello world");
        array.add(1,"hello world");

        int index = array.indexOf("22"); //-1
        System.out.println(index);
        //array.set(index,"hello world"); //java.lang.ArrayIndexOutOfBoundsException: -1
        array.add(index,"hello world");//java.lang.IndexOutOfBoundsException: Index: -1, Size: 2
    }

    @Test
    public void test003() {
        ArrayList<String> array = new ArrayList<String>();
        array.set(0,"hello world");//java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
    }

    @Test
    public void test002() {
        ArrayList<String> array = new ArrayList<String>();
        //array.add(0,"hello world");//正常
        array.add(1,"hello world");//java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
    }
}
posted @ 2021-11-12 12:29  千千寰宇  阅读(233)  评论(0编辑  收藏  举报