java数组_Java数组

java数组

Java Array is a container that can hold a fixed number of values of the same type. The values can be of the primitive type like int, short, byte, or it can be an object like String, Integer etc.

Java Array是一个容器,可以容纳固定数量的相同类型的值。 这些值可以是原始类型(例如int,short,byte),也可以是对象(例如String,Integer等)。

Java数组 (Java Array)

  • Despite the fact that array can hold primitive type and object, array itself is an object in java heap, even if it is declared to hold primitive type data.

    尽管数组可以保存基本类型和对象,但即使数组本身声明为保存基本类型数据,数组本身也是java堆中的对象。
  • We need to specify the type of values at the time of declaring the array.

    我们需要在声明数组时指定值的类型。
  • Array size needs to be provided at the time of initialization.

    初始化时需要提供数组大小。
  • Java Arrays is the utility class that provides a lot of useful methods to work with arrays.

    Java Arrays是实用程序类,提供了许多有用的方法来处理数组。
  • We can access array elements using integer index.

    我们可以使用整数索引访问数组元素。
  • We can traverse through array elements using java for loop or java forEach loop.

    我们可以使用java for循环java forEach循环遍历数组元素。
  • Array can be one dimensional as well as multidimensional.

    数组可以是一维的,也可以是多维的。
  • ArrayIndexOutOfBoundsException exception is raised when we try to access array element by specifying index value larger than the size of array.

    当我们尝试通过指定大于数组大小的索引值来访问数组元素时,引发ArrayIndexOutOfBoundsException异常。
  • List implementations such as ArrayList is backed by array. There are few utility methods to convert list to array and vice versa.

    列表实现(例如ArrayList )由数组支持。 几乎没有实用的方法可以将列表转换为数组 ,反之亦然。
  • There are utility methods to search for an element in the array or to sort an array. We will look into these through example programs in later section of this tutorial.

    有一些实用方法可以搜索数组中的元素或对数组进行排序。 我们将在本教程后面的部分中通过示例程序研究这些内容。

Let’s have a look at some important points about array through programs.

让我们看一下有关程序数组的一些重要信息。

Java中的数组声明 (Array Declaration in Java)

An Array can be declared by stating the type of data that array will hold (primitive or object) followed by the square bracket and variable name.
An array can be one dimensional or it can be multidimensional. Multidimensional arrays are in fact arrays of arrays.

可以通过声明数组将保存的数据类型(原始或对象),方括号和变量名来声明数组。
数组可以是一维的,也可以是多维的。 多维数组实际上是数组的数组。

  1. Declaring an array of primitive type of data (one dimensional):
    int[] integers;  // Recommended way of declaring an array
    int  integers[]; // Legal but not recommended

    声明原始类型的数据数组(一维)
  2. Declaring an array of object type (one dimensional):
    String[] strings; // Recommended
    String strings[];  // not Recommended

    声明对象类型的数组(一维)
  3. Declaring multidimensional array:
    int[][] integers; // Two dimensional array
    String[][][] strings; // Three dimensional array

    声明多维数组

When we are declaring an array it’s recommended that we put square bracket immediately after the declared type.

声明数组时,建议在声明的类型之后立即放置方括号。

Java初始化数组 (Java initialize array)

We can initialize an array using new keyword or using shortcut syntax, which creates and initialize array at the same time.

我们可以使用new关键字或使用快捷方式语法来初始化数组,这将同时创建和初始化数组。

Creating an array using new keyword means we are creating an array object in java heap and to create an object java needs to know how much space to allocate on the heap for that object. So we need to specify the size of the array at the time of initialization.

java initialize array

