简体   繁体   English

尽管在列表的容量内添加了ArrayList IndexOutOfBoundsException

[英]ArrayList IndexOutOfBoundsException despite adding within the capacity of the list

I have following code 我有以下代码

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(1, 555);
}

and it is initialize with 10 elements but i am getting exception 它用10个元素初始化,但我得到例外

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0   
   at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:612)  
   at java.util.ArrayList.add(ArrayList.java:426)   
   at ListTest.main(ListTest.java:9)

while below code working fine 虽然下面的代码工作正常

public static void main(String[] args) {
    List<Integer> list = new ArrayList<>();
    list.add(0, 555);
}

Why can someone explain me ? 为什么有人可以解释我? and How to fix the issue i want to put item in 1th,2nd or 5th position in my code ? 以及如何解决问题我想在我的代码中将项目放在第1,第2或第5位?

it is initialize with 10 elements 它用10个元素初始化

No, it isn't. 不,不是。 It's initialized with an internal buffer size of 10, but that's largely an implementation detail. 它的初始化内部缓冲区大小为10,但这主要是一个实现细节。 The size of the list is still 0, as you can confirm by printing out list.size() before your add call. 列表的大小仍为0,因为您可以在add调用之前打印出list.size()来确认。

It's important to differentiate between "amount of space in the buffer ready to accept more elements without copying" and "the size of the list". 区分“缓冲区中的空间量准备接受更多元素而不复制”和“列表大小”非常重要。 From the add documentation : add文档

