Language Fundamentals - Arrays

copy from http://www.janeg.ca/scjp/lang/arrays.html

 

Array declarations

  • arrays are Java objects
  • all Java arrays are technically one-dimensional. Two-dimensional arrays are arrays of arrays.
  • declaring an array does not create an array object or allocate space in memory; it creates a variable with a reference to an array
  • array variable declarations must indicate a dimension by using []
    Examples of valid array declarations: (JJ pg84)
    
    
        String[]s;
        String []s;
        String [] s;
        String [ ] s;       // extra white space ignored
        String[] s;
        String[   ] s;      // extra white space ignored
        String s[];
        String s [];
        String s [   ];     // extra white space ignored
            
        String[] s[];
        String[][]s;
        String s [] [  ];   // extra white space ignored
    
  • declaring the size of the array with the following notation is illegal
        String[5] s;        // illegal declaration
    
    
    
  • the standard convention for declaring arrays is:
        String[] s;         // one-dimensional array
        String[][] s;       // two-dimensional array
    

Initializing arrays

  • all arrays are zero-based
  • arrays must be indexed by int values or byte, short or char values (as these can be promoted to int) (JLS §10.4)
  • using a long index value to access an array causes a compile error
  • attempting to access an array with an index less than 0 or greater than the length of the array causes an ArrayIndexOutOfBoundsException to be thrown at runtime (JLS §10.4)
  • since arrays are Objects they can be initialized using the new operator
  • when created, arrays are automatically initialized with the default value of their type
    String[] s = new String[100];   // default values: null
    boolean[] b = new boolean[4];   // default values: false
    int[] i = new int[10][10];      // default values: 0
    
  • array references declared as members are initialized to null BUT array references declared in methods are not initialized
class TestArray  {
    int[] arr;          // member declaration, initialized to 'null'

    public static void main(String[] args) {
        int[] arr1;     // reference variable 'arr1' not initialized
        
        // compiles ok
        System.out.println("arr:" + new TestArray().arr); 
        // compile error

        System.out.println("arr1: " + arr1);
    }
}
  • as arrays are allocated at runtime, you can use a variable to set their dimension
        int arrSize = 100;
        String[] myArray = new String[arrSize];
    
  • you can use curly braces {} as part of an array declaration to initialize the array
        String[] oneDimArray = { "abc","def","xyz" };
    

 

Note
  • Curly braces {} can only be used in array declaration statements.
    String[] s;
    // illegal initialization


    s = { "abc", "def", "hij");     
    
    int[] arr = new int[] {1,2,3};  // legal
  • you can assign an array a null value but you can't create an empty array by using a blank index
      
        int[] array = null;             // legal
        // illegal initialization
    
    
        int[] array = new int[];        
    

Initializing two-dimensional arrays

  • the first dimension represents the rows, the second dimension, the columns
  • curly braces {} may also be used to initialize two dimensional arrays. Again they are only valid in array declaration statements.
        int[][] twoDimArray = { {1,2,3}, {4,5,6}, {7,8,9} };
    
  • you can initialize the row dimension without initializing the columns but not vice versa
        int[][] myArray = new int[5][];
        // illegal
    
        int[][] myArray = new int[][5];
     
    
  • the length of the columns can vary
     class TestTwoDimArrays {
        // initialize # of rows
        static int [][] myArray = new int[3][]; 
    
        public static void main(String[] args) {
    
        myArray[0] = new int[3];   // initialize # of cols
        myArray[1] = new int[4];   // in each row
        myArray[2] = new int[5];
    
        for(int i=0; i<3; i++)    // fill and print the array
            fillArray(i, i+3);
    
        System.out.println();
        } // end main()
    
        private static void fillArray(int row, int col) {
    
            for( int i=0; i<col; i++)
                myArray[row][i] = i;
    
            for( int i=0; i<col; i++)
                System.out.print(myArray[row][i]);
    
            System.out.println();
        }
    
    }
    
    Output of TestTwoDimArrays:
    
        012
        0123
        01234    
    
        
    

Tips

  • array index operator [] has highest level of precedence
  • integer variables can be used as array dimension values

Traps

  • incorrect array declaration statements, particularly:
       arrayType [#] varName;
  • incorrect array initialization statements, particularly:
      arrayType[] varName = new arrayType[2];
      varName = { value, value, value };
  • negative values for array index
  • long value for array index
  • array declaration used as an array creation statement
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值