Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays

Slides:



Advertisements
Similar presentations
Chapter 10 Introduction to Arrays
Advertisements

ECE122 L13: Arrays of Objects March 15, 2007 ECE 122 Engineering Problem Solving with Java Lecture 13 Arrays of Objects.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Chapter 8 Arrays and Strings
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Java Unit 9: Arrays Declaring and Processing Arrays.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Chapter 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
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.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
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
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
The ArrayList Data Structure Standard Arrays at High Speed! More Safety, More Efficient, and Less Overhead!
How do you do the following? Find the number of scores within 3 points of the average of 10 scores? What kind of a tool do you need? Today’s notes: Include.
Java – An Object Oriented Language CS 307 Lecture Notes Lecture Weeks 5-6 Khalid Siddiqui.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.
The ArrayList Data Structure The Most Important Things to Review.
The ArrayList Data Structure Standard Arrays at High Speed!
 2005 Pearson Education, Inc. All rights reserved Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Arrays Chapter 7.
CMSC 202 ArrayList Aug 9, 2007.
Chapter VII: Arrays.
Array in C# Array in C# RIHS Arshad Khan
Lesson 8: Introduction To Arrays
Arrays Chapter 7.
Lecture 20: Wrapper Classes and More Loops
Computer Programming BCT 1113
© 2016 Pearson Education, Ltd. All rights reserved.
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
Arrays, 2-D Arrays, and ArrayList
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
7 Arrays.
Can store many of the same kind of data together
Chapter 8 Slides from GaddisText
Arrays We often want to organize objects or primitive data in a way that makes them easy to access and change. An array is simple but powerful way to.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
CMSC 202 ArrayList Aug 9, 2007.
Can store many of the same kind of data together
Object Oriented Programming in java
CMSC 202 ArrayList Aug 9, 2007.
Arrays Chapter 7.
ArrayLists 22-Feb-19.
Building Java Programs
Can store many of the same kind of data together
CIS16 Application Development and Programming using Visual Basic.net
Suggested self-checks: Section 7.11 #1-11
CS1001 Lecture 14.
Review: libraries and packages
List Interface ArrayList class implements the List Interface
How do you do the following?
Arrays.
Presentation transcript:

Topics Covered: Arrays, 1-D & 2-D Passing & Returning Arrays Enhanced for loop Swap/Copy Elements List Interface ArrayList Class Margaret Winans, 2014 AP TIP

double day [] = new double[365]; Arrays Arrays may be declared and defined on one line (…the easy way) double[] day = new double[365]; ~or~ double day [] = new double[365]; number of “elements” constructor data type identifier specifies an array… an operator Margaret Winans, 2014 AP TIP

What is an Array A block of consecutive memory locations of the same data type. Allows many “values” to be saved in a single data structure Individual locations are called the array’s element, index, or subscript. When we say array’s “element” or “index” we mean the value stored in that element. There is indeed some confusion in the usage of “element.” In some situations, the word refers to the location in an array, as in “set the value of the k-th element.” In other situations it refers to a value stored in the array, as in “find the smallest element.” This dual usage is somewhat similar to the situation with the term “variable.” This is no big deal, as long as everyone understands the difference between a location and a value stored in it. Margaret Winans, 2014 AP TIP

Array Examples 5 5 INDEX = 0 to (length - 1) Margaret Winans, 2014 AP TIP

Indices We can use an int variable or any expression that evaluates to an int value as an index: That’s the beauty of it: the index may be a variable calculated at run time; it can be used in algorithms. Examples: a [3] a [k] a [k – 2] for (int i = 0; i < array.length; i++) { System.out.print(“Name: “); array[ i ] = reader.nextLine(); } Margaret Winans, 2014 AP TIP

Indices (cont’d) In Java, an array is declared with a fixed length that cannot be changed. Java interpreter checks the values of indices at run time and throws IndexOutOfBoundsException if an index is negative or if it is greater than the length of the array - 1. arr = new int[newSize]; does not really resize arr: it simply throws away the old array and allocates a new one with default values. “Throws an exception” means reports a run-time error with rather detailed information about where in the code it occurred and aborts the program. Margaret Winans, 2014 AP TIP

