java向数组中增加新元素_用Java中的新元素替换List的给定索引处的元素

java向数组中增加新元素

Given a list of the integers and we have to replace it an element from specified index with a new element in java.

给定一个整数列表,我们必须用Java中的新元素将其替换为指定索引中的一个元素。

To replace an element in the list - we use List.set() method.

替换列表中的元素 -我们使用List.set()方法。

List.set()方法 (List.set() method)

List.set() method replaces an existing element at given index with new element and returns the old object/element.

List.set()方法将给定索引处的现有元素替换为新元素,并返回旧对象/元素。

Syntax:

句法:

    Object List.set(index, new_object);

Example:

例:

    Input:
    List = [10, 20, 30, 40, 50]
    Index =1 
    new_element = 1000

    Output:
    Updated list =[10, 1000, 30, 40, 50]

Program:

程序:

import java.util.*;
public class ListExample {
	public static void main (String[] args) 
	{
		//creating a list of integers
		List<Integer> int_list = new ArrayList<Integer> ();

		//adding some of the elements 
		int_list.add (10) ;
		int_list.add (20) ;
		int_list.add (30) ;
		int_list.add (40) ;
		int_list.add (50) ;

		//replace elements
		int old_ele, new_ele, index;
		index =0; new_ele=12;
		old_ele = int_list.set (index, new_ele);
		System.out.println (old_ele+" is replace with "+new_ele);

		index =2; new_ele=24;
		old_ele = int_list.set (index, new_ele);
		System.out.println (old_ele+" is replace with "+new_ele);

		//printing updated list 
		System.out.println ("updated list: " + int_list);
	}
};

Output

输出量

10 is replace with 12
30 is replace with 24
updated list: [12, 20, 24, 40, 50]


另一个示例:将EVEN索引的所有元素替换为0,将ODD索引替换为1 (Another Example: Replace all elements of EVEN indexes with 0 and ODD indexes by 1 )

Example:

例:

    Input:
    List = [10, 20, 30, 40, 50]

    Output:
    Updated list =[0, 1, 0, 1, 0]

Program:

程序:

import java.util.*;
public class ListExample {
	public static void main (String[] args) 
	{
		//creating a list of integers
		List<Integer> int_list = new ArrayList<Integer> ();
		
		//adding some of the elements 
		int_list.add (10) ;
		int_list.add (20) ;
		int_list.add (30) ;
		int_list.add (40) ;
		int_list.add (50) ;
		
		System.out.println ("len: " + int_list.size ());
		//replace elements 
		for (int i=0; i<int_list.size(); i++) {
			if (i%2==0)
				int_list.set (i, 0);
			else
				int_list.set (i, 1);		
		}
		
		//printing updated list 
		System.out.println ("updated list: " + int_list);
	}
};

Output

输出量

len: 5
updated list: [0, 1, 0, 1, 0]


翻译自: https://www.includehelp.com/java-programs/replace-an-element-at-given-index-of-a-list-with-new-element-in-java.aspx

java向数组中增加新元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值