Adding element instances to Java arrays
•
Java
The following examples demonstrate how to sort a Java array using the sort () method and insert elements into the array using the insertelement () method. Here, we define the printarray () method to print the array:
MainClass. Java file:
import java.util.Arrays; public class MainClass { public static void main(String args[]) throws Exception { int array[] = { 2,5,-2,6,-3,8,-7,-9,4 }; Arrays.sort(array); printArray("数组排序",array); int index = Arrays.binarySearch(array,1); System.out.println("元素 1 所在位置(负数为不存在):" + index); int newIndex = -index - 1; array = insertElement(array,1,newIndex); printArray("数组添加元素 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,destination,index); destination[index] = element; System.arraycopy(original,index,index + 1,length - index); return destination; } }
The output of the above code is:
The above is the whole content of this article. I hope it will help you in your study, and I hope you will support us a lot.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码