Home > Java > javaTutorial > body text

Java example - adding elements to array

黄舟
Release: 2017-02-18 09:58:29
Original
1672 people have browsed it

The following example demonstrates how to use the sort() method to sort a Java array, and how to use the insertElement () method to insert elements into the array. Here we define the printArray() method to print the array:

/*
 author by w3cschool.cc
 文件名: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;
   }}
Copy after login

The output result of running the above code is:

数组排序: [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
Copy after login

The above is the Java example - the content of adding elements to the array. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!