Square brackets, not parentheses! Arrays are Objects In Java, an array is an object. As with other objects, the declaration creates only a reference, initially set to null. Two ways to create an array: The second form, with a list of initial values, is not in the AP subset. arrName = new anyType [ length ] ; Square brackets, not parentheses! or arrName = new anyType [ ] { val1, val2, …, valN }; Initializer List Margaret Winans, 2014 AP TIP

Array Objects Because arrays are objects, all rules that apply to objects apply to arrays. Two array variables may refer to same array. Arrays may be garbage collected. Array variables may be set to null. ref ref Margaret Winans, 2014 AP TIP

Declaring and Initializing When created, space is allocated to hold array elements Unless specific values are given in an {…} list, all the elements are initialized to a default value: 0 for numbers, false for booleans, and null for objects If its elements are objects, the array holds references to objects, which are initially set to null As for fields: 0 for numbers, false for booleans, null for objects. The elements get default values even if an array is a local variable. You can think of an array’s elements as sort of like its “fields.” Margaret Winans, 2014 AP TIP

Array Length The length of an array is determined when the array is created. The length is either given explicitly or comes from the length of the {…} initialization list. The length of an array arrName is referred to in the code as arrName.length. length appears like a public field (not a method) in an array object. As opposed to String, where length() is a method. Margaret Winans, 2014 AP TIP

Arrays that are not “full” Physical size: The maximum number of elements that an array can contain Logical size: The actual number of elements stored in an array Declare an integer counter that will always indicate the number of elements. Every time an element is added or removed, adjust the counter accordingly. The counter indicates the logical size of the array and the next open position in the array. Margaret Winans, 2014 AP TIP

Creating & Adding objects to an ‘Object’ Array Address [ ] addr = new Address [20]; int ctr = 0; addr[ctr] = new Address (nm, str, cit, stZip); ctr ++; Margaret Winans, 2014 AP TIP

