這篇文章主要介紹“java數組插入元素的方法有哪些”,在日常操作中,相信很多人在java數組插入元素的方法有哪些問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java數組插入元素的方法有哪些”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
1、使用 insertElement () 方法向數組插入元素
import java.util.Arrays;
public class Test{
public static void main(String args[]) throws Exception {
int array[] = {
2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };
Arrays.sort(array);
int index = Arrays.binarySearch(array, 1);
System.out.println("元素 1 所在位置(負數為不存在):"
+ index);
int newIndex = -index - 1;
array = insertElement(array, 1, newIndex);
System.out.println("添加元素1后:"+Arrays.toString(array));
}
private static int[] insertElement(int original[],
int element, int index) {
int length = original.length;
int destination[] = new int[length + 1];
System.arraycopy(original, 0, destination, 0, index);
destination[index] = element;
System.arraycopy(original, index, destination, index
+ 1, length - index);
return destination;
}
}
/* 輸出結果:
元素 1 所在位置(負數為不存在):-6
添加元素1:[-9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8]
*/2、把數組轉化為集合,向集合中添加元素,再將集合轉化為數組
import java.util.*;
public class Test{
public static void main(String[] args) {
String[] arr = {
"ID", "姓名"};
// 將數組轉化為集合 1
List<String> list1 = Arrays.asList(arr);
List<String> list2 = new ArrayList<>();
// 定義集合 2 、并向其中添加元素: 性別
list2.add("性別");
List<String> List = new ArrayList<String>();
// 定義新集合、將集合1、2中的元素添加到新集合
List.addAll(list1);
List.addAll(list2);
// 將新集合轉化回新數組
String[] newArr = List.toArray(new String[List.size()]);
System.out.println(Arrays.toString(newArr));
}
}
/* 輸出結果: [ID, 姓名, 性別] */3、創建一個新數組,新數組的大小為舊數組大小+1,把舊數組里的元素copy一份進新數組,并把要添加的元素添加進新數組即可。
到此,關于“java數組插入元素的方法有哪些”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。