Language Basics: Variables: Arrays Flashcards
What is an array?
A container object that holds a fixed number of values of a single type.
What is the length of an array?
The length of an array is established when the array is created. After creation, its length is fixed.
What is an element and index in an array?
Each item in an array is called an element, and each element is accessed by its numerical index.
How do you declare an array?
int[] anArray;
an array declaration has two components: the array’s type and the array’s name. An array’s type is written as type[], where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array.
How do you initialise an array?
anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialized.
How do you initialise an array?
anArray = new int[10];
If this statement is missing, then the compiler prints an error like the following, and compilation fails:
ArrayDemo.java:4: Variable anArray may not have been initialised.
What is a multidimensional array
A multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length
How do you find length of an array?
use the built-in length property to determine the size of any array.
System.out.println(anArray.length);
How do you copy an array?
The System class has an arraycopy method that you can use to efficiently copy data from one array into another:
public static void arraycopy(Object src, int srcPos,
Object dest, int destPos, int length)
The two Object arguments specify the array to copy from and the array to copy to. The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.
What useful methods does the java.util.Arrays class have?
- Searching an array for a specific value to get the index at which it is placed (the binarySearch method).
- Comparing two arrays to determine if they are equal or not (the equals method).
- Filling an array to place a specific value at each index (the fill method).
- Sorting an array into ascending order. This can be done either sequentially, using the sort method, or concurrently, using the parallelSort method introduced in Java SE 8. Parallel sorting of large arrays on multiprocessor systems is faster than sequential array sorting.