Hip Hip Array! AP Computer Science
Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays allow you to store several variables of the same type in one place index Elements [0] = 3 [1] = 7 [2] = 9 [3] = 2 [4] = 1 [5] = 5 The index starts at 0 The first item is at index 0 The last item is at index (length – 1) Length = 6 Index = 6-1=5 6 elements Index from 0 to 5 Array symbol [ ]
what type of data can arrays hold? String [ ] name = new String [ 3]; or String [ ] name = {“Billy”, “Sally”, “Bob”}; boolean [ ] done = new boolean [3]; or boolean [ ] done = {true, false, true}; int [ ] num = new int [5]; int [ ] num = {5, 2, 4, 6, 8}; double [ ] nums = new double [ 5 ]; or double [ ] nums = {2.5, 3.5, 4.5, 5.5, 6.5}; primitives or objects
What are limitations of arrays? Fixed in size each cell must hold the same type
How to declare an array String [] name; // just declare String [ ] name = new String [ 3]; // initialize to 3 elements name[0] = “Billy”; // use brute force to assign data name[1] = “Sally”; name[2] = “Bob”; Assign the elements when you create the array String [ ] name = {“Billy”, “Sally ”, “Bob”);
Arrays are never empty? Array names are a reference to memory address When you use the word new a memory address is created. double [] salesFigure; no memory address null salesFigure = new double [20]; reserves 20 memory locations for 20 doubles Each element in the array is assigned 0 by default. int arrays are filled with ________________ double arrays are filled with ____________ boolean arrays are filled with ___________ object arrays are filled with _____________ (Strings are filled with this) false null
print array You can print individual elements at specific index locations. array[0] if you print the name of the array you get the memory location. System.out.println(array); memorylocation you must loop over the elements and print each one as you go. int [] nums = new int[10]; for(int i = 0; i < nums.length; i = i+2) nums[i] = i; System.out.println(nums[i]); This will fill each index with a value i+2 and print the array Array will print: 0, 2, 4, 6, 8 i print < 10 i = 0 0 yes i = yes i = yes i = yes i = yes i = stop no
Reassigning elements in an array int[] array = {7,8,10,11,4,3}; array[array[0]/2]=15; array[array[4]+1]=9; array[array.length/2-1]=5; array[1]=array[0]+4; index 3 = 15 index 5 = 9 index 2 = 5 index 1 to be index 4 New Array:
Finding how many of a value public boolean findValue(int [] nums, int value) { int count = 0; for(int i = 0; i < nums.length; i++) { if(nums[i] == 4) count++ } return count; }
Given an int array length 2, return true if it does not contain a 2 or 3. no23({4, 5}) → true no23({4, 2}) → false no23({3, 5}) → false public boolean no23(int[] nums) { int match = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] == 2 || nums[i] == 3) match++; } if(match > 0) return false; else return true; } }
double 23 Given an int array, return true if the array contains 2 twice, or 3 twice. The array will be length 0, 1, or 2. double23({2, 2}) → true double23({3, 3}) → true double23({2, 3}) → false problem solve: We want it to count the number of 2s or 3s in the array. public boolean double23(int[] nums) { int match2 = 0; int match3 = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] == 2){ match2++;} if(nums[i] == 3){ match3++; } } if(match2 ==2 || match3 ==2) return true; else return false; }
Java Subset class java.lang.Math – static int abs(int x) – static double abs(double x) – static double pow(double base, double exponent) – static double sqrt(double x) – static double random() // returns a double in the range [0.0, 1.0)
Produce random using Math.random Math class double Math.random() Returns a number x in the range, 0.0 <= x < 1.0. int randomIndex = (int)(Math.random()*10); Produce numbers from 0 to 9 N = 9 Needs to be cast to an int
2D Arrays Two-Dimensional Arrays A two-dimensional array is a table/matrix -- with rows and columns -- where each row is an array, and there are several rows in a table. e.g. a two-dimensional array of 3 rows and 4 columns
Create 2D Array To create a two-dimensional array, you specify the number of rows (first) and columns (second). int[][] iMat = new int[3][4]; // integer matrix of 3 rows, 4 columns double[][] dMat = new double[5][3]; // double matrix of 5 rows, 3 columns char[][] cMat = new char[3][3]; // char matrix -- 3 rows, 3 columns
Direct Initialization To give initial values for the elements in a two- dimensional array, you can of course set up a loop. Another way is to provide the initial values directly in declaration. int[][] iMat = { {12, 48, 69, 7}, {5, 16, 27, 30}, {51, 3, 72, 9} };
Access an element in 2D Array Each row is an individual array Column index starts at 0 To access an element in a two- dimensional array, you specify the row index (first) and column index (second). System.out.println(iMat[0][2]); // prints an element at row 0, column 2 (69 in the example above) iMat[2][2] = 5; // assign 5 to row 2, column 1
Length 2D array Lengths of a Two-dimensional Array. Arrays can contain different number of column elements at each row | 12 | 48 | 69 | 7 | | 5 | 16 | 27 | | | 51 | 3 | | LENGTH OF ROW AND COLUMN The Row length (number of rows in the array) is found by using length. int numRow = mat.length; Array to the side has 3 rows The Column Length is different for each row so you must access the row first then the column length. int columnLength = mat[0].length // equal 4 int columnLength = mat[1].length // equal 3
Traversing Over a 2D Array with for loop Then we can utilize those two lengths to traverse over a two-dimensional array -- also by using a nested loop. Two for loops: First specify the row to loop through and then the column. Use Variables row and col to represent the row and column. int row, col; for (row = 0; row < matrix.length; row++) { for (col = 0; col < matrix[row].length; col++) System.out.print[matrix[row][col] + “ “ ); } System.out.println(); } int[][] iMat = { {12, 48, 69, 7}, {5, 16, 27, 30}, {51, 3, 72, 9} };
ArrayList implements Java.util.List Implements means that the class that implements another class must also implement (use) its methods. ArrayList implements List so it has all the methods from the List interface class java.util.ArrayList implements java.util.List class java.util.List – int size() – boolean add(E obj) // appends obj to the end of list; returns true – void add(int index, E obj) // inserts obj at position index (0<= index <= size), // moving elements at position index and higher // to the right (adds 1 to their indices) and adjusts size – E get(int index) – E set(int index, E obj) // replaces the element at position index, with obj //returns the element formerly at the specified position – E remove(int index) // removes element from position index, moving elements // at position index + 1 and higher to the left // (subtracts 1 from their indices) and adjusts size // returns the element formerly at the specified position
Facts about ArrayList ArrayList can grow and shrink in size. – add, set and remove methods ArrayList use Generics type ArrayList only hold objects – Wrapper class Integer and Double ArrayList uses size() method to find the size (length) of the array). Array class used length variable
Creating an ArrayList ArrayList contain elements of type E Generics: the collections classes are generic, with type parameters. The type parameter is replaced by an actual object type. The is replaced with the type of object. ArrayList list = new ArrayList ();
Boxing and unboxing Autoboxing is the automatic conversion from a primitive type to its Object type. For example, converting an int to an Integer, a double to a Double If the conversion goes the other way, this is called unboxing. List li = new ArrayList<>(); for (int i = 1; i < 50; i += 2) li.add(i); int x = li.get(i); i is converted to the Integer object type i is converted back to an integer (int)
Wrapper Classes class java.lang.Integer – Integer(int value) – int intValue() – Integer.MIN_VALUE // minimum value represented by an int – Integer.MAX_VALUE // maximum value represented by an int class java.lang.Double – Double(double value) – double doubleValue() public int min(int [] nums) { int min = Integer.MAX_VALUE; for(int i = 0; i < nums.length; i++) { if(min > nums[i]) min = nums[i]; } return min; }
Example Arraylist list = new ArrayList (); list.add(“one”); list.add(“two”); list.add(“three”); list.remove(0); list.set(1, “one”); System.out.println(list); one two one two three two three two one three two one three
What prints? ArrayList words = new ArrayList (); words.add(“Zack”); words.add(“Bobby”); words.add(0, "Billy"); words.add(1, "Sam"); words.add(2, "Jane"); words.add(1, "Johnny"); words.remove(2); words.set(1, "Tammy"); words.add("Sally"); What will print? Figure this out and earn extra points on your ArrayList Quiz
Printing ArrayList Printing out an ArrayList For loop for(int i = 0; i < words.size(); i++) System.out.println(words.get(i)); For each loop Create the element for type of ArrayList for(String element : words) { Systemout.println(element); }
Iterator Interface Definition of an Iterator: purpose is to traverse over a collection. Iterator Interface: is in the Collection API ListIterator is in the Collection API Iterator has these methods Boolean hasNext() returns true if at leas one more element to be examined. E next(); Returns the next element in the iteration void remove() deletes from the collection the last element that was returned by next.
Examples of using Iterator Example of Iterator System.out.println("using iterator"); Iterator itr = words.iterator(); while(itr.hasNext()) System.out.println(itr.next()); Iterator it = words.iterator(); while(it.hasNext()) // true if at least one element { if(it.next().length() == 2) //returns the next element it.remove(); // removes element returned by next } System.out.println(words);
Array & ArrayList Free Response tally is the array Contains the frequency the index location occurred. The value 4 occurred 10 times
Example of what should be returned. The first is the ArrayList. The second is the index of the modes in the array run Stats [4, 7, 7, 8, 0, 9, 3, 9, 9, 3] [5, 7, 8] > 9 is the mode. It occurred at index locations 5, 7, 8 [1, 9, 8, 2, 2, 0, 2, 9, 10, 7] [8] The mode is 10 so it returns index 8 Both Array and ArrayList solutions use the same algorithm; however, the ArrayList is easier since you do not have to know the size of an ArrayList when you create it. You must use the findMax(tally) method to find the max number before looping through the array. Then as you loop through the array you will see how many times that number is in the array. ArrayList you can directly store the index location into an ArrayList you have created. Array must first count the number of occurrences as you loop through tally. Then create a new array of that size. Loop through the old array (tally) and if index = max store that index in the new array. Don’t forget to increase the index of the new array.
Part B You Should create a method called kthDataValue(array or arraylist, int k) This method will take either an array or arraylist depending on the parameter and a number that represents the number of elements. It will return the position of the kth element. kthDataValue(list, 14); Returns: [3, 3, 10, 1, 6, 6, 10, 6, 10, 3] // arraylist 2 // The 14 element is at index 2 Remember the array or arraylist looks like this: etc. Hints: You will need a counter variable that will actually accumlate the sum of the indexes. If the sum of the index is greater than k than return that index.