CoreJavaE10V1P3.10 第3章 Java的基本編程結構-3.10 數組(Arrays)

來源:互聯網
上載者:User

標籤:system   賦值   span   color   code   快速   something   不同   令行   

數組是儲存同一類型資料的資料結構

數組的聲明與初始化

int[] a; int a[];int[] a = new int[100];
int[] a = new int[100];for (int i = 0; i < 100; i++)    a[i] = i; // fills the array with numbers 0 to 99

一旦建立就不可改變其大小

3.10.1 for each 迴圈

for each迴圈可以用來為數組賦值

for (variable : collection) statement
int[] a = new int[100] ;
for
(int element : a)System.out.println(element);

對數組a的每個 element 輸出。

  如果想直接輸出數組,可以使用Arrays(java.util.Arrays )類的toString方法。

System.out.println(Arrays.toString(a));

3.10.2 數組初始化與匿名數組

int[] smallPrimes = { 2, 3, 5, 7, 11, 13 };匿名數組初始化:new int[] { 17, 19, 23, 29, 31, 37 }smallPrimes = new int[] { 17, 19, 23, 29, 31, 37 };是int[] anonymous = { 17, 19, 23, 29, 31, 37 };smallPrimes = anonymous;的簡寫

3.10.3 複製數組

int[] copiedLuckyNumbers = Arrays.copyOf(luckyNumbers, luckyNumbers.length);

如果長度超出,賦值為0.

3.10.4  命令列參數

如果執行程式時使用命令 java Message -g cruel world

那麼在main函數中即可接受

args[0]: "-g"args[1]: "cruel"args[2]: "world"
public class Message{  public static void main(String[] args)  {    if (args.length == 0 || args[0].equals("-h"))    System.out.print("Hello,");    else if (args[0].equals("-g"))    System.out.print("Goodbye,");    // print the other command-line arguments    for (int i = 1; i < args.length; i++)    System.out.print(" " + args[i]);    System.out.println("!");  }}

3.10.5 數組排序

int[] a = new int[10000];. . .Arrays.sort(a)

3.10.6 多維陣列

double[][] balances;
int[][] magicSquare ={    {16, 3, 2, 13},    {5, 10, 11, 8},    {9, 6, 7, 12},    {4, 15, 14, 1}};
for (double[] row : a)    for (double value : row)        do something with value    
System.out.println(Arrays.deepToString(a));快速輸出2多維陣列

 

3.10.7  不規則數組(Ragged Arrays)

Java中其實沒有嚴格意義的多維陣列,他是用數組儲存的數組,每個一維數組的元素個數可以不同,類型也可不同。

 

CoreJavaE10V1P3.10 第3章 Java的基本編程結構-3.10 數組(Arrays)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.