210 likes | 239 Views
Arrays. Arrays in Java. Arrays in Java are objects. Like all objects are created with the new keyword. Declaring Arrays. Like all other variables in Java, an array must have a specific type like byte, int, String or double.
E N D
Arrays in Java • Arrays in Java are objects. • Like all objects are created with the new keyword
Declaring Arrays • Like all other variables in Java, an array must have a specific type like byte, int, String or double. • Only variables of the appropriate type can be stored in an array. One array cannot store both ints and Strings, for instance. • Like all other variables in Java an array must be declared.
Here are some examples: int[] k; float[] y; String[] names; You also have the option to append the brackets to the variable instead of the type. int k[]; float y[]; However, unlike in C, you cannot include the length of the array in the declaration. The following is a syntax error: int k[3]; float yt[7]; String names[100];
Creating an Array • Arrays are Objects so the new keyword is used • When you instantiate an array you must tell it what size. • Names = new String[100] • K = new int[6]
Referencing Arrays • Individual components of an array are referenced by the array name and by an integer which represents their position in the array. The numbers you use to identify them are called subscripts or indexes into the array. • names[35] k[3]
Initializing Arrays • For example this is how you'd store values in the arrays above: k[0] = 2; k[1] = 5; k[2] = -2; yt[17] = 7.5f; names[4] = "Fred";
String[] names = {“Fred”, “Alice” , ”Paul”} • For even medium sized arrays, it's unwieldy to specify each component individually. It is often helpful to use for loops to initialize the array. Here is a loop which fills an array with the squares of the numbers from 0 to 100. float[] squares; squares = new float[101]; for (int i=0; i <= 100; i++) { squares[i] = i*i;
ArrayIndexOutOfBoundsException. While we won’t deal with exceptions for a while. You do need to understand this exception. If you attempt to access an index past the size of an array. You will throw this exception.
Multi-Dimensional Arrays • Two dimensional arrays are declared, allocated and initialized much like one dimensional arrays. However you have to specify two dimensions rather than one, and you typically use two nested for loops to fill the array.
This example fills a two-dimensional array with the sum of the row and column indexes class FillArray { public static void main (String args[]) { int[][] matrix; matrix = new int[4][5]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { matrix[row][col] = row+col; } }
Even Higher Dimensions • You don't have to stop with two dimensional arrays. Java permits arrays of three, four or more dimensions. However chances are pretty good that if you need more than three dimensions in an array, you're probably using the wrong data structure. Even three dimensional arrays are exceptionally rare outside of scientific and engineering applications.
The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays.
class Fill3DArray { public static void main (String args[]) { int[][][] M; M = new int[4][5][3]; for (int row=0; row < 4; row++) { for (int col=0; col < 5; col++) { for (int ver=0; ver < 3; ver++) { M[row][col][ver] = row+col+ver; } } } }
Unbalanced Arrays • Java does not have true multidimensional arrays. Java fakes multidimensional arrays using arrays of arrays. This means that it is possible to have unbalanced arrays. An unbalanced array is a multidimensional array where the dimension isn't the same for all rows. In most applications this is a horrible idea and should be avoided.
Array methods • arraycopy(Object src, int srcPos, Object dest, int destPos, int length) Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array. • src - the source array. • srcPos - starting position in the source array. • dest - the destination array. • destPos - starting position in the destination data. • length - the number of array elements to be copied.
public class DoubleArray { public static void main (String args ]) { int array1[] = {1, 2, 3, 4, 5}; int array2[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; System.out.println("Original size: " + array1.length); System.out.println("New size: " + doubleArray(array1).length); System.out.println("Original size: " + array2.length); System.out.println("New size: " + doubleArray(array2).length); } static int[] doubleArray(int original[]) { int length = original.length; int newArray[] = new int[length*2]; System.arraycopy(original, 0, newArray, 0, length); return newArray; } }
getLength() • public static int getLength(Object array) throws IllegalArgumentException • Returns the length of the specified array object, as an int. • Parameters: • array - the array • Returns: • the length of the array • Throws: • IllegalArgumentException - if the object argument is not an array
get • public static Objectget(Object array, int index) throws IllegalArgumentException, ArrayIndexOutOfBoundsException • Returns the value of the indexed component in the specified array object. The value is automatically wrapped in an object if it has a primitive type. • Parameters: • array - the array • index - the index • Returns: • the (possibly wrapped) value of the indexed component in the specified array • getInt(), getBoolean, getLong(),getDouble()
set • public static void set(Object array, int index, Object value) throws IllegalArgumentException, ArrayIndexOutOfBoundsException • Sets the value of the indexed component of the specified array object to the specified new value. The new value is first automatically unwrapped if the array has a primitive component type. • Parameters: • array - the array • index - the index into the array • value - the new value of the indexed component • setInt(), setBoolean(), setFloat(),setLong()
Sort - Search • The Arrays class provides many other methods useable with arrays. • Arrays.sort() • Arrays. binarySearch() • Import java.util.*; to use these • To search an array must be sorted.