Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 5 - Arrays CS-140 Dick Steflik.

Similar presentations


Presentation on theme: "Lecture 5 - Arrays CS-140 Dick Steflik."— Presentation transcript:

1 Lecture 5 - Arrays CS-140 Dick Steflik

2 Array An array is an ordered collection of elements
ordering is by position starting at 0 to n-1 (where n is the number of elements) think of an array as a contiguous chunk of memory where the elements are next to one another in memory Elements may be primitives or objects primitives are held right in the array element for objects the array element holds a reference Arrays are often referred to as containers All of the elements of an array must be of the same type if the array represents a basket of apples then it can't contain an orange Once created the number of elements in the array is fixed (cannot increase or decrease).

3 Array reference Since arrays are allocated from dynamic storage similar to the way objects are created the variable name we assign to the array is a reference. ex int[] anArray; // make an array reference // to create the actual array use new anArray = new int[10]; //an array of 10 ints named anArray // these steps can be combined as: int[] anArray = new int[10];

4 Indexing operator the [] operator is called the indexing operator, between the opening[ and closing] you can specify a int, an int expression or a function that returns an int. Ex: int j; // if a is an array then the following are valid a[5]; a[j + 2]; a[ intfn()];

5 bounds if to attempt to index beyond the length of the array an out of bounds exception will occur this usually happens to newbies that aren't paying attention to the values of their loop control variables. some languages and compilers provide bounds checking "forwarned is forarmed" this is also a problem in C and C++

6 length to determine the number of elements in an array use .length
every array has an associated length attribute that can be retrieved using the . operator int[] abc = new int[10]; System.out.println(abc.length)

7 initializers To initialize an array you need to specify an initial value for each element, do this by placing the initial values, separated by commas between a set of braces. int[] myInt = new int[5] = {2,4,6,8,10}; or- int[] myInt = {2,4,6,8,10};

8 class Test { public static void main(String[] args) { int ia[][] = { {1, 2}, null }; for (int[] ea : ia) { for (int e: ea) { System.out.println(e); } } } } will print : 1 2

9 Enhanced for loop For situations where you want to process every element in an array, the enhanced for loop eliminates the tediousness of the regulat for loo (i.e. initializing an indexing variable, specifying a stopping condition and specifying a way to steop to the next index) class EnhancedForLoop { public static void main(String[] args) { int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29};   for (int t: primes) { System.out.println(t); } } } if primes was an array of doubles the for would become: for (double t: primes)

10 Common array algorithms
filling searching for an element finding the largest/smallest finding the average swapping elements inserting/deleting an element copying

11 Linear Search Search an array for a specific value. public int search (int[] values , int valToFind) { int pos = 0; boolean found = false; while (pos< values.length && ! found) { if (values[pos] == valToFind) { found = true; } else { pos++; } } return (pos > values.length )? pos : -1; } int[] myArray = {2,4,6,8,10}; int v = 6; System.out.println( v + "was found at position " + search(myArray, v));

12 Finding the largest int largest (int[] values){ int largest = -1; for (int element : values) if (largest < element) largest = element; return largest;

13 swapping to swap (exchange) elements j and k of an array int temp = values[j]; values[j] = values[k]; values[k] = temp;

14 inserting v at j first make sure that v.length – size => (size is a companion variable that keeps track of how many elements are currently in use) //move elements from j to last one up one position (open up a spot) for (int k = size -1 ; k < j ; k--) values[ k] = values[k-1]; // put the new item in the open position values[j] = v;

15 int[] a = new int[10]; int[] b = new int[20]; //a has ten elements for (int 1 = 0 ; i < 10 ; i++) b[i] = a[i]; a = b; //now a has 20 elements

16 arraycopy java.lang.System.arraycopy()
public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) src – name of array to copy from srcPos – integer position to start the copy from dest – name of array to copy to destPos – integer position to copy to length – integer number of elements to copy can throw out of bounds exception can throw null pointer exception

17 Multi-dimensional Arrays
data for some problems is often visualized in two, three and higher dimensional structures 2-dimensional : graphs, bar charts, tables(rows, columns) 3-dimensional: geometry (length, width, depth), degrees of motion (roll, pitch, yaw)

18 Declaring all elements must be of the same type int[][] table1 = new int[2][3]; //a table with 2 columns and 3 rows int[][] table2 = {{1,2,3},{4,5,6},{7,8,9}};

19 Accessing as any other array, use the indexing operator[] but use one for each dimension abc[2][4] - row 2, col 4 of abc def[2][3][4] - row 2, col 3, layer 4 of def access is implicit; i.e. the reference implies the contents of that location

20 int cnt = 0; for (int i = 0; i < 2 ; i++) for (j=0 ; j < 3 ; j++) table[i][j] = cnt++;

21 Ragged Arrays the array/matrix doesn't have to be square or rectangular, could be triangular or ragged // allocate the base array with 3 rows int[][] tri = new int[3][]; //allocate each row seperately making it one bigger each time for (int i=0 ; i<3 ; i++) { tri[i] = new int[i + 1]; } //this makes it an array of arrays the field of linear algebra frequently uses upper and lower triangular matricies

22 ArrayList Java version of the programming concept called a List
A list is a container object that can shrink and expand as items are added and/or removed from it. Part of a much larger topic called " Java Generics " or the making of generic data structures (read Wikipedia link)

23 Methods ArrayList<type>() = Constructor, makes an empty ArrayList of type 'type' ArrayList<type>(int i) – Constructs sn ArrayList of type 'type' with I empty elements add(etype element) – add an item at the end of the list add(int pos, etype element) – insert an item at position pos of the list remove(int pos) – remove the item at position pos of the list set(int i , etype e) – set the value of item i to e etype get(int i) – retrieve the value of item i boolean contains(etype e) - searches the list for e and returns t/f if it is found int size() – returns the number of elements in the list int indexOf(etype e) – return the position of e in the list clear() – removes all of the elements in the list boolean isEmpty() - returns true if the list is empty

24 ArrayLists hold objects not primitives
java has a set of wrapper classes corresponding to the primitive types (see of text) if you want an ArrayList that holds integers you must use the Integer class ArrayList<Integer> myList = new ArrayList<Integer>(); // creates an empty list wrapper classes are automatically boxed and unboxed ex Integer J = 5; //creates an Integer object and sets its value to int p = j // retrieves the value of object j and assigns it to primitive p array initializers don't work with ArrayLists the indexing operator [] doesn't work either

25 Array or ArrayList<T>
If the size is going to remain constant, use an array If your collection is going to be primitive types, use an array If you are targeting ultimate speed, use an array otherwise use an ArrayList ArrayLists are very versatile at the expense of efficiency. Arrays are very fast at the expense of versatility

26 References


Download ppt "Lecture 5 - Arrays CS-140 Dick Steflik."

Similar presentations


Ads by Google