Presentation is loading. Please wait.

Presentation is loading. Please wait.

Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.

Similar presentations


Presentation on theme: "Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For."— Presentation transcript:

1 Arrays and ArrayLists Topic 6

2 One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For an array of size n, valid indexed elements in an array range from 0 to n – 1 Individual elements are referenced using their index (subscript) If an invalid index is referenced, an ArrayIndexOutOfBoundsException is thrown

3 One Dimensional Arrays General Syntax – Declarations: dataType[] variableName; dataType variableName[]; dataType[] varName1, varName2; – Initializations: variableName = new dataType[size]; variableName = {elmt1, elmt2, elmt3, elmt4, …}; – Declaration/Initializations: dataType[] varName = new dataType[size]; dataType varName[] = new dataType[size]; dataType[] varName1 = new dataType[size1], varName2 = new dataType[size2]; dataType can be ANY data type, primitive or reference – There are some implications of creating an array of reference data type – Be careful of NullPointerExceptions! Initializing elements (see above) – variableName[0] = value0; variableName[1] = value1; etc

4 One Dimensional Arrays Length – A Java array has a final public instance variable (constant) called length Note this is a field, not a method For declaration: int[] ar = new int[5]; ar.length is an int with the value of 5 – Often used as a bound – i.e.: while(x < ar.length) for(int i = 0; i < ar.length; i++) Here an off by one error could cause an ArrayIndexOutOfBoundsException

5 One Dimensional Arrays Traversing an array – for loop most often used – for each loop (also called enhanced for loop) for(dataType dummyVar : iterator) – dataType must match the list you are iterating through – dummyVar continually references each element in the list linearly – Iterator is the list you want to iterate through; can be any type of list (array, ArrayList, etc) for each loop caveat – can’t replace or remove elements – Note a for each loop can change array elements if they are reference variables being accessed through methods (example: for an array of BankAccount variables, withdrawal $50 from each account) – Exercise 1: count the number of even numbers that exist in an array of type int – Exercise 2: change even indexed elements in an int array to the value of 0

6 Arrays as Parameters Passing an array as a parameter means passing its object reference (no copy is made) – Thus the elements of the actual array can be accessed and modified Example 1 – array elements accessed but not modified – public static int findMin(int[] arr) Example 2 – array elements modified – public static void squareContents(int[] arr) Example 3 – public static void swap(int[] arr, int i, int j) Example 4 – public int[] getIntegers()

7 KENO Array Project (Keno).doc

8 Arrays and Classes Arrays as class variables – Deck.java Data: – private int[] myDeck; – public static final int NUMCARDS = 52; Methods – Deck() – public void writeDeck() – private void swap(int[] arr, int i, int j) – public void shuffle() Array of class objects – ManyDecks.java Data: – private Deck[] allDecks; – public static final int NUMDECKS = 500; Methods – ManyDecks() – public void shuffleAll() – public void printDecks()

9 Two Dimensional Arrays Declarations – int [][] table;//table currently a null reference – double [][] matrix = new double[3][4]; //3x4 array of real numbers, each element is 0.0 – String [][] strs = new String[2][5]; //2x5 array of String objects, each element is null – int [][] mat = {{3, 4, 5}, {6, 7, 8}};//2x3 array Processing a 2-D array – nested for loops

10 Two Dimensional Arrays For declaration: int [][] mat = new int[3][4]; – mat[r][c] represents element at row r, column c Valid values for r are 0 – 2 Valid values for c are 0 – 3 – Rows are numbered from 0 – mat.length - 1 – Columns are numbered from 0 – mat[r].length – 1 – To use a for each loop: for(int[] row : mat) for(int element : row) //executable statement

11 Two Dimensional Arrays Example 1: Find the sum of all elements in a matrix (2- d array) mat Example 2: Write a method that returns an array which holds the values of the sum of each row of a matrix Example 3: Write a method that returns an array which holds the values of the sum of each column in a matrix Example 4: Add 10 to each element in row 2 of a matrix mat Example 5: Write a method that returns a double which is equal to the sum of the major left to right diagonal of a matrix

12 ArrayLists In util package Can grow and shrink as needed size() can access the number of elements currently in the ArrayList Indexes range from 0 to arrayList.size() – 1 Insertion or deletion of elements can be done with a single statement Is in Collections API – prepackaged data structures – implementation of these container classes should not concern the programmer No primitive types in Collections classes – must contain objects – Remember auto-boxing and unboxing

13 ArrayLists Methods to know – boolean add(E obj) – int size() – E get(int index) – E set(int index, E element) – void add(int index, E element) – E remove(int index)

14 ArrayList Example Example 1: practice ArrayList methods Example 2: print the elements in an ArrayList, one per line Example 3: write a method with the following pre and post conditions and header: – Precondition: ArrayList list contains Integer values sorted in increasing order – Postcondition: value inserted in its correct position in list – public static void insert(ArrayList list, Integer value) Example 4: write a method that returns an ArrayList (of user entered size) of random integers from -50 to 50 Example 5: write a method that swaps two values in list, indexed at I and j Example 6: write a method that prints all negatives in list a (assume that list contains Integer values) Example 7: write a method that changes every even-indexed element of strList to the empty String (assume that strList contains String values)


Download ppt "Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For."

Similar presentations


Ads by Google