The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R 1 1 1 slides partially adapted from.

Slides:



Advertisements
Similar presentations
Chapter 8: Arrays.
Advertisements

Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
An Array A sequence of elements of a particular type Each element in the array has an index which gives its position in the sequence An array is declared.
1 Various Methods of Populating Arrays Randomly generated integers.
Chapter 11 Arrays. Introduction Array: An ordered collection of values with two distinguishing characters: – Ordered and fixed length – Homogeneous. Every.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Simple Arrays Eric Roberts CS 106A February 10, 2010.
1 More on Arrays Passing arrays to or from methods Arrays of objects Command line arguments Variable length parameter lists Two dimensional arrays Reading.
O-1 University of Washington Computer Programming I Lecture 14: Arrays © 2000 UW CSE.
©2004 Brooks/Cole Chapter 8 Arrays. Figures ©2004 Brooks/Cole CS 119: Intro to JavaFall 2005 Sometimes we have lists of data values that all need to be.
© The McGraw-Hill Companies, 2006 Chapter 5 Arrays.
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.
COMP 110 Introduction to Programming Mr. Joshua Stough October 24, 2007.
Arrays in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 8 Arrays and Strings
CS0007: Introduction to Computer Programming Introduction to Arrays.
Java Unit 9: Arrays Declaring and Processing Arrays.
© 2011 Pearson Education, publishing as Addison-Wesley 1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 6 focuses.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
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.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 8 Arrays and Strings
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
CMSC 202 Arrays. Aug 6, Introduction to Arrays An array is a data structure used to process a collection of data that is all of the same type –An.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning 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.
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.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
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.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
***** SWTJC STEM ***** Chapter 7 cg 50 Arrays as Parameters Regular variables are passed to a method by value; i.e., the variable value is copied to a.
Function Overloading Two different functions may have the same name as long as they differ in the number or types of arguments: int max(int x, int y) and.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
Chapter 8 Arrays. A First Book of ANSI C, Fourth Edition2 Introduction Atomic variable: variable whose value cannot be further subdivided into a built-in.
CSE 1201 Object Oriented Programming ArrayList 1.
Java Software Solutions Lewis and Loftus Chapter 6 1 Copyright 1997 by John Lewis and William Loftus. All rights reserved. Objects for Organizing Data.
8-1 Chapter-7 Part1 Introduction to Arrays –Array Types –Creating/Declaring Arrays –Initializing Arrays –Processing Array Contents –Passing Arrays as Arguments.
Array Size Arrays use static allocation of space. That is, when the array is created, we must specify the size of the array, e.g., int[] grades = new int[100];
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
Comp 248 Introduction to Programming Chapter 6 Arrays Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Simple Arrays Eric Roberts CS 106A February 12, 2016.
1 Arrays Chapter 8. Objectives You will be able to Use arrays in your Java programs to hold a large number of data items of the same type. Initialize.
Arrays and Array Lists CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Quiz: Design a Product Class Create a definition for a class called Product, which keeps track of the following information: –Name of the product –Weight.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays. What is an array? An array is a collection of data types. For example, what if I wanted to 10 different integers? int num1; int num2; int num3;
Chapter 7 Arrays…. 7-2 Arrays An array is an ordered list of values An array of size N is indexed from.
ARRAYS (Extra slides) Arrays are objects that help us organize large amounts of information.
Chapter VII: Arrays.
Chapter 7 User-Defined Methods.
CS106A, Stanford University
Short introduction to processing data
Simple Arrays Eric Roberts CS 106A February 15, 2017.
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.
CS2011 Introduction to Programming I Arrays (II)
Announcements Lab 7 due Wednesday Assignment 4 due Friday.
Lecture 10: Arrays AP Computer Science Principles
Announcements Lab 6 was due today Lab 7 assigned this Friday
Building Java Programs
CS106A, Stanford University
Dr. Sampath Jayarathna Cal Poly Pomona
Suggested self-checks: Section 7.11 #1-11
Presentation transcript:

The Art and Science of An Introduction to Computer Science ERIC S. ROBERTS Java Arrays and ArrayLists C H A P T E R slides partially adapted from UW CSE 142 course slides Lecture Slides, Part II -- Review

Comp 101 | Özyeğin University2 A named, ordered collection of variables of identical type We do not name every individual element in the collection Instead, we give a name to the whole collection We access individual elements in the collection by specifying its order in the collection –This is called the index Recap: Arrays

3 int score = 0; int[] scores = new int[10]; scores 0 score Element type Length index

Acessing Arrays scores int[] scores = new int[10]; scores scores[0] = 25; scores scores[1] = 17; 4

Array Length int[] scores = new int[10]; println("Length of the array is " + scores.length); Length of the array is 10 5

Exercise CS 101 | Özyeğin University6 Guess the output of the following program int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers.length - i; } for (int i = 0; i < numbers.length; i++) { print(numbers[i] + " "); }

Exercise CS 101 | Özyeğin University7 Guess the output of the following program int[] numbers = new int[5]; for (int i = 0; i < numbers.length; i++) { numbers[i] = numbers.length - i; } for (int i = 0; i < numbers.length; i++) { print(numbers[i] + " "); }

Exercise CS 101 | Özyeğin University8 Write a program that provides a solution for the motivating example: –Get a set of numbers from the user –Print out the numbers that are above the average of the whole set of numbers

