Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.

Similar presentations


Presentation on theme: "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by."— Presentation transcript:

1 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Chapter 18: Collections With formatting and other updates by Dr. L. Lilien

2 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2 Chapter Topics 18.1. Introduction to the Java Collections Framework 18.2. Lists 18.3. Sets 18.4. Maps 18.5. The Collections Class Updated by L. Lilien

3 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 3 18.1. Introduction to the Java Collections Framework Collection -- an object which can store other objects Collection elements -- objects in a collection Collections provide methods for adding and removing elements, for searching for a particular element within the collection.etc. Java Collections Framework (JCF) -- a library of classes and interfaces for working with collections of objects Updated by L. Lilien

4 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 4 The Main Types of Collections Lists – covered in good detail Sets – not covered Maps – not covered Updated by L. Lilien

5 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5 Lists List assigns an index (an integer ) to each element stored Indices of elements are: 0 for the element at the beginning of the list, 1 for the next element … and so on Lists permit duplicate elements They are distinguished by their position in the list Updated by L. Lilien

6 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 6 ++ SKIP++ Sets Set: a collection with no notion of position within the collection for stored elements. Sets do not permit duplicate elements. Updated by L. Lilien

7 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 7 ++ SKIP++ Maps A map is a collection of pairs of objects: 1.A value: this is the object to be stored. 2.A key: this is another object associated with the value, and which can be used to quickly find the value within the collection. A map is really a set of keys, with each each key having a value attached to it. Maps do not allow duplicate keys. Updated by L. Lilien

8 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 8 Part of the JCF Hierarchy Updated by L. Lilien

9 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 9 The Collection Interface Comments on the Collection Interface: Lists and Sets are similar in many ways The Collection Interface describes the operations that are common to both Maps are fundamentally different from Lists and Sets and are described by a different interface Updated by L. Lilien

10 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 10 Some Methods in the Collection Interface MethodDescription add(o : E) : booleanAdds an object o to the Collection. Returns true if o is successfully added to the collection, false otherwise. clear() : voidRemoves all elements from the collection. contains(o : Object): boolean Returns true if o is an element of the collection, false otherwise. isEmpty() : booleanReturns true if there are no elements in the collection, false otherwise. iterator() : Iterator Returns an object called an iterator that can be used to look at all elements stored in the collection. remove(o : Object) : boolean Removes the object o from the collection and returns true if the operation is successful, false otherwise. size() : intReturns the number of elements currently stored in the collection.

11 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11 Iterators Iterator -- an object associated with a collection. Provides methods for fetching the elements of the collection, one at a time, in some order. Iterators also have a method for removing from the collection the last item fetched Updated by L. Lilien

12 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 12 AbstractCollection The AbstractCollection class provides a skeleton implementation for a Collection class By implementing many of the methods of the Collection interface. We can create our own collection class by providing implementations for: iterator() size() and overriding add(o : Object) Updated by L. Lilien

13 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 13 18.2. Lists

14 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 14 The List Interface The List interface is derived from the Collection interface Derived by adding operations that are specific to the position-based, index-oriented nature of a list Updated by L. Lilien

15 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 15 List Interface Methods List interface has methods for: adding elements to the list removing elements from the list based on the index of the element Also has methods for finding the index of an element in the list when the value of an element is known Updated by L. Lilien

16 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 16 The List Interface Methods add(index:int, el:E) : voidAdds the element el to the collection at the given index. Throws IndexOutOfBoundsException if index is negative, or greater than the size of the list. get(index:int):EReturns the element at the given index, or throws IndexOutBoundsException if index is negative or greater than or equal to the size of the list. indexOf(o:Object):intReturns the least (first) index at which the object o is found; returns -1 if o is not in the list. lastIndexOf(o:Object):intReturns the greatest (last) index at which the object o is found; returns -1 if o is not in the list. listIterator():ListIterator Returns an iterator specialized to work with List collections. remove(index:int):ERemoves and returns the element at the given index; throws IndexOutOfBoundsException if index is negative, or greater than or equal to the size of the list. set(index:int, el:E):EReplaces the element at index with the new element el.

17 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 17 AbstractList AbstractList -- an abstract class that provides a skeletal implementation of a List collection It extends AbstractCollection and implements the List interface It is the abstract superclass for the concrete classes ArrayList and Vector Updated by L. Lilien

18 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 18 ArrayList ArrayList is an array-based list So, internally, ArrayList uses an array to store its elements When it gets full, a new, bigger array is created, and the elements are copied to the new array Updated by L. Lilien

19 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 19 ++SKIP++ Vector Vector is also an array-based list So, internally, Vector uses an array to store its elements When it gets full, a new, bigger array is created, and the elements are copied to the new array Vector has higher overhead than ArrayList because Vector is synchronized to make it safe for use in programs with multiple threads Updated by L. Lilien

20 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 20 The Iterator Interface Iterators are objects implementing the Iterator interface Iterator interface specifies the following methods: hasNext() : boolean next() : E remove() : void The remove() method is optional, so not all iterators have it. Updated by L. Lilien

21 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 21 Methods of the Iterator Interface MethodDescription hasNext() : booleanReturns true if there is at least one more element from the collection that can be returned, false otherwise. next() : EReturns the next element from the collection. remove() : voidRemoves from the collection the element returned by the last call to next(). This method can be called at least one time for each call to next().

22 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 22 AbstractSequentialList and LinkedList Array-based lists have high overhead for inserting or deleting elements in the middle of the list (i.e., at positions that are not at the beginning or the end of the list) LinkedList eliminates this high overhead LinkedList is a concrete class It stores elements in a way that eliminates the high overhead of adding to, and removing from positions in the middle of the list LinkedList extends AbstractSequentialList, which in turn, extends AbstractList Updated by L. Lilien

