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

2021/11/12 12:40:54

本文主要是介绍[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
    }
}


这篇关于[Java SE]数组超界异常分析(IndexOutOfBoundsException/ArrayIndexOutOfBoundsException)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程