Recitation 3/27/2009 CS 180 Department of Computer Science, Purdue University.

Slides:



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

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
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;
BUILDING JAVA PROGRAMS CHAPTER 10.1 ARRAY LISTS. 22 OBJECTIVES! Use ArrayList to construct and analyze lists of arbitrary length.
Arrays and ArrayLists Ananda Gunawardena. Introduction Array is a useful and powerful aggregate data structure presence in modern programming languages.
Chapter 10 Introduction to Arrays
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Sections 1-4.
Arrays.
Arrays. Memory organization Table at right shows 16 bytes, each consisting of 8 bits Each byte has an address, shown in the column to the left
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
©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.
Hash Tables1 Part E Hash Tables  
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
Generics and Type Safety Recitation – 4/24/2009 CS 180 Department of Computer Science, Purdue University.
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.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Alice in Action with Java
CS180 Recitation 25th/26th October, 2007 Department of Computer Science, Purdue University.
CS 206 Introduction to Computer Science II 11 / 12 / 2008 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 10 *Arrays with more than one dimension *Java Collections API.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 10 Arrays Lists.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
Chapter 9 Introduction to Arrays
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
The Java Collections Framework (JCF) Introduction and review 1.
French Territory of St. Pierre CSE 114 – Computer Science I Arrays.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Problem Solving using the Java Programming Language May 2010 Mok Heng Ngee Day 5: Arrays.
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.
Arrays : Objectives After you have read and studied this chapter, you should be able to –Manipulate a collection of data values, using an array. –Declare.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
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.
Hash Tables1   © 2010 Goodrich, Tamassia.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
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.
© 2004 Goodrich, Tamassia Hash Tables1  
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
Hashing as a Dictionary Implementation Chapter 19.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
Lecture 9: Lists MIT-AITI Kenya © 2005 MIT-Africa Internet Technology Initiative In this lecture we will learn…. ArrayList – These are re-sizeable.
CS 180 Recitation 7 Arrays. Used to store similar values or objects. An array is an indexed collection of data values of the same type. Arrays are the.
COMP More About Arrays Yi Hong June 05, 2015.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
int [] scores = new int [10];
Arrays (part 2) 1 -Based on slides from Deitel & Associates, Inc. - Revised by T. A. Yang.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
CSE 143 Lecture 11: Sets and Maps reading:
Chapter 9 Introduction to Arrays Fundamentals of Java.
1 Java Review Outline Java Primitives, Program Structure Operators, Control Flow, Loops Classes and Objects Arrays and ArrayList Most of these slides are.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
Chapter VII: Arrays.
Sixth Lecture ArrayList Abstract Class and Interface
Fundamentals of Java: AP Computer Science Essentials, 4th Edition
ArrayLists.
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
int [] scores = new int [10];
Arrays.
Presentation transcript:

Recitation 3/27/2009 CS 180 Department of Computer Science, Purdue University

2 Announcements & Reminders Project 6 milestone is due today! Project 6 final due April 1st. Ask questions and spend time on this project -- do not underestimate this project or any other project here on out. Project 7 will be put out the morning of April 2nd. Exam 2 Multiple Choice Stats: avg , std. dev , median - 26, max. - 38, min. - 14; programming questions yet to be graded.

Basics Arrays are an indexed collection of data values all of the same type e.g An array of length 20 -

Arrays of Primitive Data Types Array Declaration [ ] //variation 1 [ ] //variation 2 Array Creation = new [ ] Example

Arrays of Objects In Java, in addition to arrays of primitive data types, we can declare arrays of object references. An array of primitive data is a powerful tool, but an array of object references is even more powerful.  Let’s look at an example

Array data type An array with elements of type GraduateStudent is a new data type represented as GraduateStudent[ ] int [ ] age; double salary[ ]; //less than minimum wage Person student[ ];  age is of type int[]  salary is of type double []  student is of type Person [] Each element of this array is of type GraduateStudent  age[0] is an int. salary[3] is a double.  student [1] is a Person.

Array Initialization It is possible to declare and initialize an array at the same time. It is also common to initialize an array using a for loop.

Index of an array An index for an array can move between indices 0 and length – 1 at most. An index outside of this range will throw an ArrayIndexOutOfBoundsException This does not need to be caught, but the program will terminate if it’s not. Note:  Arrays have a public constant length which will tell you the length of an array Person[] a = new Person[17]; a.length == 17;

Array example 1 int[] values = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34}; String[] names = new String[5]; names[1] = “Jupiter”; names[3] = “Pluto”; for(i=0;i<values.length;++i) System.out.println(values[i] + “ “); System.out.println(names[values[values[3]]]);

Array Example2 Assume we have an array of double called numbers which has already been initialized. The average of the numbers is computed here- double sum = 0; for(int i = 0; i < numbers.length; i++){ sum += numbers[i]; } double average = sum/numbers.length;