23 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 23 Using the Concrete List Classes The concrete classes ArrayList, Vector, and LinkedList work in similar ways but have different performance characteristics Because they all implement the List interface, you can use List interface references to instantiate and refer to the different concrete classes Using a List interface instead of the concrete class reference allows you to later switch to a different concrete class to get better performance (should you need to do so) Updated by L. Lilien

24 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 24 Example: Switching from ArrayList to Linked List Using List interface reference to instantiate ArrayList import java.util.*; public class Test1 { public static void main(String [ ] args) { List nameList = new ArrayList (); String [ ] names = {"Ann", "Bob", "Carol"}; // array // Add (from array) to ArrayList for (int k = 0; k < names.length; k++) nameList.add(names[k]); // Display contents of ArrayList for (int k = 0; k < nameList.size(); k++) System.out.println(nameList.get(k)); } Updated by L. Lilien

25 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 25 Continuing - Example: Switching from ArrayList to Linked List Because we used a List reference to refer to the concrete class objects, we can easily switch from an ArrayList (the previous slide) to a LinkedList (the next slide) The only change is in the class used to instantiate the collection Updated by L. Lilien

26 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 26 Using List interface reference to instantiate LinkedList import java.util.*; public class Test2 { public static void main(String [ ] args) { List nameList = new LinkedList (); String [ ] names = {"Ann", "Bob", "Carol"}; // array // Add (from array) to linked list for (int k = 0; k < names.length; k++) nameList.add(names[k]); // Display contents of linked list for (int k = 0; k < nameList.size(); k++) System.out.println(nameList.get(k)); } Continuing - Example: Switching from ArrayList to Linked List Updated by L. Lilien

27 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 27 Using an Iterator To use an iterator with a collection (code listing CL 18-2, p.1065): 1.Call the iterator():Iterator method To retrieve an iterator object 2.Use the hasNext():boolean method To see if there still remain elements to be returned Then use the next():E method To return the next available element 3.If desired, use the remove():void method To remove the element returned by next() remove() removes the element returned by the last call to next() remove() can be called at most one time for each call to next() Updated by L. Lilien

28 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 28 Using an Iterator import java.util.*; public class Test3 { public static void main(String [ ] args) { List nameList = new ArrayList (); // an ArrayList String [ ] names = {"Ann", "Bob", "Carol"}; // an array // Add (from array) to ArrayList (not using the iterator) for (int k = 0; k < names.length; k++) nameList.add(names[k]); // iterator NOT used // Display contents of ArrayList using an iterator Iterator iter = nameList.iterator(); // get the iterator, call it iter while (iter.hasNext()) // use the iterator iter System.out.println(iter.next()); } Updated by L. Lilien

29 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 29 ListIterator The ListIterator extends Iterator (Fig. 18-6, p.1064) Among others, ListIterator adds methods for moving backward through the list In addition to the methods for moving forward that are provided by Iterator hasPrevious() : boolean previous() : E Updated by L. Lilien

30 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 30 Some ListIterator Methods MethodDescription add(el:E):voidAdds el to the list at the position just before the element that will be returned by the next call to the next() method. hasPrevious():booleanReturns true if a call to the previous() method will return an element, false if a call to previous() will throw an exception because there is no previous element. nextIndex():intReturns the index of the element that would be returned by a call to next(), or the size of the list if there is no such element. previous():EReturns the previous element in the list. If the iterator is at the beginning of the list, it throws NoSuchElementException. previousIndex():intReturns the index of the element that would be returned by a call to previous(), or -1. set(el:E):voidReplaces the element returned by the last call to next() or previous() with a new element el.

31 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 31 Iterator Positions Think of an iterator as having a cursor position that is initially just before the element that will be returned by the first call to next() A call to next() puts the cursor just after the element returned, and just before the element that will be returned by the next call to next() At any time, in a ListIterator, the cursor is in between two list elements: a call to previous() will skip backward and return the element just skipped a call to next() will skip forward and return the element just skipped Updated by L. Lilien

32 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 32 Iterator and ListIterator Exceptions A call to previous() throws NoSuchElementException when there is no element that can be skipped in a backward move A call to next() throws NoSuchElementException when there is no element that can be skipped in a forward move Updated by L. Lilien

33 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 33 Example Use of a ListIterator import java.util.*; public class Test4 { public static void main(String [ ] args) { List nameList = new ArrayList (); String [ ] names = {"Ann", "Bob", "Carol"}; // an array // Add (from names array) to ArrayList using a ListIterator ListIterator iter = nameList.listIterator(); for (int k = 0; k < names.length; k++) iter.add(names[k]); // cf. method “add” -Table 18-5, p.1065 // Get a new ListIterator for printing (need to start from names[0]) iter = nameList.listIterator(); while (iter.hasNext()) System.out.println(iter.next()); } Updated by L. Lilien

34 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 34 Enhanced For Loop The enhanced for loop can be used with any collection The compiler converts the enhanced for loop into a traditional loop that uses the collection’s iterator Example (cf. Code Listing 18-3) System.out.println("\nThe names in the list."); for (String element : nameList) { System.out.println(element); } Updated by L. Lilien

35 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 35 ++ SKIP ++ 18.3. Sets Updated by L. Lilien

36 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 36 ++ SKIP ++ 18.4. Maps Updated by L. Lilien

37 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 37 18.5. The Collections Class © 2014 Leszek T. Lilien See Section 8.5, p.1109 Some static methods of the Collections class Example of use of the static methods: Code Listing 18-19 © 2014 Leszek T. Lilien

38 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 11-38 The End Updated by L. Lilien © 2014 Leszek T. Lilien Updated by L. Lilien


Download ppt "Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by."

Similar presentations


Ads by Google