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]
java向数组中增加新元素