Passing Arrays An array reference is passed to a method by using only the name of the array The array’s name contains the reference to the array & the length variable containing the size of the array (#of elements) The parameter in the called method is declared as an array of the same data type int num[ ] = new int[500]; loadArray(num); //method call public void loadArray(int numbers[]){ statements; } numbers IS num, not a copy Margaret Winans, 2014 AP TIP

When an array is passed: What will print from this code segment? int [] arr = {1, 2, 3, 4}; doSomething(arr); System.out.print (arr[1] + “, “ + arr[3]); public void doSomething (int [] list){ int [] b = list; for (int i = 0; i < b.length; i++) b[i] = i; } output = 1, 3 The array memory location was passed, so all changes to array ‘b’ are actually changes to the original array ‘arr’ the array now stores {0, 1, 2, 3}; Margaret Winans, 2014 AP TIP

Returning Arrays from Methods As with other objects, an array can be returned from a method. The returned array is usually constructed within the method or obtained from calls to other methods. The return type of a method that returns an array with someType elements is designated as someType [ ]. Example: public String[ ] getArray( ) It is helpful to think of someType[ ] as a data type designation, “array of someType elements.” Margaret Winans, 2014 AP TIP

Enhanced for Loop From the first index to the last Frees programmer from having to manage and use loop counters aka “for-each” loop int [ ] abc = { 2, 3, 4}; int sum = 0; for (int element : abc) sum += element; Margaret Winans, 2014 AP TIP

Enhanced for Loop (cont.) Cannot be used to: Move through an array in reverse, from the last position to the 1st position Assign elements to positions in an array Track the index position of the current element in an array Access any element other than the current element on each pass Margaret Winans, 2014 AP TIP

Parallel Arrays Two or more arrays of the same size that store complementary data Example: one array stores first names and a second stores corresponding ages. Margaret Winans, 2014 AP TIP

Interchanging adjacent elements int temp; temp = abc[i]; abc[i] = abc[i + 1]; abc [i + 1] = temp; BEFORE abc [0] = 10 abc [1] = 15 abc [2] = 20 Interchange Code temp = abc [0]; temp = 10 abc [0] = abc [1]; abc [0] = 15 abc [1] = temp; abc [1] = 10 AFTER abc [0] = 15 abc [1] = 10 abc [2] = 20 Margaret Winans, 2014 AP TIP

Copying an Array Method to make a copy of an array and return it: private int [ ] original = {1, 2, 3, 4, 5}; private int [ ] copy; //How to call the method to create a copy copy = copyArray (original); //method to copy the "original" array into a //new array named “temp“ public int[ ] copyArray (int [ ] orig){ int [ ] temp = new int [orig.length]; for (int i = 0; i < orig.length; i++){ temp[i] = orig[i]; } return temp; Margaret Winans, 2014 AP TIP

2-Dimensional Arrays Margaret Winans, 2014 AP TIP

2-D Arrays Visualize a table with rows and columns Margaret Winans, 2014 AP TIP

2-D Arrays (cont.) A 2-D array is actually an “array of arrays” Each element of a one-dimensional array contains another array Margaret Winans, 2014 AP TIP

Declare/Instantiate 2-D Array Declaring and instantiating a two-dimensional array example: declaring: int [ ] [ ] table; instantiating: table = new int [4] [5]; // The variable table will reference a // two-dimensional array of integers. // Instantiate table as an array of size 4, // each of whose elements will reference an // array of 5 integers. Margaret Winans, 2014 AP TIP

2-D Array Initializer List The rows in a 2-D array may have varying lengths. Ragged arrays (not an AP topic ) Margaret Winans, 2014 AP TIP

Looping through 2-D Array To loop through a two-dimensional array, use nested ‘for’ loops—outer loops thru the rows & inner loops thru the columns int sum = 0; for (int i = 0; i < table.length; i++){ for (int j = 0; j < table [ i ].length; j++) sum += table [ i ] [ j ]; ~OR~ for(int row = 0; row < table.length; row++) for(int colm = 0; colm < table[row].length; colm++) sum += table[row][colm]; Margaret Winans, 2014 AP TIP

List Interface ArrayList class implements the List Interface import java.util.List; Lists are generic (java 5.0)—Elements are declared to be of a specific object type when a list or collection variable is declared. <E>is a the object type—tells compiler to check for that element type when a collection is used List<E> list = new ArrayList<E>(); List<String> list = new ArrayList<String>(); Margaret Winans, 2014 AP TIP

List<Integer> list = new ArrayList<Integer>(); The variable list is declared to be of type List<Integer> (the interface) but is instantiated as type ArrayList<Integer> (the implementation)—preferred byAPCS This has the advantage of making the code applicable to any List. For example, a single change: List<Integer> list = new LinkedList<Integer>(); The AP Quick Reference Guide (given to you for the AP exam) only gives methods of the List interface Margaret Winans, 2014 AP TIP

The ArrayList Class Contains a sequence of elements ordered by position Unlike an array in that: It uses methods rather than [] to manipulate elements. It tracks both logical and physical size. The logical size is 0 when created & automatically adjusts as needed. The positions available for access range from 0 to the logical size minus 1. ArrayList can be printed without a loop Margaret Winans, 2014 AP TIP

AP Quick Reference Guide: List Interface The List interface methods below are all inherited by the ArrayList This is the actual screen shot from the QRG Margaret Winans, 2014 AP TIP

The ArrayList Class E = obj type not length boolean add(obj) Appends obj to end of the list; returns true Margaret Winans, 2014 AP TIP

The ArrayList Class (cont.) ArrayList objects cannot directly store primitive types and must use wrapper classes Boolean, Integer, Double, Character Each wrapper class contains the value of it’s primitive type. ArrayList objects automatically “box” and “unbox” primitive values when used with ArrayList methods. Margaret Winans, 2014 AP TIP

Adding/Changing values using an ArrayList //create a list of Integer objects List<Integer> list = new ArrayList<Integer>(); //add int values 1-100 to the list for (int i = 1; i <= 100; i++) list.add(i); // Increment each int in the list for (int i = 0; i < 100; i++) list.set(i, list.get(i) + 1); Margaret Winans, 2014 AP TIP