Programming & Data Structures

Slides:



Advertisements
Similar presentations
Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Collections CS3250. Sources  Slides by Professor Chuck Allison  Core Java, by Cay S. Horstmann and Gary Cornell  The Java Tutorial 
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
The Java Collections Package C. DeJong Fall 2001.
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections F The limitations of arrays F Java Collection Framework hierarchy  Use the Iterator interface to traverse a collection  Set interface, HashSet,
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
COLLECTIONS Byju Veedu s/Collection.html.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Collections –data structures and Algorithms L. Grewe.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
University of Limerick1 Collections The Collection Framework.
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Slide 1 Collections – Part I. Slide 2 Lesson Overview Topics covered: (1) Introduction to the Java Collections framework (2) Collection interfaces: Collection.
©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Fundamental of Java Programming
Chapter 19 Java Data Structures
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
TCSS 342, Winter 2006 Lecture Notes
Java语言程序设计 马 皓
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
Collections Not in our text.
Introduction to Collections
Introduction to Collections
Containers and Iterators
Part of the Collections Framework
Java Generics & Iterators
Presentation transcript:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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