我们来使用java的数组的例子,来学习一下java的数组使用。
例子1 数字数组
int[] stu = new int[2]
例子2 字符串数组
String[] str = new String[3]; //3 表示数组长度
例子3 二纬数组
String[][] tarr = new String[2][2];
建立文件JavaArray.java
/**
java-er.com
learn java is so easy
*/
import java.util.*;
public class JavaArray
{
public static void main(String[] args){
String[] arr = new String[3]; //initialize the array
arr[0] = "a";
arr[1] = "b";
arr[2] = "c";
for(int i = 0 ; i < arr.length;i++){
System.out.println("arr["+i+"] " + arr[i]);
}
// another way to initialize the array and assign the value to the array
System.out.println("--------------------------");
String[] arr2 = new String[]{"a1","a3","a2"};
for(int i = 0 ; i < arr2.length;i++){
System.out.println("arr2["+i+"] " + arr2[i]);
}
System.out.println("--------------------------");
Arrays.sort(arr2);// sort the array,you must import java.util.*
for(int i = 0 ; i < arr2.length;i++){
System.out.println("arr2["+i+"] " + arr2[i]);
}
//two-dimensional array
System.out.println("--------------------------");
String[][] tarr = new String[2][2];
tarr[0][0] = "x1";
tarr[0][1] = "x2";
tarr[1][0] = "x3";
tarr[1][1] = "x4";
for(int i = 0 ; i < tarr.length;i++){
for (int j = 0 ; j < tarr[i].length ; j ++ ){
System.out.println(tarr[i][j]);
}
}
}
}
编译
javac JavaArray.java
执行
java JavaArray
输出
arr[0] a
arr[1] b
arr[2] c
--------------------------
arr2[0] a1
arr2[1] a3
arr2[2] a2
--------------------------
arr2[0] a1
arr2[1] a2
arr2[2] a3
--------------------------
x1
x2
x3
x4