1.00/1.001 - Lecture 8 Arrays and Vectors. Arrays-1 Arrays are a simple data structure Arrays store a set of values of the same type – Built-in types.

Slides:



Advertisements
Similar presentations
The ArrayList Class and the enum Keyword
Advertisements

CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
1 Dynamic Arrays  Why Dynamic Arrays?  A Dynamic Array Implementation  The Vector Class  Program Example  Array Versus Vector.
CS 106 Introduction to Computer Science I 10 / 04 / 2006 Instructor: Michael Eckmann.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Review Java.
CS 106 Introduction to Computer Science I 02 / 19 / 2007 Instructor: Michael Eckmann.
Java Unit 9: Arrays Declaring and Processing Arrays.
03/16/ What is an Array?... An array is an object that stores list of items. Each slot of an array holds an individual element. Characteristics.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Random, Collections & Loops Chapter 5 Copyright © 2012 Pearson Education, Inc.
Lists in Python.
Arrays (Part 1) Computer Science Erwin High School Fall 2014.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
04/29/ Introduction to Vectors?... A vector is a dynamic array. - It can be expanded and shrunk as required - A Component of a vector can be accessed.
CSC 142 J(part 1) 1 CSC 142 The ArrayList class [Reading: chapter 10]
ArrayList, Multidimensional Arrays
Object Oriented Programming Lecture 5: Arrays and Strings Mustafa Emre İlal
JAVA Array 8-1 Outline  Extra material  Array of Objects  enhanced-for Loop  Class Array  Passing Arrays as Arguments to Methods  Returning Arrays.
More arrays Primitive vs. reference parameters. Arrays as parameters to functions.
What is an Array? An array is a collection of variables. Arrays have three important properties: –group of related items(for example, temperature for.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Lecture 5: Arrays A way to organize data MIT AITI April 9th, 2005.
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.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
8-1 Chapter 8: Arrays Arrays are objects that help us organize large amounts of information Today we will focuses on: –array declaration and use –bounds.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
An Introduction to Java – Part 1 Dylan Boltz. What is Java?  An object-oriented programming language  Developed and released by Sun in 1995  Designed.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
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.
Title Slid CSC 444 Java Programming Arrays By Ralph B. Bisland, Jr.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
Arrays Chapter 12. Overview Arrays and their properties Creating arrays Accessing array elements Modifying array elements Loops and arrays.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
int [] scores = new int [10];
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];
CS 116: Object Oriented Programming II. Topics Vectors Multidimensional Arrays ArrayList.
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
Week 6 - Friday.  What did we talk about last time?  Loop examples.
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
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.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
19-Mar-16 Collections and ArrayLists.. 2 Collections Why use Collections. Collections and Object-Orientation. ArrayLists. Special Features. Creating ArrayLists.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Data Structures & Algorithms CHAPTER 2 Arrays Ms. Manal Al-Asmari.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter VII: Arrays.
A simple way to organize data
An Introduction to Java – Part I, language basics
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.
Object Oriented Programming in java
The Vector Class An object of class Vector is similar to an array in that it stores multiple values However, a vector only stores objects does not have.
Dr. Sampath Jayarathna Cal Poly Pomona
Arrays in Java.
Building Java Programs
Arrays and ArrayLists.
Presentation transcript:

1.00/ Lecture 8 Arrays and Vectors

Arrays-1 Arrays are a simple data structure Arrays store a set of values of the same type – Built-in types (int, double, etc.) or – Objects (Students, Dates, etc.) Arrays are part of the Java® language – Arrays are objects, not primitives like int or double. – They are declared in the same way as other objects int[] intArray= new int[20]; – The array object has an integer data member, length, that gives the number of elements in the array: int aSize= intArray.length;// aSize= 20 Each value is accessed through an index intArray[0]= 4; intArray[1]= 77;

Arrays, p.2 – Array indexes start at 0, not 1 An array with N slots has indices 0 through N-1 intArray has elements intArray[0] through intArray[19] – Array lengths cannot be changed once they are declared – Arrays can be initialized when declared int[] intArray= {5, 77, 4, 9, 28, 0, -9}; // Note that ‘new’ is implicit (not needed) in this case – Arrays of numerical values are zero when constructed

Arrays, p.3 – To copy an array, use arraycopy() method int[] newArray= new int[15]; // Can be diff size // arraycopy(fromArray, fromIndex, toArray, toIndex, count) System.arraycopy(intArray, 0, newArray, 0, 15); // Now intArray and newArray have separate copies of data – If we had just defined newArray without copying: int[] newArray= intArray; newArray[2]= -44;// This sets intArray[2]= -44 also // intArray and newArray would just be two names for the // same array. Remember in Java references refer to // objects – You can create 2, 3,..n dimensional arrays in Java®. int[ ][ ] twoDArray = new int[5][10];

