Java 实例 - 数组添加元素

Java 教程 · 2019-02-10 10:12:10

以下实例演示了如何使用sort()方法对Java数组进行排序,及如何使用 insertElement () 方法向数组插入元素, 这边我们定义了 printArray() 方法来打印数组:

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("数组排序", 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, 0, destination, 0, index); destination[index] = element; System.arraycopy(original, index, destination, index + 1, length - index); return destination; } }

以上代码运行输出结果为:

数组排序: [length: 10] -9, -7, -3, -2, 0, 2, 4, 5, 6, 8 
元素 1 所在位置(负数为不存在):-6 
数组添加元素 1: [length: 11] -9, -7, -3, -2, 0, 1, 2, 4, 5, 6, 8

点击查看所有 Java 教程 文章: https://codercto.com/courses/l/12.html

查看所有标签

The Probabilistic Method

The Probabilistic Method

Noga Alon、Joel H. Spencer / Wiley-Interscience / 2008-8-11 / USD 137.00

Praise for the Second Edition : "Serious researchers in combinatorics or algorithm design will wish to read the book in its entirety...the book may also be enjoyed on a lighter level since the diffe......一起来看看 《The Probabilistic Method》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具