Introduction to Java Collections

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
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 Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
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.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L16 (Chapter 22) Java Collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Unit 291 Java Collections Framework: Interfaces Introduction to the Java Collections Framework (JCF) The Comparator Interface Revisited The Collection.
05 - Containers DRAFT COPY © S. Uchitel, 2004 Container OrderedDuplicates BagsNOYES SetsNONO ListsYESYES MapsNO.
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 Java Collections Package C. DeJong Fall 2001.
Chapter 19 Java Data Structures
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
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.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
1 Java's Collection Framework By Rick Mercer with help from The Java Tutorial, The Collections Trail, by Joshua BlockThe Collections Trail.
(c) University of Washington14-1 CSC 143 Java Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
111 © 2002, Cisco Systems, Inc. All rights reserved.
COLLECTIONS Byju Veedu s/Collection.html.
Chapter 18 Java Collections Framework
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Collections –data structures and Algorithms L. Grewe.
Data structures and algorithms in the collection framework 1.
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:
1 Interfaces in Java’s Collection Framework Rick Mercer.
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.
Priority Queues. Priority Queue ADT A priority queue stores a collection of entries Each entry is a pair (key, value) Main methods of the Priority Queue.
Nov 22, 2010IAT 2651 Java Collections. Nov 22, 2010IAT 2652 Data Structures  With a collection of data, we often want to do many things –Organize –Iterate.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
©Karsten Lundqvist Example: Array and Arrays 1 import java.util.*; public class Example { private int intValues[] = { 1, 2, 3, 4, 5, 6 }; private double.
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Java Collections CHAPTER 3-February-2003
Chapter 19 Java Data Structures
Programming & Data Structures
Java语言程序设计 马 皓
Introduction to Java Collection
Presentation transcript:

Introduction to Java Collections Written by Adam Carmi

Agenda About Collections Core Collection Interfaces Object Ordering Collection, Set, List, Map Object Ordering Comparable, Comparator More Core Collection interfaces SortedSet, SortedMap Implementations Algorithms

What is a Collection Framework? A collection (sometimes called a container) is an object that groups multiple elements into a single unit. A collection framework is a unified architecture for representing and manipulating collections. Java’s collection framework consists of Collection interfaces Concrete collection implementations (reusable data structures) Algorithms (reusable functionality) C++’s Standard Template Library is also a collection framework

Benefits of a Collection Framework Reduces programming effort Powerful data structures and algorithms Increases program speed and quality High quality implementations Fine tuning by switching implementations Reduces the effort of learning new APIs Uniformity of the framework APIs of applications Encourages software reuse New data structures and algorithms

Core Collection Interfaces Collection interfaces allow collections to be manipulated independently of the details of their representation

The Collection Interface Represents a group of objects, known as its elements. The JDK does not provide any direct implementations of this interface. Collection is used to pass collections around and manipulate them when maximum generality is desired. java.util.Collection

Iterator A mechanism for iterating over a collection’s elements. Represented by the Iterator interface. Iterator allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics The only safe way to modify a collection during iteration java.util.Iterator

Example: Iterator static void filter(Collection c) { for (Iterator it = c.iterator() ; it.hasNext(); ) if (!cond(it.next())) it.remove(); } Iterator it = c.iterator(); while (it.hasNext())

The Set Interface A collection that can not contain duplicate keys. Contains no methods other than those declared in the Collection interface. Two set objects are equal if they contain the same elements, regardless of their implementations. java.util.Set

Example: Set import java.util.*; public class FindDups { public static void main(String args[]) { Set s = new HashSet(); for (int i=0; i<args.length; i++) if (!s.add(args[i])) System.out.println("Duplicate detected: " + args[i]); System.out.println(s.size() + " distinct words" + " detected: " + s); }

The List Interface An ordered collection (sometimes called a sequence) Lists may contain duplicate elements Collection operations remove operation removes the first occurrence of the specified element add and addAll operations always appends new elements to the end of the list. Two List objects are equal if they contain the same elements in the same order.

The List Interface (cont) New List operations Positional access Search Iteration (ordered, backward) Range-view operations java.util.List java.util.ListIterator

Calls to next and previous can be intermixed Example: List private static void swap(List a, int i, int j) { Object tmp = a.get(i); a.set(i, a.get(j)); a.set(j, tmp); } for (ListIterator i=l.listIterator(l.size()); i.hasPrevious(); ) { Foo f = (Foo)i.previous(); ... Calls to next and previous can be intermixed

Exampe: List (cont) public static void replace(List l, Object val, List newVals) { for (ListIterator i = l.listIterator(); i.hasNext() ; ) { if (val==null ? i.next()==null : val.equals(i.next())) { i.remove(); for (Iterator j = newVals.iterator(); j.hasNext(); ) i.add(j.next()); } The add method inserts a new element into the list, immediately before the current cursor position

The Map Interface An object that maps keys to values. A map cannot contain duplicate keys. Each key cat map to at most one value. Every object can be used as a hash key public int Object.hashCode() Equal objects (according to equals()) must produce the same hash code. The same hash code must be returned by an object throughout the execution of a Java application. Two Map objects are equal if they represent the same key-value mappings

The Map Interface (cont) Collection-view methods allow a Map to be viewed as a Collection keySet – The Set of keys contained in the Map values – The Collection of values contained in the Map entrySet – The Set of key-value pairs contained in the Map With all three Collection-views, calling an Iterator's remove operation removes the associated entry from the backing Map. This is the only safe way to modify a Map during iteration. java.util.Map

Example: Map import java.util.*; public class Freq { private static final Integer ONE = new Integer(1); public static void main(String args[]) { Map m = new HashMap(); for (int i=0; i<args.length; i++) { Integer freq = (Integer)m.get(args[i]); m.put(args[i], (freq==null ? ONE : new Integer(freq.intValue() + 1))); } System.out.println(m.size() + " distinct words detected:"); System.out.println(m);

Collection-views provide the only means to iterate over a Map. Example: Map (cont) for (Iterator i = m.keySet().iterator() ; i.hasNext() ; ) System.out.println(i.next()); for (Iterator i = m.values().iterator(); i.hasNext() ; ) for (Iterator i = m.entrySet().iterator(); i.hasNext() ; ) { Map.Entry e = (Map.Entry)i.next(); System.out.println(e.getKey() + ": " + e.getValue()); } Collection-views provide the only means to iterate over a Map.

Object Ordering A natural ordering can be defined for a class by implementing the Comparable interface Objects of classes that implement the Comparable interface may be sorted automatically Many JDK1 classes implement the Comparable interface: Integer signed numerical Double String lexicographic Date chronological Java Development Kit

Object Ordering (cont) The Comparable interface consists of a single method public interface Comparable { public int compareTo(Object o); } Natural ordering is not always sufficient Ordering objects in some order other than their natural order Ordering objects that don't implement the Comparable interface compareTo returns a negative integer, zero or a positive integer as the receiving object is less than, equal or greater than the input object

Object Ordering (cont) A Comparator may be used to order objects when natural ordering does not suffice public interface Comparable { public int compare(Object o1, Object o2); }

Example: Comparable public class Name implements Comparable { private String firstName, lastName; ... public int compareTo(Object o) { Name n = (Name)o; int lastCmp = lastName.compareTo(n.lastName); return lastCmp != 0 ? lastCmp : firstName.compareTo(n.firstName); }

Example: Comparator public class NameComparator implements Comparator { public int compare(Object o1, Object o2) { Name n1 = (Name)o1; Name n2 = (Name)o2; int lastCmp = n1.getLastName().compareTo(n2.getLastName()); return lastCmp != 0 ? lastCmp : n1.getFirstName().compareTo(n2.getFirstName()); }

SortedSet Interface A Set that maintains its elements in ascending order according to elements' natural order according to a Comparator provided at SortedSet creation time Set operations Iterator traverses the sorted set in order Additional operations Range view – range operations Endpoints – return the first or last element Comparator access java.util.SortedSet

SortedMap Interface A Map that maintains its entries in ascending order According to keys' natural order According to a Comparator provided at creation time. Map operations Iterator traverses elements in any of the sorted map's collection-views in key-order. Additional Operations Range view End points Comparator access java.util.SortedMap

Implementations Implementations are the actual data objects used to store elements Implement the core collection interfaces There are three kinds of implementations General purpose implementations Wrapper implementations Convenience implementations Lesson: Implementations

General Purpose Implementations Hash Table Resizeable Array Balanced Tree Linked List Interfaces Set HashSet TreeSet List ArrayList LinkedList Map HashMap TreeMap

Older Implementations The collections framework was introduced in JDK1.2. Earlier JDK versions included collection implementations that were not part of any framework java.util.Vector java.util.Hashtable These implementations were extended to implement the core interfaces but still have all their legacy operations Be careful to always manipulate them only through the core interfaces.

Algorithms Polymorphic algorithms are pieces of reusable functionality provided by the JDK. defined as static methods of the Collections class Provided algorithms Sorting Shuffling Data manipulation reverse, fill, copy Searching Extreme values Lesson: Algorithms

Example: Algorithms public static void sortNames(Name[] names) { List l = Arrays.asList(names); Collections.sort(l); } Collections.sort(l, new Comparator() { public int compare(Object o1, Object o2) { Name n1 = (Name)o1; Name n2 = (Name)o2; int lastCmp = n1.getLastName().compareTo(n2.getLastName()); return lastCmp != 0 ? lastCmp : n1.getFirstName().compareTo(n2.getFirstName()); }}); Arrays.asList is a Convenience implementation of the List interface API Bridge Performance