Java ArrayList add(index,element) 方法抛出Exception in thread "main" java.lang.IndexOutOfBoundsException

准备使用ArrayList 的 add(index,element) 来插入元素,天真的以为这样能给list排序,结果抛出:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1

代码如下:


import java.util.ArrayList;
import java.util.List;

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

抛出异常:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 1
    at java.util.ArrayList.rangeCheckForAdd(Unknown Source)
    at java.util.ArrayList.add(Unknown Source)
    at test.main.TestQuene.main(TestQuene.java:24)

编译运行之后抛出了exception,百思不得其解,等到看了源码之后才发现原因,ArrayList  add(index,element)方法源码:

public void add(int index, E element) {
   if (index > size || index < 0)
       throw new IndexOutOfBoundsException(
       "Index: "+index+", Size: "+size);
 
   ensureCapacity(size+1);  // Increments modCount!!
   System.arraycopy(elementData, index, elementData, index + 1,
            size - index);
   elementData[index] = element;
   size++;
}

从代码中可以看出,当数组中的元素个数(size)小于index的时候,此方法是会抛出异常的。

所以此方法只适用于想要插入的位置小于数组中实际元素个数的时候才有作用。

也就是说,让list里面没有元素时,想通过插入元素到指定位置来达到排序的效果是不可行的。

回答: 引发异常"Exception in thread "main" java.lang.UnsupportedOperationException: remove"的原因是在调用Arrays.asList()方法生成的List对象上调用了add或remove方法。\[2\]Arrays.asList()返回的是Arrays的内部类ArrayList,而不是java.util.ArrayList。Arrays的内部类ArrayList继承自AbstractList,而AbstractList中的remove和add方法默认会抛出UnsupportedOperationException异常。\[3\]解决这个问题的方法是将Arrays.asList()生成的List对象转换为java.util.ArrayList对象,然后再进行add或remove操作。例如,可以使用以下代码解决这个问题: ``` String\[\] array = {"1","2","3","4","5"}; List<String> list = Arrays.asList(array); List<String> arrList = new ArrayList<>(list); arrList.add("6"); ``` #### 引用[.reference_title] - *1* *3* [java.lang.UnsupportedOperationException解决方法!!!](https://blog.csdn.net/lcdaaaa/article/details/80240030)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [java:Exception in threadmainjava.lang.UnsupportedOperationException](https://blog.csdn.net/qq_44732146/article/details/125866796)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值