當我們在使用 Array 時,
有時會有需求是將 Array 中的物件內容列印出來,
這時我們就需要將 Array 轉換為字串,
雖然我們可以用 for 或 iterator 自己拼出字串,但其實還有更快的方法!
除了把陣列轉換為字串外,從另一方面來看,
我們也會有將 Array String 重新轉換成 Array 的需求。
以下的程式碼以簡單的 int array 為例,
說明用array 的方法:
For primitive types:
int[] myIntArray = new int[3];
int[] myIntArray = {1,2,3};
int[] myIntArray = new int[]{1,2,3};
For classes, for example String
, it’s the same:
String[] myStringArray = new String[3];
String[] myStringArray = {"a","b","c"};
String[] myStringArray = new String[]{"a","b","c"};
Syntax for default values:
int[] num = new int[5];
Or (less preferred)
int num[] = new int[5];
Syntax with values given (variable/field initialization):
int[] num = {1,2,3,4,5};
Or (less preferred)
int num[] = {1, 2, 3, 4, 5};
Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.
Multidimensional array
Declaration
int[][] num = new int[5][2];
Or
int num[][] = new int[5][2];
Or
int[] num[] = new int[5][2];
Initialization
num[0][0]=1;
num[0][1]=2;
num[1][0]=1;
num[1][1]=2;
num[2][0]=1;
num[2][1]=2;
num[3][0]=1;
num[3][1]=2;
num[4][0]=1;
num[4][1]=2;
Or
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
facebook 查詢:
24 hours enquiry facebook channel :
https://www.facebook.com/itteacheritfreelance/?ref=aymt_homepage_panel
Leave a Reply