Chapter 8 Slides from GaddisText Arrays of more than 1 dimension.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Two Dimensional Arrays and ArrayList
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays.
Slides prepared by Rose Williams, Binghamton University Chapter 6 Arrays.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
Java: How to Program Arrays and ArrayLists Summary Yingcai Xiao.
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.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 9 Introduction to Arrays
Introduction to Arrays. Useful Array Operations  Finding the Highest Value int [] numbers = new int[50]; int highest = numbers[0]; for (int i = 1; i.
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 and the ArrayList Class
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
© 2012 Pearson Education, Inc. All rights reserved. Lecture 2 (Chapter 8): Arrays and the ArrayList Class Starting Out with Java: From Control Structures.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: From Control Structures through Objects Third Edition.
One Dimensional Array. Introduction to Arrays Primitive variables are designed to hold only one value at a time. Arrays allow us to create a collection.
Chapter 7: Arrays and the ArrayList Class
Chapter 9: Advanced Array Concepts
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Arrays and the ArrayList Class Starting Out with Java From Control.
Chapter 8 Arrays and Strings
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
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.
AP Comp Sci A Chapter 12 - Arrays. Ch 12 Goals: Goals: Declare and create arrays Declare and create arrays Access elements in arrays Access elements in.
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.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 8: Arrays and the ArrayList Class Starting Out with Java: From.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
I NTRODUCTION TO PROGRAMMING Starting Out with Java: From Control Structures through Objects.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 6: Arrays Presentation slides for Java Software Solutions for AP* Computer Science 3rd Edition.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
IT259 Foundation of Programming Using Java Unit 9 Seminar : (Chapter 8 ) Instructor : Vladimir Gubanov, PhD
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Two Dimensional Arrays Found in chapter 8, Section 8.9.
Chapter 8: Part 3 Collections and Two-dimensional arrays.
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 7: Arrays and the ArrayList Class Starting Out with Java: From Control Structures through Objects Fifth Edition by Tony Gaddis.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java: Early Objects Third Edition by Tony Gaddis as modified.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
C++ Array 1. C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An array is used.
© 2004 Pearson Addison-Wesley. All rights reserved7-1 Array review Array of primitives int [] count; count = new int[10]; Array of objects Grade [] cs239;
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
Chapter 9 Introduction to Arrays Fundamentals of Java.
1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is.
Chapter 8 Arrays and the ArrayList Class Arrays of Objects.
Chapter 8 Arrays and the ArrayList Class Multi-Dimensional Arrays.
Chapter Topics Chapter 7 discusses the following main topics:
ARRAYLIST AND VECTOR.
Arrays, Searching and Sorting
Arrays and the ArrayList Class The ArrayList Class
Chapter-7 part3 Arrays Two-Dimensional Arrays The ArrayList Class.
Chapter 8: Advanced Arrays and the ArrayList Class
Chapter 7A: Arrays and the ArrayList Class
Chapter 8 Slides from GaddisText
Multi-Dimensional Arrays
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays.
Presentation transcript:

Chapter 8 Slides from GaddisText Arrays of more than 1 dimension

Declaring a two-dimensional array requires two sets of brackets and two size declarators Declaring a two-dimensional array requires two sets of brackets and two size declarators The first one is for the number of rows The first one is for the number of rows The second one is for the number of columns. The second one is for the number of columns. double[][] scores = new double[3][4]; The two sets of brackets in the data type indicate that the scores variable will reference a two-dimensional array. The two sets of brackets in the data type indicate that the scores variable will reference a two-dimensional array. Notice that each size declarator is enclosed in its own set of brackets. Notice that each size declarator is enclosed in its own set of brackets. Two-Dimensional Arrays two dimensional array rowscolumns

Accessing Two-Dimensional Array Elements When processing the data in a two- dimensional array, each element has two subscripts: When processing the data in a two- dimensional array, each element has two subscripts: one for its row and one for its row and another for its column. another for its column.

Accessing Two-Dimensional Array Elements scores[0][3]scores[0][2]scores[0][1]scores[0][0] row 0 column 1column 2column 3column 0 row 1 row 2 The scores variable holds the address of a 2D array of double s. Address scores[1][3]scores[1][2]scores[1][1]scores[1][0] scores[2][3]scores[2][2]scores[2][1]scores[2][0]

Accessing Two-Dimensional Array Elements Accessing one of the elements in a two- dimensional array requires the use of both subscripts. scores[2][1] = 95; 0000 row 0 column 1column 2column 3column 0 row 1 row 2 Address The scores variable holds the address of a 2D array of double s.

Accessing Two-Dimensional Array Elements Programs that process two-dimensional arrays can do so with nested loops. Programs that process two-dimensional arrays can do so with nested loops. To fill the scores array: To fill the scores array: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) for (int col = 0; col < 4; col++){ System.out.print("Enter a score: "); System.out.print("Enter a score: "); scores[row][col] = keyboard.nextDouble(); scores[row][col] = keyboard.nextDouble(); }} Number of rows, not the largest subscript Number of columns, not the largest subscript keyboard references a Scanner object

