数组的三种方式总结 多维数组的遍历 Arrays类的常用方法总结
Java数组
一.数组的三种声明方式
public class WhatEver { public static void main(String[] args) { //第一种 例: String[] test1 = new String[6]; test1[0] = "数组0"; test1[1] = "数组1"; //第二种 例: String[] test2 = {"数组0","数组1","数组2","...."}; //第三种 例: String[] test3 = new String[]{"数组0","数组1","数组2","...."}; } }
二.多维数组的遍历
数组是Java中的一种容器对象,它拥有多个单一类型的值。当数组被创建的时候数组长度就已经确定了。在创建之后,其长度是固定的。下面是一个长度为10的数组。
public class ArrayDemo{ private int arraySize=10; public int [] arrayOfIntegers = new int[arraySize]; }
上面的代码是一维数组的例子。换句话说,数组长度只能在一个方向上增长。很多时候我们需要数组在多个维度上增长。这种数组我们称之为多维数组。为简单起见,我们将它称为2维数组。当我们需要一个矩阵或者X-Y坐标系的时候,二维数组是非常有用的。下面就是一个二维数组的例子:
public class TheProblemOf2DArray { private static final int ARR_SIZE=10; public static void main(String[] args) { int arr[][]=new int[ARR_SIZE][ARR_SIZE]; } }
然而 在java中并没有二维数组,其实,当你定义一个二维数组的时候 ,其实就是定义了一个一维数组的数组。这意味着,在上面的例子中,二维数组是一个数组的引用,其每一个元素都是另一个int数组的引用。
不同的遍历方式对性能的影响非常大 比如看下面的例子
package arrayTraverse; /** * 二维数组的问题 * * 我们在初始化一个任意大小的2维数组。(为简化分析我们使用二维方阵)我们将用两种不同方式迭代同一个数组,分析结果 * 两种迭代方式的性能差距很大 * @author mohit * */ public class TheProblemOf2DArray { //数组大小:数组越大,性能差距越明显 private static final int ARR_SIZE=9999; public static void main(String[] args) { //新数组 int arr[][]=new int[ARR_SIZE][ARR_SIZE]; long currTime=System.currentTimeMillis(); colMajor(arr); System.out.println("Total time in colMajor : "+(System.currentTimeMillis()-currTime)+" ms"); //新数组,与arr完全相同 int arr1[][]=new int[ARR_SIZE][ARR_SIZE]; currTime=System.currentTimeMillis(); rowMajor(arr1); // this is the only difference in above System.out.println("Total time in col : "+(System.currentTimeMillis()-currTime) +" ms"); } /** * 下面的代码按列为主遍历数组 * 即在扫描下一行之前先扫描完本行 * */ private static void colMajor(int arr[][]) { for(int i=0;i<ARR_SIZE;i++){ for (int j=0;j<ARR_SIZE;j++){ //See this, we are traversing j first and then i arr[i][j]=i+j; } } } /** * 如果我们转换内外循环 * 程序就以行为主顺序遍历数组 * 即在扫描下一列之前先扫描完本列 * 这意味着我们访问数组时每次都在访问不同的行(因此也在访问不同的页) * 代码微小的改变将导致这个程序花费更多的时间完成遍历 */ private static void rowMajor(int arr[][]) { for(int i=0;i<ARR_SIZE;i++){ for (int j=0;j<ARR_SIZE;j++){ /*看这个,我们先遍历j,然后遍历i,但是对于访问元素来说 * 它们在更远的位置,所以需要花费的更多 */ arr[j][i]=i+j; } } } }
三.Arrays类
java.util.Arrays 类能方便地操作数组,它提供的所有方法都是静态的。
具有以下功能:
- 给数组赋值:通过 fill 方法。
- 对数组排序:通过 sort 方法,按升序。
- 比较数组:通过 equals 方法比较数组中元素值是否相等。
- 查找数组元素:通过 binarySearch 方法能对排序好的数组进行二分查找法操作。
具体说明请查看下表: