java set arraylist_Java ArrayList set()用法及代码示例

java.util.ArrayList类的set()方法用于使用指定元素替换此列表中指定位置的元素。

用法:

public E set(int index, E element)

参数:此方法将以下参数作为参数。

index-替换元素的索引

element-要存储在指定位置的元素

返回值:此方法返回先前位于指定位置的元素。

异常:如果索引不在ArrayList的大小范围内,则此方法将引发IndexOutOfBoundsException。

以下示例说明了set()方法。

示例1:

// Java program to demonstrate

// set() method

// for Integer value

import java.util.*;

public class GFG1 {

public static void main(String[] argv) throws Exception

{

try {

// Creating object of ArrayList

ArrayList

arrlist = new ArrayList();

// Populating arrlist1

arrlist.add(1);

arrlist.add(2);

arrlist.add(3);

arrlist.add(4);

arrlist.add(5);

// print arrlist

System.out.println("Before operation: "

+ arrlist);

// Replacing element at the index 3 with 30

// using method set()

int i = arrlist.set(3, 30);

// Print the modified arrlist

System.out.println("After operation: "

+ arrlist);

// Print the Replaced element

System.out.println("Replaced element: "

+ i);

}

catch (IndexOutOfBoundsException e) {

System.out.println("Exception thrown: "

+ e);

}

}

}

输出:

Before operation : [1, 2, 3, 4, 5]

After operation : [1, 2, 3, 30, 5]

Replaced element : 4

示例2:对于IndexOutOfBoundsException

// Java program to demonstrate

// set() method

// for IndexOutOfBoundsException

import java.util.*;

public class GFG1 {

public static void main(String[] argv) throws Exception

{

try {

// Creating object of ArrayList

ArrayList

arrlist = new ArrayList();

// Populating arrlist1

arrlist.add(1);

arrlist.add(2);

arrlist.add(3);

arrlist.add(4);

arrlist.add(5);

// print arrlist

System.out.println("Before operation : "

+ arrlist);

// Replacing element at the index 7 with 30

// using method set()

System.out.println("\nTrying to Replace"

+ " the element at"

+ " (index > Capacity) ");

int i = arrlist.set(7, 30);

// Print the modified arrlist

System.out.println("After operation: "

+ arrlist);

// Print the Replaced element

System.out.println("Replaced element: "

+ i);

}

catch (IndexOutOfBoundsException e) {

System.out.println("Exception thrown : " + e);

}

}

}

输出:

Before operation : [1, 2, 3, 4, 5]

Trying to Replace the element at (index > Capacity)

Exception thrown : java.lang.IndexOutOfBoundsException: Index: 7, Size: 5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值