Learn Java - Chapter 1 變數(Variables)-數組(Arrays)

來源:互聯網
上載者:User

標籤:

Java數組在被建立的時候確定數組長度。索引下標從0開始。

1.數組定義及初始化

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]);//使用

程式輸出:

Element at index 0: 100Element at index 1: 200

2.定義初始化同時賦值

int[] anArray = {     100, 200, 300,    400, 500, 600,     700, 800, 900, 1000};

3.多維陣列

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. SmithMs. Jones

從以上例子中可以看出,Java多維陣列每一行數組的長度不要求相等。

4.複製數組

    

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));    }}

程式輸出:

caffein


Learn Java - Chapter 1 變數(Variables)-數組(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.