arrays. arrays in java arrays in java are objects. like all objects are created with the new...

21
Arrays

Upload: junior-osborne

Post on 16-Jan-2016

266 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

Arrays

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

Arrays in Java

Arrays in Java are objects. Like all objects are created with the

new keyword

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

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.

Page 4: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 5: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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]

Page 6: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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]

Page 7: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 8: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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;

Page 9: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.

Page 10: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.

Page 11: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 12: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.

Page 13: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 14: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 15: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.

Page 16: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.

Page 17: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

}

Page 18: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 19: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

get

public static Object get(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()

Page 20: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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

Page 21: Arrays. Arrays in Java  Arrays in Java are objects.  Like all objects are created with the new keyword

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.