Array Example3 – Array of objects public class Brady{ private String name; private int age; public Brady(String n, int a){ name = n; age = a; } public String getName(){ return name; } public int age(){ return age; } Brady[] bunch = new Brady[6]; bunch[0] = new Brady(“Bobby”, 8); bunch[1] = new Brady(“Cindy”, 7); bunch[2] = new Brady(“Peter”, 14); bunch[3] = new Brady(“Jan”, 13); bunch[4] = new Brady(“Marcia”, 15); bunch[5] = new Brady(“Greg”, 16); for(int i = 0; i < bunch.length; i++) { System.out.println(“Name: “ + bunch[i].getName() + “ Age: “ + bunch[i].getAge()); }

Variable Size Declaration In Java, we are not required to declare the size at compile time. The size of an array can be specified as a variable as shown below:

Passing Arrays to Methods When arrays are passed as arguments, the address of the array is copied to the parameter. Example: float arrayOne[] = new float[10];

Arguments and Return Values An array can be returned by a method. The return type must be an array in this case. public int[ ] evenIntValues(int [ ] inArray) int[] array = new int[ 50 ]; int[] y = evenIntValues ( array );

Two-Dimensional Arrays Two-dimensional arrays are useful in representing tabular information. 2-dimensional arrays are usually represented in a row-column approach

Declaring and Creating a 2-D Array Declaration  [][] //variation 1  [][] //variation 2 Creation  = new [ ][ ] Example int [][] array; array = new int[4 ][5]; array

More on 2-d arrays A 2-d array is essentially an array of arrays The subarrays may have different lengths

2-d arrays example Subarrays of different lengths Executing triangularArray = new double[4][ ]; for (int i = 0; i < 4; i++) triangularArray[i] = new double [i + 1]; results in an array that looks like:

19 A More Involved Example /*assume numRows and numCols are greater than 3*/ int[][] a = new int[numRows][numCols]; for(int i =0; i<numRows; i+=2){ for(int j=0; j<numCols; j++){ a[i][j] = 1; } for(int[] row : a){ for(int colOfRow : row){ System.out.print(colOfRow); } System.out.println(); } for(int i=1; i < numRows-1; i++){ for(int j=1; j < numCols-1; j++){ System.out.println("at cell ("+i+","+j+")"); if(a[i-1][j] == 1){ System.out.println("see 1 at top"); } if(a[i+1][j] == 1){ System.out.println("see 1 at bottom"); } System.out.println(); } 19

Limitation of Arrays Once an array object is created, its size is fixed -- it cannot be changed. To overcome this, we can use Lists or Maps.

Lists and Maps The java.util standard package contains different types of classes for maintaining a collection of objects. These classes are collectively referred to as the Java Collection Framework (JCF). JCF includes classes that maintain collections of objects as sets, lists, or maps.

The List interface The List interface supports methods to maintain a collection of objects as a linear list. We can add to, remove from, and retrieve objects in a given list. A list does not have a set limit to the number of objects we can add to it. The ArrayList class uses an array to manage data. The LinkedList class uses a technique called linked-node representation.

List Methods Here are a few list methods:

List example 1 list = new ArrayList(); list.add("a"); // Append an element to the list // list - (a) list.add(0, "b"); // Insert an element at the head of the list // list - (b,a) int size = list.size(); // Get the number of elements in the list // size - 2

List example 1 (contd.) Object element = list.get(list.size()-1); // Retrieving the element at the end of the list // element returned- a list element = list.get(0); // Retrieving the element at the head of the list // element returned- b boolean b = list.remove("b"); // Remove the first occurrence of an element // b - true, list – (a) element = list.remove(0); // Remove the element at a particular index // list – (), element - a

JCF Maps JCF includes the Map interface that supports methods to maintain a collection of objects (key, value) pairs called map entries.

Map Methods Here are a few Map methods:

Map example Map map = new HashMap(); // hash table //Add key/value pairs to the map map.put("a", new Integer(1)); map.put("b", new Integer(2)); map.put("c", new Integer(3)); // Get number of entries in map int size = map.size(); // size - 3 // Adding an entry whose key exists in the map causes the new value to replace the old value Object oldValue = map.put("a", new Integer(9)); // oldValue - 1

Map example (contd) int value = map.get(“a”); // value - 9 // Remove an entry from the map and return the value of the removed entry oldValue = map.remove("c"); // 3

30 Before the Quiz! Your next lab will consist of programming a LEGO robot! If you’ve never logged on to a CS Windows machine, you’ll need to:  Retrieve your initial password from (after logging in with your career account, see “My Accounts” on the left)  Go to LWSN B160 & try to log on with your initial password  You’ll be asked to change your Windows account password (it’s different from your password on your lore account)  Be sure to change your password & remember it! 30

31 Quiz How would I instantiate an array to store 100 real value points from a 3-dimensional space? 31