Difference between revisions of "Arrays"

From Suhrid.net Wiki
Jump to navigationJump to search
Line 22: Line 22:
 
* Only the size of the array needs to be specified - in this case 5 says that matrix 2-D array can store 5 1-D array objects. So only the 5 is sufficient to be specified.
 
* Only the size of the array needs to be specified - in this case 5 says that matrix 2-D array can store 5 1-D array objects. So only the 5 is sufficient to be specified.
 
* Of course we can also specify both dimensions like int[][] matrix = new int[3][2]; Which menas that matrix can store 3 1-D arrays each of length 2.
 
* Of course we can also specify both dimensions like int[][] matrix = new int[3][2]; Which menas that matrix can store 3 1-D arrays each of length 2.
 +
 +
== Initializing ==
 +
 +
*

Revision as of 09:40, 28 June 2011

Introduction

  • Arrays store multiple variables of the same type.
  • The array itself is always an object on the heap (even if it is storing primitive elements).
  • Arrays can be multi-dimensional.
  • Think of a multi-dimensional array as an array of arrays.

Declaring

  • int[] scores; (Preferred) or int scores[]; (Legal, but bad)
  • String[] names;
  • int[][] matrix;

Constructing

  • int[] scores = new int[10];
  • This will create a new array object on the heap. All the int values will be assigned their default values, Object references will be assigned null.
  • The array size must be present, when there is no initializer.
  • double[] rates = new double[]; //illegal
  • Thread[] pool = new Thread[10]; //No thread objects are created here, only the array object to hold ten thread references is created.
  • int[][] matrix = new int[5][];
  • Only the size of the array needs to be specified - in this case 5 says that matrix 2-D array can store 5 1-D array objects. So only the 5 is sufficient to be specified.
  • Of course we can also specify both dimensions like int[][] matrix = new int[3][2]; Which menas that matrix can store 3 1-D arrays each of length 2.

Initializing