Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 ArrayList Starring: Purse, Sr. Co-Starring: Purse, Jr. Poe Numbers."— Presentation transcript:

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

2 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 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 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 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 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 7 AP AB Subset:Lets read the Course Description regarding ArrayList on page 27 (paragraphs 2 & 3)

8 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 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 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 11

12 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 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 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 15 The specific implementation of an Abstract Structure depends on the needs of the system or problem you are attempting to resolve.

16 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 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 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 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 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 21

22 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 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 24 Why is such an Interface Important ? What benefits, if any, does it provide ? What does a List limit its elements to be ?

25 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 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 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 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 29 Lets look at the java.util.ArrayList in the Java API (javadocs) Notice the Constructors and overloaded methods

30 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 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 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 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 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 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 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 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 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 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 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 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 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 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 44 public Object RemoveElement(int i) { return myArray.remove(i); } SPVM…

45 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 46 TPS:How Can we display the contents of the Purse ?

47 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 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 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 50 NLogN 83 102410 1M20 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 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 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 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 54 TPS:How would you store Numbers in an ArrayList ? Java Essentials chapter 13 Section 3 p.530

55 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 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 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 58 Projects: NewPurse ListOfNumbers

59 59 TEST FOLLOWS THE PROJECT DUE DATE !!!


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

Similar presentations


Ads by Google