CS 101 | Özyeğin University9 int noOfNumbers = readInt("Enter the total amount of numbers: "); int[] numbers = new int[noOfNumbers]; for (int i = 0; i < numbers.length; i++) { numbers[i] = readInt("Enter a number: "); } int total = 0; for (int i = 0; i < noOfNumbers; i++) { total = total + numbers[i]; } double average = (double) total / numbers.length; for (int i = 0; i < numbers.length; i++) { if(numbers[i] > average) { println(numbers[i] + " is above average!"); }

An array is a collection of variables Each element can be used wherever a simple variable of that type is allowed. –Assignment, expressions, input/output An entire array can’t be treated as a single variable –Can’t assign or compare arrays using =, <, … –Can’t use println to read or write an entire array –But, you can do these things one element at a time Technicalities

Internal Representation of Arrays Arrays in Java are implemented as objects, which means that they are stored in the heap. The value stored in an array variable is simply a reference to the actual array. int score = 0; int[] scores = new int[10]; 0 score scores 11

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score foo 12

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 5 foo 13

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 6 foo 14

Internal Representation of Arrays int score = 5; int foo = score; foo++; println(score); // prints 5 println(foo); // prints 6 5 score 6 foo 15

Internal Representation of Arrays int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints scores numbers 16

Internal Representation of Arrays scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 17

Internal Representation of Arrays scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 18

Internal Representation of Arrays scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 19

Internal Representation of Arrays scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 20

Internal Representation of Arrays scores numbers int[] scores = new int[10]; int[] numbers = scores; numbers[5] = 42; println(scores[5]); // prints 42 println(numbers[5]); // prints 42 scores[0] = 77; println(scores[0]); // prints 77 println(numbers[0]); // prints 77 21

Individual array elements can be used as parameters, just like other simple variables. The corresponding element in the array is copied to the argument Example: int result = power(numbers[0], numbers[1]); println(numbers[0] + “ to the power ” + numbers[1] + “ is ” + result) ; Array elements as arguments

Array arguments (entire arrays) work differently: –An array is never copied –The array name is always treated as a reference to the collection of elements Whole arrays as arguments

Initializing Arrays Java makes it easy to initialize the elements of an array as part of a declaration. The syntax is type [] name = { elements }; where elements is a list of the elements of the array separated by commas. The length of the array is automatically set to be the number of values in the list. For example, the following declaration initializes the variable powersOfTen to the values 10 0, 10 1, 10 2, 10 3, and 10 4 : int[] powersOfTen = { 1, 10, 100, 1000, }; This declaration creates an integer array of length 5 and initializes the elements as specified. 24

Exercise Comp 101 | Özyeğin University25 Write a method, which takes an array of integers as argument and returns an array with the same elements in reverse order.

The ReverseArray Program skip simulation public void run() { int n = readInt("Enter number of elements: "); int[] intArray = createIndexArray(n); println("Forward: " + arrayToString(intArray)); reverseArray(intArray); println("Reverse: " + arrayToString(intArray)); } n 10 intArray ReverseArray Enter number of elements: 10 Forward: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Reverse: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] private int[] createIndexArray(int n) { int[] array = new int[n]; for ( int i = 0; i < n; i++ ) { array[i] = i; } return array; } 10 narrayi private String arrayToString(int[] array) { String str = ""; for (int i = 0; i < array.length; i++) { if (i > 0) str += ", "; str += array[i]; } return "[" + str + "]"; } arrayistr , 10, 1, 20, 1, 2, 30, 1, 2, 3, 40, 1, 2, 3, 4, 50, 1, 2, 3, 4, 5, 60, 1, 2, 3, 4, 5, 6, 70, 1, 2, 3, 4, 5, 6, 7, 80, 1, 2, 3, 4, 5, 6, 7, 8, 9 private void reverseArray(int[] array) { for (int i = 0; i < array.length / 2; i++) { swapElements(array, i, array.length - i - 1); } arrayi private void swapElements(int[] array, int p1, int p2) { int temp = array[p1]; array[p1] = array[p2]; array[p2] = temp; } array 9 p2 0 p1temp 0 public void run() { int n = readInt("Enter number of elements: "); int[] intArray = createIndexArray(n); println("Forward: " + arrayToString(intArray)); reverseArray(intArray); println("Reverse: " + arrayToString(intArray)); } nintArray

Exercise Comp 101 | Özyeğin University27 Write the DiceRoll program using an array, instead of using a variable for each face value.

Comp 101 | Özyeğin University28 public class DiceRoll extends ConsoleProgram { private RandomGenerator rgen = RandomGenerator.getInstance(); private static final int NUM_ROLLS = ; public void run() { int[] faces = new int[6]; for(int i = 0; i < NUM_ROLLS; i++) { int n = rgen.nextInt(1, 6); faces[n-1]++; } for (int i = 0; i < faces.length; i++) { println("Percentage of " + (i+1) +"'s " + faces[i]*100.0/NUM_ROLLS + " %."); }

Arrays hold multiple values All values are of the same type Notation: [i] selects one array element [0] is always the first element Be careful with array bounds! Especially useful with large amounts of data Often processed within loops Entire array can be passed as an argument Summary

Extending an array Arrays are created with fixed length; they cannot be resized. Solution: Create a new array that is one element longer than the original. Copy each element from the original into the new array. Set the extra element of the new array. Assign the new array back to the original array variable.

Extending an array abcdef Create a new array that is one element longer than the original. originalArray newArray

Extending an array abcdef Copy each element from the original into the new array. originalArray newArray abcdef

Extending an array abcdef Set the extra element of the new array. originalArray newArray abcdefg

Extending an array abcdef Assign the new array back to the original array variable. originalArray newArray abcdefg