1 ArrayList Starring: Purse, Sr. Co-Starring: Purse, Jr. Poe Numbers.

Slides:



Advertisements
Similar presentations
Chapter 23 Organizing list implementations. This chapter discusses n The notion of an iterator. n The standard Java library interface Collection, and.
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.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Chapter 10 Introduction to Arrays
Lecture 8 CS203. Implementation of Data Structures 2 In the last couple of weeks, we have covered various data structures that are implemented in the.
CS 106 Introduction to Computer Science I 04 / 30 / 2007 Last lecture :( Instructor: Michael Eckmann.
CS 106 Introduction to Computer Science I 04 / 27 / 2007 Instructor: Michael Eckmann.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Chapter 19 Java Data Structures
1 CSC 222: Computer Programming II Spring 2005 Searching and efficiency  sequential search  big-Oh, rate-of-growth  binary search  example: spell checker.
Abstract Data Types (ADTs) Data Structures The Java Collections API
Arrays And ArrayLists - S. Kelly-Bootle
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Introduction to Collections – Stacks Modified
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
AP CS Workshop ArrayList It is very common for applications to require us to store a large amount of data. Array lists store large amounts of data.
CS 106 Introduction to Computer Science I 04 / 25 / 2007 Instructor: Michael Eckmann.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Chapter 10 Strings, Searches, Sorts, and Modifications Midterm Review By Ben Razon AP Computer Science Period 3.
ArrayList, Multidimensional Arrays
Lists Ellen Walker CPSC 201 Data Structures Hiram College.
Chapter 11 Arrays Continued
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
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.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
Data Design and Implementation. Definitions of Java TYPES Atomic or primitive type A data type whose elements are single, non-decomposable data items.
1 Heaps and Priority Queues Starring: Min Heap Co-Starring: Max Heap.
Chapter 18 Java Collections Framework
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
1 Stacks and Queues Starring: IndexOutOfBOundsException Co-Starring: NoSuchElementException.
 A Collection class is a data type that is capable of holding a group of items.  In Java, Collection classes can be implemented as a class, along with.
M180: Data Structures & Algorithms in Java Arrays in Java Arab Open University 1.
CS 106 Introduction to Computer Science I 04 / 25 / 2008 Instructor: Michael Eckmann.
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
1 ArrayList Starring: Purse, Sr. Co-Starring: Purse, Jr. Poe Numbers.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
1 Heaps and Priority Queues v2 Starring: Min Heap Co-Starring: Max Heap.
Chapter 2 Collections. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Define the concept and terminology related.
Chapter 3 Collections. Objectives  Define the concepts and terminology related to collections  Explore the basic structures of the Java Collections.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Data Design and Implementation. Definitions Atomic or primitive type A data type whose elements are single, non-decomposable data items Composite type.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
IMPLEMENTING ARRAYLIST COMP 103. RECAP  Comparator and Comparable  Brief look at Exceptions TODAY  Abstract Classes - but note that the details are.
1 Algorithms Starring: Binary Search Co Starring: Big-O.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Generics Starring: Rite-Aid Aspirin Co-Starring: CVS Paper Plates.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Data Structures Arrays and Lists Part 2 More List Operations.
Collections Dwight Deugo Nesa Matic
1 The copy constructor in the BankAccounts class. Two alternatives here: /** copy constructor */ public BankAccounts(BankAccounts L){ theAccounts = L.theAccounts.clone();
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
LESSON 8: INTRODUCTION TO ARRAYS. Lesson 8: Introduction To Arrays Objectives: Write programs that handle collections of similar items. Declare array.
(like an array on steroids)
CSC 222: Object-Oriented Programming
Top Ten Words that Almost Rhyme with “Peas”
TCSS 143, Autumn 2004 Lecture Notes
ArrayLists 22-Feb-19.
Introduction to Data Structure
Presentation transcript:

1 ArrayList Starring: Purse, Sr. Co-Starring: Purse, Jr. Poe Numbers

2 Purpose: In this lecture series we will introduce the concept of a LIST. We will take a look at Java’s ArrayList class that implements Java’s List interface. The AP subset includes the ArrayList as part of the testable material on the AB exam.

3 Resources: Java.util.ArrayList Java Essentials Chapter 13 p.521 Java Essentials Study Guide Chapter 11 p.163 & Chapter 16 p.263 Java Methods Data Structures Chapter 2 p.33 APCS Course Description p.27 Paragraphs 2 & 3

4 Intro: In Computer Science II we discussed Arrays as well as Java’s Arrays class. With Arrays, we learned to use 1 and 2 dimensional arrays of primitives and objects, passing arrays as parameters, Bubble Sorting an array.

5 Intro: With the Arrays Java class (it is really a utility class), java.util.Arrays, we used it’s methods to sort & search (Binary Search) & compare its elements which can contain primitives or objects. This class works with existing user defined arrays.

6 Now we will take one step forward by discussing the Java ArrayList. This class introduces the concept of a List. The List is an ADT and will be discussed in greater detail when we learn about ADT’s & Data Structures.

7 AP AB Subset:Lets read the Course Description regarding ArrayList on page 27 (paragraphs 2 & 3)

8 What we will Cover in this Lecture: You will initially create YOUR OWN ArrayList and use it in a test application. Elements of a List A First look at the List interface java.util.List Arraylist: Where it fits in the Collections Hierarchy A Look at java.util.ArrayList Working with the ArrayList adding an element Get the Size Retrieve (Get) an Element Modify (Set) the State of an Element Remove an element Big-O of ArrayList Best Use for this type of Data Structure Wrapping Numbers What is critical for the AP Exam

9 TPS: Use the following files, located on the APCompSci WebPage, to create your own implementation of an ArrayList: MyArrayList.javaIs a class shell containing the methods you need to code UseMyArrayList.javaIs a sample Driver program (SPVM) that utilizes your ArrayList. It should execute as is. Download your COPY of these files, implement and test your version of MyArrayList

10 Elements of a List: A Look at the following diagram, one we will see MANY times throughout the year, shows a class Hierarchy. Lets focus on the List Interface Then we will look at a class, ArrayList, that implements the List interface.

11

12 On an ABSTRACT Level, a generic List contains a number of elements (values or objects) arranged in sequence from which we can locate a specific list element, add elements to the list and remove elements from the list. This is the framework or definition of an Abstract List Data Structure A List is an Abstract Data Type (ADT)

13 We could further define the List to be in some ordered sequence and include a behavior that permits an element to be placed “in order” onto the List This would be called an Ordered List This is merely a structure or a set of criteria that can be implemented different ways

14 We can have an Array implementation of the Abstract List Structure. All we need to do is make sure we provide for the BEHAVIORS as specified in the Criteria for a List (add, remove, get, size, modify) As we will see later in the year, we can provide other implementations such as a Linked List implementation

15 The specific implementation of an Abstract Structure depends on the needs of the system or problem you are attempting to resolve.

16 As we will see, we can evaluate the effectiveness of a specific implementation by evaluating its order of growth or Big-O. Each behavior of the List Structure that is implemented will carry a “COST” that is specific to the type of implementation. For example, Suppose we are asked to develop a system that requires us to maintain a list of students and the list was ordered by Last Name.

17 Now, in this system the Dominant behavior will be Searching for a specific student in the list. The list, once built, will not change much but it will be accessed frequently for student info.

18 In this case we need to implement a list with a Data Structure that minimizes the “cost” of searches. In this case we COULD design an ArrayList implementation because it has a low cost for finding a specific element (binary search or hash implementation).

19 The “cost” of a find behavior against an Ordered ArrayList would be Log N (Binary Search) or O( 1 ) (hash) That is much better than a “cost” of N (linear) if we used a Linked List implementation for this system. We will soon see that there are other options such as a Binary Tree implementation.

20 At this point, make sure you keep clear that we have a Concept that is an Abstract Data Structure (ADT) such as a List An Implementation of that ADT such as an ArrayList Each implementation must be evaluated against their relative “costs” when deciding which one to use for a particular system

21

22 The actual Java List interface includes many more methods, but for AP purposes, these are the ones we need to be able to work with although we are adding the Remove method As you can see, this interface merely identifies the behaviors that MUST exist in a List

23 The actual implementation of which is left to the specific data structure (ArrayList for example) For now, ignore the Iterator and ListIterator behaviors as we will discuss these at a later time.

24 Why is such an Interface Important ? What benefits, if any, does it provide ? What does a List limit its elements to be ?

25 Objects, You can only have a List that contains Objects, you CAN NOT have a List of primitive data types What can you do if your list needs to maintain integers or doubles ? Since, all classes extends from Object, you may fill in a List with any kind of object like Strings, arrays or instances of your own defined class

26 The List interface, as with other interfaces, does not define any Constructors that is left up to the class that implements this interface For the methods that remove or find a specific element they need to handle situations where the INDEX being sought is not in the range of the list In these instances, you need to throw an IndexOutOfBoundsException

27 Arraylist: Where it fits in the Collections Hierarchy: ArrayList implements the List interface therefore it MUST provide for behaviors for all of the methods in the interface A Look at java.util.ArrayList: public class ArrayList extends AbstractList implements List

28 class java.util.ArrayList  Notes: AP Computer Science AB students need to know that ArrayList implements List & which methods from ArrayList implement those specified by List.  Required methods specified by interface java.util.List ListIterator listIterator() (AB only) int size() boolean add(Object x)  Required methods not part of interface java.util.List Object get(int n) void set(int n, Object x) boolean add(int n, Object x) Object remove(int n)

29 Lets look at the java.util.ArrayList in the Java API (javadocs) Notice the Constructors and overloaded methods

30 Working with the ArrayList: In the previous lecture, Advanced Classes, we used the Coin and Purse example. The Purse had a Add method that simply accumulated the total value of coins in the purse However, it did NOT keep track of each individual Coin or Traveler Check

31 Suppose we were to modify the requirements of the Purse class to maintain information on EACH separate Coin in the Purse. How could we accomplish this ?

32 One way would be to maintain an Array of coins The limitation of this would be that, unless we knew how many Coins we would have the array would be too big or too small

33 We might have to repeatedly have to re size the array (reallocate new space) to handle a large number of Coins. Also, if we needed to obtain a specific Coin in the array or modify a specific Coin we would need to write that code from scratch This is where the ArrayList comes in

34 We could maintain an ArrayList of objects that implement the Top Interface In the Purse class we would add a new class level attribute and modify the constructor: private ArrayList myArray; public Purse () { myArray = new ArrayList(100); // initial capacity of 100 objects }

35 This array list can hold any type of object but we will limit it to any object that implements the Top interface We then would need to maintain the elements every time the user added a new coin or travelers check to the purse:

36 Adding an element: We are adding an instance of a class that implements the Top interface to the ArrayList public void add(Top ci) { // code here if (count == 0 || max.getTop() < ci.getTop() ) { max = ci; } count++; sum += ci.getTop(); // added for arraylist // add new "coin" or "TC" superobject to list myArray.add(ci); }

37 There is also an overloaded add method that adds an object at a specified index, sliding all elements at that index and higher up one element --- TRY THIS ONE ON YOUR OWN

38 Get the Size: Instead of using the count attribute, we can use the ArrayList’s size method public int getCount() { // return count; return myArray.size(); }

39 Retrieve (Get) an Element: public Object getElement(int i) { return myArray.get(i); } Realize that the get method of ArrayList returns a generic Object reference You must cast this return type to the appropriate child / sub class before using it

40 SPVM… Object o = myPurse.getElement(1); if (o instanceof Coin) { System.out.println("the 2nd element in the Purse is a Coin"); } o = myPurse.getElement(2); if (o instanceof TravelerCheck) { System.out.println("the 3rd element in the Purse is a TC"); } The output results in both out messages being displayed

41 Modify (Set) the State of an Element : This method mutates an existing object in the ArrayList It accepts an index and an Object and returns the object that was replaced Set can only overwrite existing values and NOT create new elements in the List

42 public Object setElement(int e, Object o) { return myArray.set(e, o); } SPVM… // modify an element -- replace a Coin with a TC o = myPurse.setElement(0, myStuff[2]); if (o instanceof Coin) { System.out.println("the 1st element was a Coin"); }

43 Remove an element: This method will remove a given element from the list and return it It will move all elements from the index removed forward up one place and reduce the logical size of the List by 1

44 public Object RemoveElement(int i) { return myArray.remove(i); } SPVM…

45 // remove an element o = myPurse.RemoveElement(1); if (o instanceof Coin) // TRUE { System.out.println("the 2nd element Coin is removed"); } System.out.println("There are " + myPurse.getCount() + " Objects in the Purse"); o = myPurse.getElement(2); // the result is an IndexOutOfBoundsException // as there are now only 2 elements in the // ArrayList

46 TPS:How Can we display the contents of the Purse ?

47 ANS: //Add to SuperObject: public String toString() { return myName; } Add to Purse: public String toString() { String s = " "; for(int x = 0; x < myArray.size(); x++) { s += ((SuperObject)myArray.get(x)).toString(); s += " "; } return s; }

48 Call in SPVM: // display the types of objects in the purse String ss = myPurse.toString(); System.out.println("the elements in the purse are now " + ss);

49 Big-O of ArrayList: The “cost” of an operation Big-o of different options (AVERAGE CASE): addcontains removesizeconstructor NN N11 Arraylist(uniqueness) 1N or N*M NN 1 ArrayList(all dups)

50 NLogN M20 Be aware that there are “hidden” details that occur on an ArrayList that are Abstracted from the user of this type of list implementation. The overloaded Add method requires the ArrayList to MOVE many elements down the list when a new item is added somewhere inside the list. This effects efficiency

51 The same can be said for the Remove method In the worst case almost ALL of the elements need to be shifted The get and set methods operate in constant time O (1) as regardless of the list size, they require one step and are, therefore, extremely efficient

52 Best Use for this type of Data Structure: This data structure is excellent in situations where the actual size of the elements is not known until the program executes, but once established remains stable This structure is also best used in cases where specific elements are frequently modified

53 When finding the value of a specific element index is frequently performed When you add objects to the end of the list When removing a specific object (index) is frequently performed

54 TPS:How would you store Numbers in an ArrayList ? Java Essentials chapter 13 Section 3 p.530

55 Wrapping Numbers: ArrayLists MUST contain objects What if we need to maintain a list of simple numbers ? You must “wrap” these primitives in a child of the Number class

56 Tips for the AP Exam: Elements of a list start at index 0 Make sure any iteration on a list does not go out of bounds ArrayLists store Objects and to access these objects, you must cast them to the appropriate type

57 Using equals with Array Lists uses the default Object equals and compares references and NOT contents. So it returns TRUE if two ArrayList elements are the same, otherwise it returns false

58 Projects: NewPurse ListOfNumbers

59 TEST FOLLOWS THE PROJECT DUE DATE !!!