Accessing Two-Dimensional Array Elements To print out the scores array: To print out the scores array: for (int row = 0; row < 3; row++) { for (int col = 0; col < 4; col++) for (int col = 0; col < 4; col++){ System.out.println(scores[row][col]); System.out.println(scores[row][col]); }} See example: CorpSales.java See example: CorpSales.javaCorpSales.java

Initializing a Two-Dimensional Array Initializing a two-dimensional array requires enclosing each row’s initialization list in its own set of braces. Initializing a two-dimensional array requires enclosing each row’s initialization list in its own set of braces. int[][] numbers = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; Java automatically creates the array and fills its elements with the initialization values. Java automatically creates the array and fills its elements with the initialization values. row 0 {1, 2, 3} row 0 {1, 2, 3} row 1 {4, 5, 6} row 1 {4, 5, 6} row 2 {7, 8, 9} row 2 {7, 8, 9} Declares an array with three rows and three columns. Declares an array with three rows and three columns.

Initializing a Two-Dimensional Array 321 row 0 column 1column 2column 0 row 1 row 2 Address The numbers variable holds the address of a 2D array of int values. int[][] numbers = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; produces:

The length Field Two-dimensional arrays are arrays of one- dimensional arrays. Two-dimensional arrays are arrays of one- dimensional arrays. The length field of the array gives the number of rows in the array. The length field of the array gives the number of rows in the array. Each row has a length constant tells how many columns is in that row. Each row has a length constant tells how many columns is in that row. Each row can have a different number of columns. Each row can have a different number of columns.

The length Field To access the length fields of the array: To access the length fields of the array: int[][] numbers = { { 1, 2, 3, 4 }, { 5, 6, 7 }, { 5, 6, 7 }, { 9, 10, 11, 12 } }; { 9, 10, 11, 12 } }; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) for (int col = 0; col < numbers[row].length; col++) System.out.println(numbers[row][col]); System.out.println(numbers[row][col]);} See example: Lengths.java See example: Lengths.javaLengths.java Number of rowsNumber of columns in this row. The array can have variable length rows.

Summing The Elements of a Two-Dimensional Array int[][] numbers = { { 1, 2, 3, 4 }, {5, 6, 7, 8}, {5, 6, 7, 8}, {9, 10, 11, 12} }; {9, 10, 11, 12} }; int total; total = 0; for (int row = 0; row < numbers.length; row++) { for (int col = 0; col < numbers[row].length; col++) for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; total += numbers[row][col];} System.out.println("The total is " + total);

Summing The Rows of a Two- Dimensional Array int[][] numbers = {{ 1, 2, 3, 4}, {5, 6, 7, 8}, {5, 6, 7, 8}, {9, 10, 11, 12}}; {9, 10, 11, 12}}; int total; for (int row = 0; row < numbers.length; row++) { total = 0; total = 0; for (int col = 0; col < numbers[row].length; col++) for (int col = 0; col < numbers[row].length; col++) total += numbers[row][col]; total += numbers[row][col]; System.out.println("Total of row " System.out.println("Total of row " + row + " is " + total); + row + " is " + total);}

