Java學習筆記3(數組)

來源:互聯網
上載者:User

標籤:中括弧   []   for   9.png   ring   賦值   i++   維數   java學習   

1.數組的定義:

第一種:

public class ArrayDemo{
  public static void main(String[] args){
  //定義數組
  int [] arr = new int[3];
  //數組中的元素預設值為0
  System.out.println(arr[0]);
  System.out.println(arr.length);
  }
}

 

這裡的length是數組的長度

 

第二種定義方法:

public class ArrayDemo{
  public static void main(String[ ] args){
  //定義數組,注意new後邊的中括弧不能寫數字
  int [ ] arr = new int[ ]{1,2,4,3,6,5};
  System.out.println(arr[4]);
  System.out.println(arr.length);
  }
}

第三種(最常用的):

public class ArrayDemo{
  public static void main(String[ ] args){
  int [ ] arr = {1,2,4,3,6,5};
  System.out.println(arr[4]);
  System.out.println(arr.length);
  }
}

 

兩種的結果相同,如下:

 

 

 

2.數組的賦值:

arr[1] = 3

3.遍曆

public class ArrayDemo{
  public static void main(String[] args){
    int [] arr = {2,1,3,5,7,0,4};
    for(int i = 0 ; i < arr.length; i++){
    System.out.println(arr[i]);
    }
  }
}

結果:

 

4.擷取最大值(最小值原理相同):

public class ArrayDemo{
  public static void main(String[] args){
    int [] arr = {5,-1,2,-4,6,0,8,3};
    int max = arr[0];
    for(int i = 1 ; i < arr.length; i++){
      if( max < arr[i]){
        max = arr[i];
      }
    }
    System.out.println(max);
  }
}

 

 

5.二維數組:

定義:

int  [][] arr = new int [3][4];

int [][] arr = {{1,2},{3,4,5},{6,7,8,9}};

記憶體方法:在堆中存三個一維數組,每個一維數組有四個位置,三個一維數組的首地址存入一個新的數組,這個新數組也有首地址,棧中的arr指向這個地址

二維數組訪問和一維數組類似

遍曆:

public class ArrayDemo{
  public static void main(String[] args){
    int [][] arr = {{1,2,3},{4,5},{6,7,8,9},{0}};
    for(int i = 0 ; i < arr.length; i++){
      for(int j = 0 ; j<arr[i].length; j++){
        System.out.print(arr[i][j]);
      }
      System.out.println();
    }
  }
}

 

Java學習筆記3(數組)

聯繫我們

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