Java學習:數組

來源:互聯網
上載者:User

標籤:大小   under   new   stp   拷貝   public   改變   each   ati   

1、定義數組

定義一維數組

int array1[ ];
int [ ] array2,array3;

符號“[]”說明聲明的是一個數組對象。這兩種聲明方式沒有區別,但是第二種可以同時聲明多個數組

// 建立大小為10個整型的數組int[] array = new int[10];// 建立大小為5個整型的數組並初始化int[] array = {1, 2, 3, 4, 5};

 

2、length執行個體變數

int[] arr = new int[10];

arr.length 表示數組長度

 

3、一維數組複製

// 從 src 數組 srcPos 位置開始拷貝 length 長度到 dest 數組 destPos 開始的位置

// 參數1:原數組

// 參數2:複製原數組的起始位置

// 參數3:目標數組

// 參數4:目標數組存放的起始位置

// 參數5:複製的長度

System.arraycopy(src, srcPos, dest, destPos, length);

int[] arr1 = new int[5];int[] arr2 = new int[5];// 該語句會把 arr1 也指向 arr2 數組,改變 arr2 數組的值,arr1 數組的值也會改變//arr1 = arr2;// 該語句會把 arr2 數組中的值複製到 arr1 數組中,改變 arr2 中的值,不會影響 arr1 數組//System.arraycopy(arr2, 0, arr1, 0, arr2.length);

 

4、二維數組

int[][] two = new int[5][6];

two.length表示數組的行數,two[i].length表示數組的列數。

 

5、不規則數組

int[][] two = new int[4][];            // 數組有4行

two[0] = new int[1];  // 第1行有1列

two[0] = new int[2];      // 第1行有2列

two[0] = new int[3];      // 第1行有3列

two[0] = new int[3];      // 第1行有4列

 

6、for-each迴圈:用來遍曆數組

// for-each 訪問一維數組public class Array {    public static void main(String[] args) {        int sum = 0;        int[] arr = {1, 2, 3, 4, 5};        for (int i : arr) {            sum += i;        }        System.out.println(sum);    }}

結果:15

// for-each 訪問二維數組public class Array {    public static void main(String[] args) {        int sum = 0;        int[][] arr = {{1, 2},{3, 4}};        for (int i[] : arr) {            for (int j : i) {                sum += j;            }        }        System.out.println(sum);    }}

結果:10

Java學習:數組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.