美文网首页
ArrayList对象中remove()方法的使用

ArrayList对象中remove()方法的使用

作者: Hnnn | 来源:发表于2017-03-31 22:08 被阅读0次

    今天在使用ArrayList时,初始化了一个test变量:

    ArrayList<Integer> test = new ArrayList<Integer>(3);
    test.add(1);
    test.add(2);
    test.add(3);
    

    当我想删除其中的3时:
    test.remove(3);

    却抛出了异常:

    Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
        at java.util.ArrayList.rangeCheck(Unknown Source)
        at java.util.ArrayList.remove(Unknown Source)
        at Game.main(Game.java:32)
    

    我发现是其中的remove方法出现了问题,于是就去看了下remove方法的具体说明:

    1. remove(int index) : Integer - ArrayList
    2. remove(Object o) : boolean - ArrayList

    一般情况在remove括号中输入整数它会识别为一个索引,即我们输入3,那么它会识别为我们要删除下标为3的元素,但是test中并不存在这个下标元素,所以就抛出了异常,所以当你要删除3这个元素时,remove应该这么写:
    test.remove((Integer)3);

    或者通过indexOf方法获得元素3的索引值进行删除:
    test.remove(test.indexOf(3));

    相关文章

      网友评论

          本文标题:ArrayList对象中remove()方法的使用

          本文链接:https://www.haomeiwen.com/subject/elfbottx.html