Java数组在被建立的时候肯定数组长度。索引下标从0开始。html
1.数组定义及初始化java
int[] anArray;//定义 anArray = new int[2];//初始化 anArray[0] = 100;//赋值 anArray[1] = 200;//赋值 System.out.println("Element at index 0: " + anArray[0]);//使用 System.out.println("Element at index 1: " + anArray[1]);//使用
程序输出:api
Element at index 0: 100 Element at index 1: 200
2.定义初始化同时赋值数组
int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
3.多维数组
oracle
String[][] names = { {"Mr. ", "Mrs. ", "Ms. "}, {"Smith", "Jones"} }; System.out.println(names[0][0] + names[1][0]); System.out.println(names[0][2] + names[1][1]);
程序输出:工具
Mr. Smith Ms. Jones
从以上例子中能够看出,Java多维数组每一行数组的长度不要求相等。spa
4.复制数组code
class ArrayCopyDemo { public static void main(String[] args) { char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e', 'i', 'n', 'a', 't', 'e', 'd' }; char[] copyTo = new char[7]; System.arraycopy(copyFrom, 2, copyTo, 0, 7); System.out.println(new String(copyTo)); } }
程序输出:htm
caffein
5.Arrays工具类对象
Java SE提供了java.util.Arrays
工具类操做数组,经常使用的方法有:
搜索:binarySearch
比较:equals
填充:fill
排序:sort (sort 自定义类时,能够根据业务重写业务对象的sort方法来实现业务排序),Java 8还新添了方法parallelSort来进行数组的并行排序。