Test Your Knowledge 1. Which of the following expressions does not declare and construct an array? a. int[ ] arr = new int[4]; b. int[ ] arr; arr = new int [4]; c. int[ ] arr = {1,2,3,4}; d. int[ ] arr; 2. Given this code fragment: int j= ?; int[] data = new int[10]; System.out.print(data[ j ]); Which of the following is a legal value of j? a.-1 b.0 c.1.5 d.10

Test Your Knowledge 3. Given this code fragment: int[] arrayA = new int[4]; int[] arrayB; arrayB = arrayA; arrayB[2]=4; arrayA[0]=arrayB[2]; What are the values of the elements in array A? a. unknown b. 0,0,0,0 c. 4,0,4,0 d. 4,0,0,0 4. How many objects are present after the following code fragment has executed? float[] arrayA = new float[10]; float[] arrayB; arrayB = arrayA; a.1 b.2 c.10 d.20

Test Your Knowledge 5. For which of these applications an array is NOT suitable? a.Holding the scores on 4 quarters of a Basketball game b.Holding the name, account balance and account number of an individual c.Holding temperature readings taken every hour through a day d. Holding monthly expenses through a year 6. Given the following code fragment: int[] data = {1,3,5,7,11}; for(______________________) System.out.println(data[index] ); Fill in the blanks so that the program prints out every element in the array in order a. int index = 4; index>0; index-- b. int index=0; index<4; index++ c. int index=0; index<data.length(); index++ d. int index=0; index<data.length; index++

Test Your Knowledge 7. What is the output of the following program? class Test{ public static void main ( String[] args ){ int value = 10; int[] arr = {10,11,12,13}; System.out.println("value before:"+value); alterValue( value ); System.out.println("value after:"+value); System.out.println("arr[0]before:"+arr[0]); alterArray( arr ); System.out.println("arr[0] after:"+arr[0]); } public static void alterValue (int x ){ x = 0; } public static void alterArray (int[]a){ a[0] = 0; } } a.value before:10 value after:0 arr[0] before:10 arr[0] after: 0 b. value before:10 value after:10 arr[0] before:10 arr[0] after: 10 c. value before:10 value after:10 arr[0] before:10 arr[0] after: 0 d. value before:10 value after:0 arr[0] before:10 arr[0] after: 10

Example-Computing an Average Given a list of numerical data items, store them in an array and compute the average value. We’ll use a for loop to iterate over the array entries. We’ll put the computation of the average in a separate method.