使用new关键字创建数组意味着我们要在java堆中创建一个数组对象,并且要创建一个对象,java需要知道要在堆上为该对象分配多少空间。 因此,我们需要在初始化时指定数组的大小。

  1. Initializing one dimensional array:
    int[] integers; // declaration
    integers  =  new int[5]; // Initializing an array of primitive type with size 5
    
    int[] integers = new int[5]; // declaration and initialization in one line
    
    String[] strings; // declaration
    strings = new String[5]; // initializing an array of type String object with size 5
    
    String[] strings = new String[5]; // declaration and initialization in one line

    初始化一维数组
  2. Initializing multidimensional array:
    int[][] intArr = new int[4][5];
    // multidimensional array initialization with only leftmost dimension
    int[][] intArr = new int[2][];
    intArr [0] = new int[2];
    intArr [1] = new int[3]; // complete initialization is required before we use the array

    初始化多维数组
  3. Initializing an array using shortcut syntax:
    int[] intArr = {1,2,3};
    String[] strings = {"one", "two", "three"};
    int[][] intArr2 = {{1, 2}, {1, 2, 3}};

    If you notice above, the two dimensional array intArr2 is not a symmetric matrix. It’s because a multidimensional array in java is actually an array of array. For complete explanation, refer Two Dimensional Array in Java.

    使用快捷方式语法初始化数组

    如果您在上面注意到,则二维数组inArr2不是对称矩阵。 这是因为Java中的多维数组实际上是数组的数组。 有关完整说明,请参见Java中的二维数组

  4. Invalid ways to initialize an array: Here are some invalid ways to initialize an array.
    int[] a = new int[]; // invalid because size is not provided
    int[][] aa = new int[][5]; // invalid because leftmost dimension value is not provided

    无效的数组初始化方法 :以下是一些无效的数组初始化方法。
  5. Non recommended way to initialize an array: Here are some other variations of initializing arrays in java but they are strongly discouraged to avoid confusion.
    int[] integers[] = new int[4][5];
    int integers[][] = new int[5][];

    不建议使用初始化数组的方法 :这是Java中初始化数组的其他一些方法,但是强烈建议不要使用它们,以免造成混淆。

访问数组元素 (Accessing Array Elements)

  • Array elements can be accessed by its index and it always start with the 0 (zero).

    数组元素可以通过其索引进行访问,并且始终以0(零)开头。
  • Array object have public variable called length, which gives the number of elements in the array.

    数组对象具有称为length的公共变量,该变量给出数组中元素的数量。
  • We can process or traverse array elements using for or foreach loop.

    我们可以使用forforeach循环处理或遍历数组元素。

Let’s have look at the below example program for accessing array elements in java.

让我们看一下下面的示例程序,该程序用于访问Java中的数组元素。

package com.journaldev.examples;

public class JavaArrayExample {

	public static void main(String[] args) {

		// initializing an array		
		int[] integers = {1, 2, 3, 4, 5};
		String[] strings = {"one", "two", "three", "four", "five"};
		
		// using for loop to access elements
		System.out.println("Printing integer array using for loop :");
		for (int i = 0; i<integers.length; i++) {
			System.out.println(integers[i]);
		}
		
		System.out.println("Printing string array using for loop :");
		for (int i = 0; i<strings.length; i++) {
			System.out.println(strings[i]);
		}
		
		// using foreach loop for traversing through array
		System.out.println("Printing integer array using foreach loop :");
		for (int i : integers) {
			System.out.println(i);
		}
		
		System.out.println("Printing string array using foreach loop :");
		for (String s : strings) {
			System.out.println(s);
		}
	}
}

Now let’s look at an example of printing two-dimensional array using nested for loops.

现在,让我们看一个使用嵌套的for循环打印二维数组的示例。

package com.journaldev.examples;

public class TwoDimensionalArrayExample {

