Presentation is loading. Please wait.

Presentation is loading. Please wait.

Programming & Data Structures

Similar presentations


Presentation on theme: "Programming & Data Structures"— Presentation transcript:

1 Programming & Data Structures
GRIFFITH COLLEGE DUBLIN Programming & Data Structures Java Collections Framework Lecture 21

2 What is a Collection A Collection (sometimes called a container) is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another. While earlier versions of Java contained collection implementations, they did not contain a collections framework. A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain three things: Lecture 21

3 Three Elements of Framework
Interfaces: abstract data types representing collections. Interfaces allow collections to be manipulated independently of the details of their representation. In object-oriented languages like Java, these interfaces generally form a hierarchy. Implementations: concrete implementations of the collection interfaces. In essence, these are reusable data structures. Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. Lecture 21

4 Benefits of Collections Framework
It reduces programming effort: By providing useful data structures and algorithms, frees you to concentrate on the important parts of your program, rather than implemenation It increases program speed and quality: The collections framework does this primarily by providing high-performance, high-quality implementations. It fosters software reuse: New data structures that conform to the standard collection interfaces are by nature reusable. The same goes for new algorithms. It allows interoperability among unrelated APIs: The collections interfaces will become the "lingua franca" by which APIs pass collections back and forth. Lecture 21

5 Interfaces The core collection interfaces are the interfaces used to manipulate collections, and to pass them from one method to another. The basic purpose of these interfaces is to allow collections to be manipulated independently of the details of their representation. When you understand how to use these interfaces, you know most of what there is to know about the framework. The core collections interfaces are shown below: Lecture 21

6 Collections Framework
The core collection interfaces form a hierarchy: Collection Set List HashSet Map SortedMap TreeMap HashMap ArrayList TreeSet LinkedList Stack Lecture 21

7 Collection The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement. Collection is used to pass collections around and manipulate them when maximum generality is desired. Lecture 21

8 Set and List Containers
A Set is a collection that cannot contain duplicate elements. It is used to represent sets like the cards comprising a poker hand, the courses making up a student's schedule, or the processes running on a machine. A List is an ordered collection (sometimes called a sequence). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted. The user can access elements by their integer index (position). If you've used Vector, you're already familiar with the general flavour of List. Lecture 21

9 Map Container Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. The last two core collection interfaces (SortedSet (not shown) and SortedMap) are merely sorted versions of Set and Map. A SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. A SortedMap is a Map that maintains its mappings in ascending key order. Lecture 21

10 Collection Interface public interface Collection { // Basic Operations
int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); boolean remove(Object element); Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); // Array Operations Object[] toArray(); Object[] toArray(Object a[]); } Lecture 21

11 Discussion The interface has methods to tell you how many elements are in the collection (size, isEmpty), to check if a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator). The add method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. Similarly, the remove method is defined to remove a single instance of the specified element from the Collection, assuming the Collection contains the element. Lecture 21

12 Iterators The object returned by the iterator method deserves special mention. It is an Iterator. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics. public interface Iterator { boolean hasNext(); Object next(); void remove(); } The remove method removes from the underlying Collection the last element that was returned by next. The remove method may be called only once per call to next, and throws an exception if this condition is violated. Lecture 21

13 Iterators The following snippet shows you how to use an Iterator to filter a Collection, that is, to traverse the collection, removing every element that does not satisfy some condition: static void filter(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (!cond(i.next())) i.remove(); } Note : The code is polymorphic: it works for any Collection that supports element removal, regardless of implementation. Lecture 21

14 Bulk Operations The bulk operations perform some operation on an entire Collection in a single shot. containsAll: Returns true if the target Collection contains all of the elements in the specified Collection (c). addAll: Adds all of the elements in the specified Collection to the target Collection. removeAll: Removes from the target Collection all of its elements that are also contained in the specified Collection. retainAll: Removes from the target Collection all of its elements that are not also contained in the specified Collection. clear: Removes all elements from the Collection. Lecture 21

15 Array Methods The toArray allow the contents of a Collection to be translated into an array. The simple form with no arguments creates a new array of Object. The more complex form allows the caller to provide an array or to choose the runtime type of the output array. For example, suppose c is a Collection. The following snippet dumps the contents of c into a newly allocated array of Object whose length is identical to the number of elements in c: Object[] a = c.toArray(); Suppose c is known to contain only strings. The following snippet dumps the contents of c into a newly allocated array of String whose length is identical to the number of elements in c: String[] a = (String[]) c.toArray(new String[0]); Lecture 21

