Java數(shù)組添加元素實例
以下實例演示了如何使用sort()方法對Java數(shù)組進行排序,及如何使用 insertElement () 方法向數(shù)組插入元素, 這邊我們定義了 printArray() 方法來打印數(shù)組:
MainClass.java 文件:
import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 }; Arrays.sort(array); printArray("數(shù)組排序", array); int index = Arrays.binarySearch(array, 1); System.out.println("元素 1 所在位置(負(fù)數(shù)為不存在):" + index); int newIndex = -index - 1; array = insertElement(array, 1, newIndex); printArray("數(shù)組添加元素 1", array); } private static void printArray(String message, int array[]) { System.out.println(message + ": [length: " + array.length + "]"); for (int i = 0; i < array.length; i++) { if (i != 0){ System.out.print(", "); } System.out.print(array[i]); } System.out.println(); } 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; } }
以上代碼運行輸出結(jié)果為:
數(shù)組排序: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8
元素 1 所在位置(負(fù)數(shù)為不存在):-6
數(shù)組添加元素 1: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Springboot之restTemplate的配置及使用方式
這篇文章主要介紹了Springboot之restTemplate的配置及使用方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10java中實現(xiàn)對象排序的兩種方法(Comparable,Comparator)
這篇文章主要給大家介紹了關(guān)于java中實現(xiàn)對象排序的兩種方法,一種是實現(xiàn)Comparable進行排序,另一種是實現(xiàn)Comparator進行排序,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12Java?Web中ServletContext對象詳解與應(yīng)用
ServletContext是一個容器,可以用來存放變量,供一個web項目中多個Servlet共享,下面這篇文章主要給大家介紹了關(guān)于Java?Web中ServletContext對象詳解與應(yīng)用的相關(guān)資料,需要的朋友可以參考下2023-04-04