Collections: Arrays

 

Python

Java

 

The array module includes resources for creating and using sequences of basic types such as numbers.  An array is essentially a more efficient version of a list.

 

 

An array is a sequence of elements of the same type.  Each element is accessed in constant time using an index position.  Unlike a list, an arrayÕs length is fixed when it is created and cannot be changed.  Moreover, the only operations on an array are access or replacement of elements via subscripts.

 

Like other data structures, arrays are objects and thus are of a reference type.  The type of an array is determined by its element type, which is specified when the array is instantiated.

 

Examples:

 

int[] ages = new int[10];

String[] names = new String[10];

 

The variables ages and names now refer to arrays capable of holding 10 integers and 10 strings, respectively.  Each array element in ages has a default value of 0.  Each array element in names has a default value of null (as does a new array whose elements are of any reference type).

 

The length of an array can be obtained from the array objectÕs length variable, as follows:

 

System.out.println(names.length);

 

The elements in the names array can be reset with a for loop, using the subscript and the length variable, as follows:

 

java.util.Scanner input = new java.util.Scanner(System.in);

for (int i = 0; i < names.length; i++)

    names[i] = reader.nextLine("Enter a name: ");

 

The enhanced for loop can be used just to reference the elements in an array:

 

for (String name: names)

    System.out.println(name);

 

 

Previous

Index

Next