16 Set Interface A Set is a Collection that cannot contain duplicate elements. Set models the mathematical set abstraction. The Set interface extends Collection and contains no methods other than those inherited from Collection. It adds the restriction that duplicate elements are prohibited. Two Set objects are equal if they contain the same elements. Lecture 21

17 List Interface A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements. In addition to the operations inherited from Collection, the List interface includes operations for: Positional Access: manipulate elements based on their numerical position in the list. Search: search for a specified object in the list and return its numerical position. List Iteration: extend Iterator semantics to take advantage of the list's sequential nature. Range-view: perform arbitrary range operations on the list. Lecture 21

18 List Interface public interface List extends Collection {
// Positional Access Object get(int index); Object set(int index, Object element); void add(int index, Object element); Object remove(int index); abstract boolean addAll(int index, Collection c); // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator listIterator(); ListIterator listIterator(int index); // Range-view List subList(int from, int to); } Lecture 21

19 Implementations The JDK contains two general-purpose List implementations. ArrayList which is generally the best-performing implementation LinkedList which offers better performance under certain circumstances. Also, Vector has been retrofitted to implement List. Lecture 21

20 Discussion hasNext() and hasPrevious() next() and previous()
The remove operation always removes the first occurrence of the specified element from the list. The add and addAll operations always append the new element(s) to the end of the list. The set and remove operations return the old value that is being overwritten or removed The ListIterator allows us to move backwards as well as forwards through the List hasNext() and hasPrevious() next() and previous() The subList method allows us to manipulate subLists using the same methods we use on Lists Lecture 21

21 Algorithms Most of the polymorphic algorithms in the Collections class apply specifically to List. sort(List): Sorts a List using a merge sort algorithm, which provides a fast, stable sort. shuffle(List): Randomly permutes the elements in a List. reverse(List): Reverses the order of the elements in a List. fill(List, Object): Overwrites every element in a List with the specified value. copy(List dest, List src): Copies the source List into the destination List. binarySearch(List, Object): Searches for an element in an ordered List using the binary search algorithm. Collections.min(List) and Collections.max(List) return the extreme values in the List Lecture 21

22 Map Interface public interface Map { // Basic Operations
Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk Operations void putAll(Map t); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set entrySet(); // Interface for entrySet elements public interface Entry { Object getKey(); Object getValue(); Object setValue(Object value); } } Lecture 21

23 Map Interface The Basic and Bulk Operations perform as you would expect. The Collection-view methods allow a Map to be viewed as a Collection in three ways: keySet: the Set of keys contained in the Map. values: The Collection of values contained in the Map. This Collection is not a Set, as multiple keys can map to the same value. entrySet: The Set of key-value pairs contained in the Map. The Map interface provides a small nested interface called Map.Entry that is the type of the elements in this Set. The Collection-views provide the only means to iterate over a Map Lecture 21

24 Example Code : HashSet import java.util.*; public class CollTest
{ public static void main(String [] args) { // HashSet example HashSet hs = new HashSet(); String st; hs.add(" Beta "); hs.add(" Alpha "); hs.add(" Gamma "); System.out.println(hs); for(Iterator i = hs.iterator(); i.hasNext();) { st = (String)i.next(); System.out.println(st); } Lecture 21

25 Example Code : LinkedList
import java.util.*; public class CollTest { public static void main(String [] args) { // LinkedList example LinkedList ll = new LinkedList(); String st; ll.add(" Beta "); ll.add(" Alpha "); ll.add(" Gamma "); System.out.println(ll); for(Iterator i = ll.iterator(); i.hasNext();) { st = (String)i.next(); System.out.println(st); } Collections.sort(ll); Lecture 21

26 Example Code : TreeMap import java.util.*; public class CollTest
{ public static void main(String [] args) { // TreeMap example TreeMap tm = new TreeMap(); String st; tm.put(“A”, " Beta "); tm.put(“B”, " Alpha "); tm.put(“B”, " Gamma "); System.out.println(tm); Set ks = tm.keySet(); for(Iterator i = ks.iterator(); i.hasNext();) { st = (String)i.next(); System.out.println(st); } Lecture 21

27 Summary The Java Collection Framework supplies us with reusable data structures and algorithms to manipulate data in many ways The main elements are Containers, Interfaces and Algorithms The main Interfaces are Map, List and Set The main concrete implementations are HashMap, TreeMap, HashSet, TreeSet, ArrayList, LinkedList, Stack and Vector The Java Tutorial Collections Trail is very informative Lecture 21


Download ppt "Programming & Data Structures"

Similar presentations


Ads by Google