1 / 21

Arrays

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.

Download Presentation

Arrays

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Arrays

  2. Arrays in Java • Arrays in Java are objects. • Like all objects are created with the new keyword

  3. 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.

  4. 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];

  5. 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]

  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]

  7. 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";

  8. 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;

  9. 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.

  10. 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.

  11. 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; } }

  12. 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.

  13. The syntax for three dimensional arrays is a direct extension of that for two-dimensional arrays.

  14. 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; } } } }

  15. 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.

  16. 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.

  17. 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; } }

  18. 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

  19. 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()

  20. 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()

  21. 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.

More Related