天天看點

Java中數組的使用方法? 初始化,二維數組,數組複制

1.靜态初始化:程式員指定初始值,系統決定長度。注意數組要使用new關鍵字。

class ArrTest 
{
	public static void main(String[] args) 
	{
	
		int[] arr;
		arr = new int[]{1,2,3};
		//int[] arr = new int[]{1,2,3};
                //int[] arr = {1,2,3};
	}
}
           

2.動态初始化:程式員指定長度,系統配置設定初始值

這樣定義是不行的:int[3] arr = new int[3];

class ArrTest 
{
	public static void main(String[] args) 
	{
	
		int[] arr = new int[3];
	}
}
           

3.複制數組

輸出: 1  1 

如果直接使用arr2 = arr,則arr[0]随arr2[0]變化,輸出為1   5

import java.util.Arrays;
class ArrTest 
{
	public static void main(String[] args) 
	{
		int[] arr = {1,2,3};
		int[] arr2 = Arrays.copyOf(arr,arr.length);
		System.out.println(arr2[0]);
		arr[0] = 5;
		System.out.println(arr2[0]);
		
	}
}
           
上一篇: 數組複制