Summing The Columns of a Two-Dimensional Array int[][] numbers = {{1, 2, 3, 4}, {5, 6, 7, 8}, {5, 6, 7, 8}, {9, 10, 11, 12}}; {9, 10, 11, 12}}; int total; for (int col = 0; col < numbers[0].length; col++) { total = 0; total = 0; for (int row = 0; row < numbers.length; row++) for (int row = 0; row < numbers.length; row++) total += numbers[row][col]; total += numbers[row][col]; System.out.println("Total of column " System.out.println("Total of column " + col + " is " + total); + col + " is " + total);}

Passing and Returning Two- Dimensional Array References There is no difference between passing a single or two-dimensional array as an argument to a method. There is no difference between passing a single or two-dimensional array as an argument to a method. The method must accept a two-dimensional array as a parameter. The method must accept a two-dimensional array as a parameter. See example: Pass2Darray.java See example: Pass2Darray.javaPass2Darray.java

Ragged Arrays When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array. When the rows of a two-dimensional array are of different lengths, the array is known as a ragged array. You can create a ragged array by creating a two- dimensional array with a specific number of rows, but no columns. You can create a ragged array by creating a two- dimensional array with a specific number of rows, but no columns. int [][] ragged = new int [4][]; Then create the individual rows. Then create the individual rows. ragged[0] = new int [3]; ragged[1] = new int [4]; ragged[2] = new int [5]; ragged[3] = new int [6];

More Than Two Dimensions Java does not limit the number of dimensions that an array may be. Java does not limit the number of dimensions that an array may be. More than three dimensions is hard to visualize, but can be useful in some programming problems. More than three dimensions is hard to visualize, but can be useful in some programming problems.

Selection Sort In a selection sort: In a selection sort: The smallest value in the array is located and moved to element 0. The smallest value in the array is located and moved to element 0. Then the next smallest value is located and moved to element 1. Then the next smallest value is located and moved to element 1. This process continues until all of the elements have been placed in their proper order. This process continues until all of the elements have been placed in their proper order. See example: SelectionSortDemo.java See example: SelectionSortDemo.javaSelectionSortDemo.java

Binary Search A binary search: A binary search: requires an array sorted in ascending order. requires an array sorted in ascending order. starts with the element in the middle of the array. starts with the element in the middle of the array. If that element is the desired value, the search is over. If that element is the desired value, the search is over. Otherwise, the value in the middle element is either greater or less than the desired value Otherwise, the value in the middle element is either greater or less than the desired value If it is greater than the desired value, search in the first half of the array. If it is greater than the desired value, search in the first half of the array. Otherwise, search the last half of the array. Otherwise, search the last half of the array. Repeat as needed while adjusting start and end points of the search. Repeat as needed while adjusting start and end points of the search. See example: BinarySearchDemo.java See example: BinarySearchDemo.javaBinarySearchDemo.java

Command-Line Arguments A Java program can receive arguments from the operating system command-line. A Java program can receive arguments from the operating system command-line. The main method has a header that looks like this: The main method has a header that looks like this: public static void main(String[] args) The main method receives a String array as a parameter. The main method receives a String array as a parameter. The array that is passed into the args parameter comes from the operating system command-line. The array that is passed into the args parameter comes from the operating system command-line.

Command-Line Arguments To run the example: To run the example: java CommandLine How does this work? args[0] is assigned "How" args[0] is assigned "does" args[0] is assigned "this" args[0] is assigned "work?" Example: CommandLine.java Example: CommandLine.javaCommandLine.java It is not required that the name of main ’s parameter array be args. It is not required that the name of main ’s parameter array be args.