	public static void main(String[] args) {

		// initializing an array
		int[][] integers = { { 1, 2, 3 }, { 4, 5, 6 } };

		for (int i = 0; i < integers.length; i++) {
			for (int j = 0; j < integers[i].length; j++) {
				System.out.print(integers[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}
}

什么是ArrayIndexOutOfBoundsException? (What is ArrayIndexOutOfBoundsException?)

Sometimes we try to access element outside the array size; for example if we have an array of size 10 and if we try to access 11th element then compiler will throw ArrayIndexOutOfBoundsException.

有时,我们尝试访问数组大小之外的元素; 例如,如果我们有一个大小为10的数组,并且如果尝试访问第11个元素,则编译器将抛出ArrayIndexOutOfBoundsException

Let’s have a look at the below example program.

让我们看一下下面的示例程序。

package com.journaldev.examples;

public class ArrayIndexOutOfBoundExample {

	public static void main(String[] args) {
		
		// declaring and initializing an array
		int[] a = new int[2];
		a[0] = 1;
		a[1] = 2;
		
		System.out.println(a[2]);
	}

}

Output of above program is:

上面程序的输出是:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
	at com.journaldev.examples.ArrayIndexOutOfBoundExample.main(ArrayIndexOutOfBoundExample.java:18)

将数组转换为列表,反之亦然 (Converting Array to List and Vice Versa)

package com.journaldev.examples;

import java.util.Arrays;
import java.util.List;

public class ArrayConversionExample {

	public static void main(String[] args) {
		
		// initializing an array
		String[] strings = {"one", "two", "three", "four", "five"};
		
		//Converting array to list
		List<String> list = Arrays.asList(strings);
		System.out.println("Array to List : "+list);
		
		//Converting list to array
		String[] strings2 = list.toArray(new String[list.size()]);
		System.out.println("List to Array :");
		for (String string : strings2) {
			System.out.println(string);
		}
	}
}

Output of above program is:

上面程序的输出是

Array to List : [one, two, three, four, five]
List to Array :
one
two
three
four
five

Java排序数组 (Java Sort Array)

Arrays can be sorted by using java.util.Arrays sort method which sorts the given array into an ascending order. Below is a simple program for sorting arrays.

可以使用java.util.Arrays sort方法对数组进行排序,该方法将给定数组按升序排序。 下面是一个简单的数组排序程序。

package com.journaldev.examples;

import java.util.Arrays;

public class ArraysSortExample {

	public static void main(String[] args) {
		
		// initializing an array of Character
		char[] chars = {'B', 'D', 'C', 'A', 'E'};
		// sorting array of Character
		Arrays.sort(chars);
		System.out.print("Sorted Characters : ");
		for (char character : chars) {
			System.out.print(character+" ");
		}
		
		// initializing an array of Integer
		int[] integers = {5, 2, 1, 4, 3};
		// sorting array of Integer
		Arrays.sort(integers);
		System.out.print("\nSorted Integers : ");
		for (int i : integers) {
			System.out.print(i+" ");
		}
	}
}

Output of above program is:

上面程序的输出是

Sorted Characters : A B C D E 
Sorted Integers : 1 2 3 4 5

在Java数组中搜索元素 (Searching for element in Java Array)

java.util.Arrays provides binarySearch method which uses binary search algorithm to search specified value from the given array. Below is a simple program for searching element in an array using binary search. The array must be sorted prior to making this call. If it is not sorted, the results are undefined. If the array contains multiple elements with the specified value, there is no guarantee which one will be found.

java.util.Arrays提供了binarySearch方法,该方法使用二进制搜索算法从给定数组中搜索指定的值。 下面是一个使用二进制搜索来搜索数组中元素的简单程序。 在进行此调用之前,必须对数组进行排序。 如果未排序,则结果不确定。 如果数组包含具有指定值的多个元素,则不能保证将找到哪个元素。

package com.journaldev.examples;

import java.util.Arrays;

public class ArraysBinarySearchExample {

	public static void main(String[] args) {

		// Searching a value from array of integer
		int[] integers = { 5, 2, 1, 4, 3, 9, 6, 8, 7, 10 };
		int index = Arrays.binarySearch(integers, 2);
		if (index >= 0) {
			System.out.println("Element is found at the index :" + index);
		} else {
			System.out.println("Element is not found");
		}

		// Searching a value from array of integer with specific range
		int fromIndex = 2;
		int toIndex = 7;
		int index2 = Arrays.binarySearch(integers, fromIndex, toIndex, 9);
		if (index2 >= 0) {
			System.out.println("Element is found at the index :" + index2);
		} else {
			System.out.println("Element is not found");
		}

	}

}

Output of above program is:

上面程序的输出是

Element is found at the index :1
Element is found at the index :5

Java复制数组 (Java Copy Array)

Object class provides clone() method and since an array in java is also an Object, you can use this method to achieve full array copy. This method will not suit you if you want a partial copy of the array. Below is a simple program for copying arrays in java.

Object类提供了clone()方法,并且由于java中的数组也是Object,因此可以使用此方法实现完整的数组复制。 如果要部分复制数组,则此方法不适合您。 下面是一个用于复制Java中数组的简单程序。

package com.journaldev.examples;

public class CopyingArrayExample {

	public static void main(String[] args) {
		
		// initialing an array
		int[] integers = {1, 2, 3, 4, 5};
		String[] strings = {"one", "two", "three", "four", "five"};
		
		//Copying Arrays
		int[] copyIntegers = integers.clone();
		System.out.println("Copy of Integer array :");
		for (int i : copyIntegers) {
			System.out.println(i);
		}
		
		String[] copyStrings = strings.clone();
		System.out.println("Copy of String array :");
		for (String string : copyStrings) {
			System.out.println(string);
		}
		
		//Copying two dimensional array
		int[][] arr = { { 1, 2, 3 }, { 4, 5, 6 } };
		int[][] copyArr = arr.clone();
		System.out.println("Copy of two dimensional Integer array :");
		for (int i = 0; i < copyArr.length; i++) {
			for (int j = 0; j < copyArr[i].length; j++) {
				System.out.print(copyArr[i][j]);
				System.out.print(" ");
			}
			System.out.println();
		}
	}

}

There are many other ways to copy the array in java. Please refer java copy array to learn other ways.

还有许多其他方法可以在Java中复制数组。 请参考Java复制数组以了解其他方法。

向数组添加元素 (Add elements to Array)

There is no shortcut method to add elements to an array in java. But as a programmer, we can write one. Here I am providing a utility method that we can use to add elements to an array.

没有快捷方式可以在Java中向数组添加元素。 但是作为程序员,我们可以编写一个。 在这里,我提供了一种实用程序方法,可用于将元素添加到数组中。

package com.journaldev.examples;

import java.util.Arrays;

public class ArrayAddElementExample {

	public static void main(String[] args) {
		
		//initializing one array
		int[] a1 = {1, 2, 3, 4, 5};
		//element to be added
		int i = 6;
		//initializing second array
		int[] a2 = new int[a1.length+1];
		//copy first array into second
		System.arraycopy(a1, 0, a2, 0, a1.length);
		
		//add element to second array
		a2[a2.length-1] = i;
		System.out.println("Old Array: "+Arrays.toString(a1));
		System.out.println("New Array: "+Arrays.toString(a2));
		
		
	}
}

Output of the above program is:

上面程序的输出是:

Old Array: [1, 2, 3, 4, 5]
New Array: [1, 2, 3, 4, 5, 6]

从数组中删除元素 (Remove element from Array)

Below is a simple program to remove element from array.

下面是一个简单的程序,用于从数组中删除元素。

package com.journaldev.examples;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class RemoveElementFromArrayExample {

	public static void main(String[] args) {
		
		// initializing array
		String[] strings = {"one", "two", "three", "four", "five"};
		System.out.println("Array Before Removing element : "+Arrays.toString(strings));
		List<String> list = new ArrayList<>();
		String elementTobeRemoved = "four";
		for (String string : strings) {
			if (!string.equals(elementTobeRemoved)) {
				list.add(string);
			}
		}
		System.out.println("Array After Removing element : "+Arrays.toString(list.toArray(new String[list.size()])));
	}

}

Output of the above program is:

上面程序的输出是:

Array Before Removing element : [one, two, three, four, five]
Array After Removing element : [one, two, three, five]

That’s all for Java Array tutorial, I hope nothing important got missed here.

Java Array教程就这些了,我希望这里不会错过任何重要的事情。

Reference: Oracle Documentation

参考: Oracle文档

翻译自: https://www.journaldev.com/16851/java-array

java数组

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值