Computing Test Averages public class AverageTest { public static void main(String args[ ]) { double[ ] testScores = new double[4]; testScores[0] = 80.0; testScores[1] = 50.5; testScores[2] = 90.0; testScores[3] = 75.0; System.out.println("Average is: " + average(testScores)); } public static double average(double[ ] aDouble) { double aver = 0.0; // initialize value for(int i=0; i<aDouble.length; i++) aver += aDouble[i]; // accumulate sum of values return(aver/aDouble.length); //return average }

Example A. Create a TestArray class to store and manage temperatures for a week B. Start writing main(): – Declare and construct an array of doubles, called dailyTemp holding daily temperature data Use an initializer list with braces { } MonTueWedThuFriSatSun – Using a for loop, print every element of the dailyTemp array in reverse order (starting from Sunday and going backwards to Monday)

public class TestArray { public static void main(String args[]) { int[] dailyTemp = {70,61,64,71,66,68,62}; for (int i=dailyTemp.length-1; i>=0; i--) System.out.println(dailyTemp[i]); }

Vectors Vector class is a fancy version of an array – Vector can grow automatically as needed Has capacity that is increased when needed Has size, which is the actual number of elements – Vector can hold elements of different types As long as each is an Object (reference), Vector can’t hold a basic type (not an int, double, etc.) ! You will use type casts or wrapper classes in Vectors – Wrappers are objects (e.g., Double) that hold built-ins

Vectors Vectors are not in the core language They are in package java.util, which you must import: import java.util.*;// At top of program Vectors are slightly slower than arrays Matters only in large scale numerical methods Vectors have many methods you can use

Vector Methods Void addElement (Object o) int capacity() Object elementAT (int i) int indexOf (Object o) void insertElementAt(Object o, int i) boolean isEmpty() void removeElementAt(int i) void setElementAt(Object o, int i) int size() Adds object to end of vector, increases vector size by one Returns capacity of vector Returns object at index i Finds first occurrence of object; uses equals method Inserts object at index i Returns true if vector has no objects, false otherwise Deletes object at index i Sets vector element at index I to be the specified object Returns size of vector

Vector Constructors Three basic forms (method overloading): – Vector() Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero. Capacity will double whenever increased. – Vector(int initialCapacity) Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero. Capacity will double whenever increased. – Vector(int initialCapacity, int capacityIncrement) Constructs an empty vector with the specified initial capacity and capacity increment

A Vector Example We will show a program that generates a random number of lines with random start and end points. We’ll use a Vector object to hold the lines, and use Vector methods to control loop through the contents of the Vector

Line class import java.awt.*; public class Line { int x1,y1; // coordinates of start of line int x2,y2; // coordinates of end of line // constructor method for Line public Line(Point p1, Point p2) { // Point class in AWT x1 = p1.x; y1 = p1.y; x2 = p2.x; y2 = p2.y; } public void showLine() // Method to draw line segment { System.out.println("Coordinates are: ("+ x1+","+ y1+"),("+ x2+","+ y2+")" ); } } // end of class Line

VectorExample class import java.awt.*; import java.util.*; public class VectorExample { static final double MAXCOORD = ; static final int MAXLINES = 30; public static void main(String args[ ]) { int numLines = (int) (Math.random()*MAXLINES); Vector vec = new Vector(); for (int i=0; i< numLines;i++) { Line curLine = new Line( new Point((int)(Math.random()*MAXCOORD), (int)(Math.random() * MAXCOORD) ), new Point( (int)(Math.random()*MAXCOORD), (int) (Math.random() * MAXCOORD))); vec.addElement(curLine); } System.out.println ("Vector size: "+vec.size()); for (int i=0; i<vec.size(); i++) ((Line) vec.elementAt(i)).showLine(); } } // end of VectorExample

Test Your Knowledge 1.Which of the following statements is NOT true about Vectors? a. Vectors are slightly faster than arrays. b. Vectors can store elements of different types. c. Vectors can increase in size to store more elements. d. Vectors have methods to manage their content. 2. Considering myVector is a Vector that has been declared and constructed, which of the following expressions is always true? a.myVector.size() >= myVector.capacity() b.myVector.size() > myVector.capacity() c.myVector.capacity() >= myVector.size() d. myVector.capacity() > myVector.size()

Test Your Knowledge 3. What is the output of the following code fragment? Vector myVector = new Vector(2); myVector.addElement(new Integer(1)); myVector.addElement(new Integer(2)); myVector.addElement(new Integer(3)); System.out.println(myVector.size()+",“+ myVector.capacity()); a. 2, 3 b. 3, 2 c. 3, 4 d. 3, 3

Test Your Knowledge 4. Given the following code fragment: Vector myVector = new Vector(); myVector.addElement("One"); myVector.addElement("Two"); myVector.addElement("Three"); myVector.addElement("Four"); Which one of the following expressions will modify myVector so it looks like: One; Two; Four a. myVector.removeElementAt(myVector.elementAt(3)); b. myVector.removeElementAt(myVector.indexOf("Three")); c. myVector.removeElementAt(3); d. myVector.removeElementAt(myVector.elementAt(2));

Test Your Knowledge 5. Given the code fragment of question 4, which one of the following expressions will modify myVector so it looks like: One; Two; Three; Five a. myVector[3] = "Five" b. myVector[4] = "Five" c. myVector.setElementAt("Five", myVector.indexOf("Four")); d. myVector.setElementAt("Four", myVector.indexOf("Five")); 6. Given the code fragment of question 4, which one of the following expressions will modify myVector so it looks like: One; Two; Three a. myVector.removeElementAt(2); b. myVector.removeElementAt(myVector.lastElement()); c. myVector.removeElementAt(myVector.capacity()); d. myVector.removeElementAt(myVector.size()-1);

Test Your Knowledge 7. Given the following code fragment: Vector myVector = new Vector(); myVector.addElement(new Integer(1)); myVector.addElement(new Integer(3)); myVector.addElement(new Integer(7)); Which one of the following expressions will modify myVector so it looks like: a. myVector.addElementAt[new Integer(5)]; b. myVector.insertElementAt[new Integer(5), 2]; c. myVector.insertElementAt[5, 2]; d. myVector.insertElementAt[5, 3];

A. Problem description – We want to store student names in a subject. MIT subjects have between 1 and 900 students, so it’s hard to anticipate the size of an array to hold the data. We will use a Vector, since it can be dynamically sized. B. Write the Java® code. – 1. Name your class MITCourse. – 2. In its main() method: Create a Vector students with capacity 5 Add 4 students “Amy”, “Bob”, “Cindy” and “David” to the Vector. These students are Strings. Add them to the Vector directly; don’t declare 4 String variables. Exercise

Exercise, p.2 –3. Write a method to print all the elements in the vector and its size and capacity. Add a method printOutVector to the Course100 class: public static void printOutVector(Vector vec) { // Code goes here } – 4. Call printOutVector() method from main(). Pass the students Vector as the argument – 5. Your output should be: Amy Bob Cindy David Size: 4 Capacity: 5 Java ® is a trademark or registered trademark of Sun Microsystems, Inc. in the United States and other countries.