Variable-Length Argument Lists Special type parameter – vararg… Special type parameter – vararg… Vararg parameters are actually arrays Vararg parameters are actually arrays Examples: VarArgsDemo1.java, VarargsDemo2.java Examples: VarArgsDemo1.java, VarargsDemo2.javaVarArgsDemo1.javaVarargsDemo2.javaVarArgsDemo1.javaVarargsDemo2.java public static int sum(int... numbers) { int total = 0; // Accumulator // Add all the values in the numbers array. for (int val : numbers) total += val; // Return the total. return total; }

The ArrayList Class Similar to an array, an ArrayList allows object storage Similar to an array, an ArrayList allows object storage Unlike an array, an ArrayList object: Unlike an array, an ArrayList object: Automatically expands when a new item is added Automatically expands when a new item is added Automatically shrinks when items are removed Automatically shrinks when items are removed Requires: Requires: import java.util.ArrayList; import java.util.ArrayList;

Creating and Using an ArrayList Create an ArrayList object with no-args constructor Create an ArrayList object with no-args constructor ArrayList nameList = new ArrayList(); ArrayList nameList = new ArrayList(); To populate the ArrayList, use the add method: To populate the ArrayList, use the add method: nameList.add("James"); nameList.add("James"); nameList.add("Catherine"); nameList.add("Catherine"); To get the current size, call the size method To get the current size, call the size method nameList.size(); // returns 2 nameList.size(); // returns 2

Creating and Using an ArrayList To access items in an ArrayList, use the get method To access items in an ArrayList, use the get methodnameList.get(1); In this statement 1 is the index of the item to get. Example: ArrayListDemo1.java Example: ArrayListDemo1.javaArrayListDemo1.java

Using an ArrayList The ArrayList class's toString method r eturns a string representing all items in the ArrayList The ArrayList class's toString method r eturns a string representing all items in the ArrayListSystem.out.println(nameList); This statement yields : [ James, Catherine ] The ArrayList class's remove method removes designated item from the ArrayList The ArrayList class's remove method removes designated item from the ArrayListnameList.remove(1); This statement removes the second item. See example: ArrayListDemo3.java See example: ArrayListDemo3.javaArrayListDemo3.java

Using an ArrayList The ArrayList class's add method with one argument adds new items to the end of the ArrayList The ArrayList class's add method with one argument adds new items to the end of the ArrayList To insert items at a location of choice, use the add method with two arguments: To insert items at a location of choice, use the add method with two arguments: nameList.add(1, "Mary"); This statement inserts the String "Mary" at index 1 To replace an existing item, use the set method: To replace an existing item, use the set method: nameList.set(1, "Becky"); This statement replaces “Mary” with “Becky” See example: ArrayListDemo4.java See example: ArrayListDemo4.javaArrayListDemo4.java

Using an ArrayList An ArrayList has a capacity, which is the number of items it can hold without increasing its size. An ArrayList has a capacity, which is the number of items it can hold without increasing its size. The default capacity of an ArrayList is 10 items. The default capacity of an ArrayList is 10 items. To designate a different capacity, use a parameterized constructor: To designate a different capacity, use a parameterized constructor: ArrayList list = new ArrayList(100);

Using a Cast Operator with the get Method An ArrayList object is not typed An ArrayList object is not typed To retrieve items from an ArrayList, you must cast the item to the appropriate type To retrieve items from an ArrayList, you must cast the item to the appropriate type ArrayList nameList = new ArrayList(); nameList.add("Mary"); // Inserts an item String str = (String)nameList.get(0); Try get without the cast to see the effect. Try get without the cast to see the effect. Example: ArrayListDemo6.java Example: ArrayListDemo6.javaArrayListDemo6.java

Using ArrayList as a Generic Data Type You can create a type-safe ArrayList object by using generics. You can create a type-safe ArrayList object by using generics. For example an ArrayList object for String s: For example an ArrayList object for String s: ArrayList nameList = new ArrayList (); The get method no longer requires casts to work. The get method no longer requires casts to work. Example: GenericArrayListDemo1.java Example: GenericArrayListDemo1.javaGenericArrayListDemo1.java Example: GenericArrayListDemo2.java Example: GenericArrayListDemo2.javaGenericArrayListDemo2.java