Difference between revisions of "Arrays"

From Suhrid.net Wiki
Jump to navigationJump to search
 
Line 95: Line 95:
 
== Assignments ==
 
== Assignments ==
  
* For primitive array types, once the array is declared it cannot point to a different array type. Cannot assign an int[] to a long[] !
+
* For primitive array types, once the array is declared it cannot point to a different array type. '''Cannot assign an int[] to a long[] !'''
 
* However, Object of any subclass of the declared array type can be put into the array.
 
* However, Object of any subclass of the declared array type can be put into the array.
 
* It also works for the whole array itself. a subtype array can be assigned to a super-type array.
 
* It also works for the whole array itself. a subtype array can be assigned to a super-type array.

Latest revision as of 03:37, 7 September 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.
  • Zero size arrays are legal
int[] row = new int[0]; //OK

//OR

int[] row = {}; //OK

//row.length will be zero

Initializing

  • Initializing means assigning values to the elements of the array.
  • Initializing can be done after the array is declared and constructed.
  • Initializing can be combined along with the array declaration and construction. If array's are initialized with constants, then this can be done ONLY at the time of array declaration.
  • IMP: Array elements are ALWAYS given their default values when the array is constructed. e.g. int will be 0, boolean false, Objects null etc. This holds true irrespective of where the array is declared.
String[] names; //Declare
names = new String[3]; //Construct
//Initialize
names[0] = "A";
names[1] = "B";
names[2] = "C";

//All in one
String[] names = new String[] {"A", "B", "C"}; //This will automatically construct a size-3 String array and assign the elements.
String[] names = {"A", "B", "C"}; //Concise form.

//Multi-dimensional - initing a 3x3 int array
int[][] matrix = { {1,2,3}, {4,5,6}, {7,8,9} };
Illegal Legal
int[5] scores; //No size in LHS.
int[] scores = new int[]; //No size specified;
int[3] scores = new int[3] {1, 2, 3}; //Cant specify both size and initializer

int[] scores;
scores = {1,2,3}; //Intializer being used, without array being constructed.
int[] scores;
scores = new int[] {1,2,3}; //OK

int[] scores = {1, 2, 3 }; //OK - concise.

int[] scores = new int[] {1, 2 , 3}; /OK

Assignments

  • For primitive array types, once the array is declared it cannot point to a different array type. Cannot assign an int[] to a long[] !
  • However, Object of any subclass of the declared array type can be put into the array.
  • It also works for the whole array itself. a subtype array can be assigned to a super-type array.
  • Works for interfaces too.
  • Cannot assign arrays of different dimensions to each other !
class Animal {
}

class Dog extends Animal {
}

class Cat extends Animal {
}

public class ArrayTest2 {

	public static void main(String[] args) {
		

		Dog[] dogs = new Dog[3];
		Cat[] cats = {new Cat()};
		Animal[] animals = {new Animal(), new Dog(), new Cat()};		
		
		animals = dogs;
		animals = cats;
		
	}
}

Usage

  • Accessing an array with out of bounds index values will only throw a run-time exception. NOT compile-time.

Multidimensional Arrays

  • Multi-dimensional arrays can be thought of as arrays of arrays.
  • For e.g. a 2-D array is an array which contains arrays as elements.
  • For e.g. a 3-D array is an array which contains 2-D arrays as elements and so on..
  • Chaining the array indices allow us to access the elements of arrays within arrays, see below:
int[][] matrix = new int[3][];

//accessing the first element of the first array or "row"
int[] array1 = matrix[0] ;
int firsteleofarray1 = array1[0];
//Or simply:
int first = matrix[0][0];
  • 3-D Array:
public class MultiArrayTest {
	
	public static void main(String[] args) {
	
	int[][][] matrix = new int[3][][];
	
	int[][] twod1 = { {1,2,3},
			  {4,5,6},
			  {7,8,9}
			};
	
	int[][] twod2 = { {10,11,12},
	                  {13,14,15},
	                  {16,17,18}
			};
	
	int[][] twod3 = { {19,20,21},
	                  {22,23,24},
	                  {25,26,27}
			};
	
	matrix[0] = twod1;
	matrix[1] = twod2;
	matrix[2] = twod3;
	
	for(int[][] a : matrix) {
		for(int[] b : a) {
			for(int c : b) {
				System.out.print(c + " ");
			}
			System.out.println();
		}
	}
	
	System.out.println("2 + 4 = " + matrix[0][1][2]);
	System.out.println("3 cube = " + matrix[2][2][2]);

	}
}


  • Arrays in a multi-dimensional array need not be of the same length.
  • For e.g.
int[][] matrix = new int[3][];

matrix[0] = {1,2,3,4};
matrix[1] = {5,6};