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.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

The ArrayList Class and the enum Keyword
ArrayLists The lazy mans array. Whats the matter here? int[] list = new int[10]; list[0] = 5; list[2] = hey; list[3] = 15; list[4] = 23;
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Chapter 7 – Arrays.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
Java Unit 9: Arrays Declaring and Processing Arrays.
Arrays And ArrayLists - S. Kelly-Bootle
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Week 10 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
1 ArrayList  Array’s are limited because we need to know the size before we use them.  An ArrayList is an extension of an array that grows and shrinks.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
Copyright 2008 by Pearson Education Building Java Programs ArrayList Reading: 10.1.
1 Building Java Programs Chapter 7: Arrays These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be rehosted, sold, or.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Enhanced For Loops (For Each Loops) Less Code and Less Overhead for Writing For Loops.
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Lists What to do?. Lists  A list is a linear arrangement of data elements.  Items are arranged in sequential (linear) order  Items are therefore ordered.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Arrays…JavaCPython have fixed lengthyes*yesno are initialized to default values yesno? track their own lengthyesnoyes trying to access “out of bounds”
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
Get Longest Run Index (FR) public int getLongestRunIndex(int []values) { int maxRunStart = -1, maxRunLength = 1; int runStart = 0, runLength = 1; for(int.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 1201 Object Oriented Programming ArrayList 1.
ArrayList JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria Litvin, Gary Litvin, and Skylight.
int [] scores = new int [10];
Chapter 12 The ArrayList Data Structure Section 1 - How to Instantiate an ArrayList Section 2 - The ArrayList Subset Section 3 - Declaring an ArrayList.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
The ArrayList Data Structure The Most Important Things to Review.
The ArrayList Data Structure Standard Arrays at High Speed!
Chapter 9 Introduction to Arrays Fundamentals of Java.
Lecture 20: Wrapper Classes and More Loops
(like an array on steroids)
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
TCSS 143, Autumn 2004 Lecture Notes
Can store many of the same kind of data together
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
ArrayList Collections.
Can store many of the same kind of data together
Grouped Data Arrays, and Array Lists.
int [] scores = new int [10];
ArrayLists 22-Feb-19.
Building Java Programs
Can store many of the same kind of data together
Review of Previous Lesson
Review: libraries and packages
Ps Module 7 – Part II 2D Arrays and LISTS 5/26/2019 CSE 1321 Module 7.
Presentation transcript:

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.