Throws: 抛出:
IndexOutOfBoundsException - if the index is out of range ( index < 0 || index > size() ) IndexOutOfBoundsException - 如果index超出范围( index < 0 || index > size()

Here size() is 0, and 1 > 0 , hence the exception. 这里size()为0,1 1 > 0 ,因此是例外。

You should always check the documentation before assuming that it's the framework (or compiler) that's wrong. 在假设它是错误的框架(或编译器)之前,您应该始终检查文档。

How to fix the issue i want to put item in 1th,2nd or 5th position in my code? 如何解决问题我想把项目放在我的代码中的第1,第2或第5位?

You either need to add enough elements first, eg 可能需要先添加足够的元素,如

for (int i = 0; i < 10; i++) {
    list.add(null);
}
list.set(1, 555);
list.set(2, 500);
list.set(5, 200);

Note that these are set operations, not add - it's not clear whether you really want to insert or modify. 请注意,这些是设置操作,而不是添加 - 不清楚是否真的要插入或修改。

Or you should potentially use an array instead. 或者您应该使用数组代替。 For example: 例如:

int[] array = new int[10];
array[1] = 555;
array[2] = 500;
array[5] = 200;

In both cases, it's important to understand that indexes are 0-based - so list.set(1, 555) changes the second element of the list. 在这两种情况下,重要的是要理解索引是基于0的 - 所以list.set(1, 555)更改列表的第二个元素。 You'd want list.set(0, 555) to change the first element. 你想要list.set(0, 555)来改变第一个元素。 The same applies for arrays. 这同样适用于数组。

Here is your answer : The code snippet of public void add(int index, E element) { 这是你的答案: public void add(int index, E element) {的代码片段public void add(int index, E element) {

 if (index > size || index < 0)
        throw new IndexOutOfBoundsException(
        "Index: "+index+", Size: "+size);

basically, when you do new ArrayList() the size of the list will be 0 . 基本上,当你执行new ArrayList()时,列表的大小将为0 Since your index is greater than size , you get IndexOutOfBoundsException 由于索引 大于 size ,因此会得到IndexOutOfBoundsException

You have to add elements to a list gradually, the list will be extended automatically. 您必须逐渐向列表中添加元素,列表将自动扩展。

If you want to add a certain element on a specific position, and you know the length of the amount of items you want; 如果您想在特定位置添加某个元素,并且您知道所需项目数量的长度; you can use an Integer array and convert that to a list afterwards, for example 例如,您可以使用整数数组并将其转换为列表

public static void main(String []args){
    Integer []fixedLengthArray = new Integer[5];
    fixedLengthArray[1] = 3;
    List<Integer> intList = Arrays.asList(fixedLengthArray);
    for(int i= 0;i<intList.size();i++)System.out.println("Value of index "+i+":"+intList.get(i));
}

Output will be: 输出将是:

Value of index 0:null Value of index 1:3 Value of index 2:null Value of index 3:null Value of index 4:null 索引0的值:null索引1的值:3索引的值2:null索引的值3:null索引的值4:null

While the method is called add it is really an insert operation. 虽然这个方法被称为add但它实际上是一个插入操作。 You are essentially telling Java 'put this after the first item in the list' and Java is replying 'there is no first item in the list'. 你实际上是在告诉Java'把它放在列表中的第一项之后'并且Java正在回复'列表中没有第一项'。

Fist of all it will give a compilation error on 所有它的拳头将给出编译错误

List<Integer> list = new ArrayList<>(); 

for ArrayList<Integer>() for ArrayList<Integer>()

and it is initialize with 10 elements Where you did that.? and it is initialize with 10 elements你在哪里做的。

What we see, It's not initialized with 10 elements actually its empty that why when you try to add something on index 1 it's giving IndexOutOfBound on line 我们看到,它没有初始化10个元素实际上是空的,为什么当你尝试在索引1上添加一些东西时它会在线上给出IndexOutOfBound

list.add(0, 555);
public static void main(String[] args) {
     List<Integer> list = new ArrayList<>(1);
     list.add(0, 555);
}

This code will help. 这段代码会有所帮助。 This add method with index can be invoke if there is data in that index position. 如果索引位置中有数据,则可以调用带索引的add方法。

Because, at the second code piece zero is the first index. 因为,在第二个代码片段,零是第一个索引。 But at the first code piece one is not the first index and there isn't any memory allocation for your index. 但是在第一个代码片段中,一个不是第一个索引,并且没有为您的索引分配任何内存。

You have to do like that; 你必须这样做;

public static void main(String[] args) {
             List<Integer> list = new ArrayList<>();
             list.add(0, 555); //Correct
             list.add(1, 55); //Correct
             list.add(2, 525); //Correct
             list.add(5, 55235); // Not-correct  ! 
        }

or 要么

Create a list and assign all indexes with a default value. 创建列表并使用默认值分配所有索引。 Then use the index which you want. 然后使用您想要的索引。

public static void main(String[] args) {
             List<Integer> list = new ArrayList<>();
             for(int i=0; i<10; i++)
             {
                 list.add(null);//or default value like -99
              }
             list.add(0, 555); //Correct
             list.add(1, 55); //Correct
             list.add(2, 525); //Correct
             list.add(5, 55235); //correct  ! 
        }

or 要么

Just do that 就这样做

int[] array = new int[10];

It's because you will not get fruits from the tree untill you plant the Tree as simple as that . 这是因为你不会从树上获得水果 ,直到你把树种植得那么简单。

When you initialised the list , it is an empty list , which can be verified by list.size() which will return 0 , Now you have 0 elements in the list and you are trying to access the 1 index , So it is giving you the exception 初始化列表时,它是一个空列表,可以通过list.size()验证,它将返回0 ,现在列表中有0个元素,并且您正在尝试访问1索引,所以它给了你例外

From Java Docs 来自Java Docs

void add(int index,
       E element)

Inserts the specified element at the specified position in this list(optional operation). 将指定元素插入此列表中的指定位置(可选操作)。 Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices). 将当前位置的元素 (如果有)和任何后续元素向右移动 (将其添加到其索引中)。

and it Throws: 并且它Throws:

IndexOutOfBoundsException - if the index is out of range (index < 0 || index > size()) IndexOutOfBoundsException - 如果索引超出范围(索引<0 || index> size())

Your 'list' is still an ArrayList So you can not change its index (Normally, index of an arraylist must be started at 0). 你的'list'仍然是一个ArrayList所以你不能改变它的索引(通常,arraylist的索引必须从0开始)。 So that the reason why when you put " list.add(1,555) " it throw an error. 这就是为什么当你把“list.add(1,555)”它抛出一个错误。

Just simple list.add(555) 只是简单的list.add(555)

Instead of ArrayList you can use Map, SortedMap, HashMap, TreeMap. 您可以使用Map,SortedMap,HashMap,TreeMap代替ArrayList。 Those will store values as a pair Key - Value. 那些将值存储为Key - Value。

Hashtable<Integer,Integer> list = new Hashtable<>();
list.put(1, 555);

HashMap<Integer,Integer> list2 = new HashMap<Integer,Integer>();
list2.put(3, 555);

Hope this help! 希望这有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尽管提供了初始容量,但 Java ArrayList IndexOutOfBoundsException - Java ArrayList IndexOutOfBoundsException despite giving an initial capacity 添加到arraylist中的列表时出现IndexOutOfBoundsException - IndexOutOfBoundsException while adding to a list in an arraylist 添加到ArrayList时出现IndexOutOfBoundsException - IndexOutOfBoundsException when adding to ArrayList 在索引处添加到 ArrayList 时出现 IndexOutOfBoundsException - IndexOutOfBoundsException when adding to ArrayList at index IndexOutOfBoundsException at Index: 4, Size: 4 将元素添加到 ArrayList 时 - IndexOutOfBoundsException at Index: 4, Size: 4 when adding elements to an ArrayList ArrayList IndexOutOfBoundsException - ArrayList IndexOutOfBoundsException 使用嵌套 while 循环添加到 ArrayList 时出现 IndexOutOfBoundsException - IndexOutOfBoundsException when adding to ArrayList using nested while loops Android ArrayList-逐一添加项目会导致IndexOutOfBoundsException - Android ArrayList - Adding items one by one results in IndexOutOfBoundsException 将人员添加到ArrayList中,除非他们已经在列表中(名字和姓氏字符串) - Adding person to ArrayList unless they are already within the list (firstName and surname strings) 尽管列表中存在对象,但在Long类型的ArrayList上使用indexOf返回-1 - Using indexOf on ArrayList of type Long returns -1, despite the object existing within the list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM