Slides by Donald W. Smith

Slides:



Advertisements
Similar presentations
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Advertisements

Processing Data in Collections Chapter Object Wrappers Collections can only hold objects. Primitive types ( int, double, float, etc.) are not objects.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
1 Chapter 24 Lists Stacks and Queues. 2 Objectives F To design list with interface and abstract class (§24.2). F To design and implement a dynamic list.
Copyright © 2013 by John Wiley & Sons. All rights reserved. THE JAVA COLLECTIONS FRAMEWORK CHAPTER Slides by Donald W. Smith TechNeTrain.com 15.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
Chapter 19 Java Data Structures
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
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.
(c) University of Washington14-1 CSC 143 Java Collections.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 15 – The Java Collections Framework.
Big Java Chapter 16.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
CS 46B: Introduction to Data Structures July 9 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak
Chapter 18 Java Collections Framework
LinkedList Many slides from Horstmann modified by Dr V.
Data structures Abstract data types Java classes for Data structures and ADTs.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
1 Chapter 17 Object-Oriented Data Structures. 2 Objectives F To describe what a data structure is (§17.1). F To explain the limitations of arrays (§17.1).
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fifteen: An Introduction to Data Structures.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. An Introduction to Data Structures.
Collections Data structures in Java. OBJECTIVE “ WHEN TO USE WHICH DATA STRUCTURE ” D e b u g.
Chapter 15 An Introduction to Data Structures. Chapter Goals To learn how to use the linked lists provided in the standard library To be able to use iterators.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 15 – An Introduction to Data Structures.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
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
Sets and Maps Chapter 9.
Using the Java Collection Libraries COMP 103 # T2
Data Structure By Amee Trivedi.
Slides by Donald W. Smith
Slides by Donald W. Smith
Unit 1 Hadoop and big data
Chapter 19 Java Data Structures
Ch 16: Data Structures - Set and Map
Chapter 20 An Introduction to Data Structures
JAVA COLLECTIONS LIBRARY
University of Central Florida COP 3330 Object Oriented Programming
CS240: Advanced Programming Concepts
Chapter 17 Object-Oriented Data Structures
Introduction to Data Structures
Road Map CS Concepts Data Structures Java Language Java Collections
structures and their relationships." - Linus Torvalds
Linked Lists.
CSE 143 Lecture 27: Advanced List Implementation
Lecture 26: Advanced List Implementation
Chapter 15 – An Introduction to Data Structures
Sets, Maps and Hash Tables
Dynamic Data Structures and Generics
CS2110: Software Development Methods
Collections Framework
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Containers and Iterators
Sets and Maps Chapter 9.
slides created by Marty Stepp
CSE 143 Lecture 21 Advanced List Implementation
structures and their relationships." - Linus Torvalds
Presentation transcript:

Slides by Donald W. Smith 15 CHAPTER THE JAVA COLLECTIONS FRAMEWORK Copyright © 2013 by John Wiley & Sons. All rights reserved. Slides by Donald W. Smith TechNeTrain.com

Contents An Overview of the Java Collections Framework Linked Lists Sets Maps Stacks Queues and Priority Queues Stack and Queue Applications In this chapter, you will learn about the Java collection framework, a hierarchy of interface types and classes for collecting objects Copyright © 2013 by John Wiley & Sons. All rights reserved.

15.1 Java Collections Framework When you need to organize multiple objects in your program, you can place them into a collection The ArrayList class that was introduced in Chapter 6 is one of many collection classes that the standard Java library supplies Each interface type is implemented by one or more classes A collection groups together elements and allows them to be accessed and retrieved later Copyright © 2013 by John Wiley & Sons. All rights reserved.

Collections Framework Diagram Each collection class implements an interface from a hierarchy Each class is designed for a specific type of storage Copyright © 2013 by John Wiley & Sons. All rights reserved.

Lists and Sets Ordered Lists ArrayList LinkedList Stores a list of items in a dynamically sized array LinkedList Allows speedy insertion and removal of items from the list A list is a collection that maintains the order of its elements. Copyright © 2013 by John Wiley & Sons. All rights reserved.

Lists and Sets Unordered Sets HashSet TreeSet Uses hash tables to speed up finding, adding, and removing elements TreeSet Uses a binary tree to speed up finding, adding, and removing elements A set is an unordered collection of unique elements. Copyright © 2013 by John Wiley & Sons. All rights reserved.

Stacks and Queues Another way of gaining efficiency in a collection is to reduce the number of operations available Two examples are: Stack Remembers the order of its elements, but it does not allow you to insert elements in every position You can only add and remove elements at the top Queue Add items to one end (the tail) Remove them from the other end (the head) Example: A line of people waiting for a bank teller Copyright © 2013 by John Wiley & Sons. All rights reserved.

Maps A map stores keys, values, and the associations between them Keys Example: Barcode keys and books Keys Provides an easy way to represent an object (such as a numeric bar code, or a Student Identification Number) Values The actual object that is associated with the key A map keeps associations between key and value objects. Copyright © 2013 by John Wiley & Sons. All rights reserved.

The Collection Interface (1) List, Queue and Set are specialized interfaces that inherit from the Collection interface All share the following commonly used methods Copyright © 2013 by John Wiley & Sons. All rights reserved.

The Collection Interface (2) Copyright © 2013 by John Wiley & Sons. All rights reserved.

15.2 Linked Lists Linked lists use references to maintain an ordered lists of ‘nodes’ The ‘head’ of the list references the first node Each node has a value and a reference to the next node They can be used to implement A List Interface A Queue Interface Copyright © 2013 by John Wiley & Sons. All rights reserved.

Linked Lists Operations Efficient Operations Insertion of a node Find the elements it goes between Remap the references Removal of a node Find the element to remove Remap neighbor’s references Visiting all elements in order Inefficient Operations Random access Each instance variable is declared just like other variables we have used. Copyright © 2013 by John Wiley & Sons. All rights reserved.

LinkedList: Important Methods Copyright © 2013 by John Wiley & Sons. All rights reserved.

Generic Linked Lists The Collection Framework uses Generics Each list is declared with a type field in < > angle brackets LinkedList<String> employeeNames = . . .; LinkedList<String> LinkedList<Employee> Copyright © 2013 by John Wiley & Sons. All rights reserved.

List Iterators Use an iterator to: When traversing a LinkedList, use a ListIterator Keeps track of where you are in the list. Use an iterator to: Access elements inside a linked list Visit other than the first and the last nodes LinkedList<String> employeeNames = . . .; ListIterator<String> iter = employeeNames.listIterator() Copyright © 2013 by John Wiley & Sons. All rights reserved.

Using Iterators Think of an iterator as pointing between two elements (think of cursor in word processor) ListIterator<String> iter = myList.listIterator() iterator.next(); Note that the generic type for the listIterator must match the generic type of the LinkedList iterator.add(“J”); Copyright © 2013 by John Wiley & Sons. All rights reserved.

Iterator and ListIterator Methods Iterators allow you to move through a list easily Similar to an index variable for an array Copyright © 2013 by John Wiley & Sons. All rights reserved.

Iterators and Loops Iterators are often used in while and “for-each” loops hasNext returns true if there is a next element next returns a reference to the value of the next element Where is the iterator in the “for-next” loop? Iterators are used ‘behind the scenes’ while (iterator.hasNext()) { String name = iterator.next(); // Do something with name } for (String name : employeeNames) { // Do something with name } Copyright © 2013 by John Wiley & Sons. All rights reserved.

Adding and Removing with Iterators A new node is added AFTER the Iterator The Iterator is moved past the new node Removing Removes the object that was returned with the last call to next or previous It can be called only once after next or previous You cannot call it immediately after a call to add.(why?) iterator.add("Juliet"); while (iterator.hasNext()) { String name = iterator.next(); if (condition is true for name) iterator.remove(); } If you call the remove method improperly, it throws an IllegalStateException. Copyright © 2013 by John Wiley & Sons. All rights reserved.

ListDemo.java (1) Illustrates adding, removing and printing a list Copyright © 2013 by John Wiley & Sons. All rights reserved.

ListDemo.java (2) Copyright © 2013 by John Wiley & Sons. All rights reserved.

15.3 Sets A set is an unordered collection It does not support duplicate elements The collection does not keep track of the order in which elements have been added Therefore, it can carry out its operations more efficiently than an ordered collection The HashSet and TreeSet classes both implement the Set interface. Copyright © 2013 by John Wiley & Sons. All rights reserved.

Sets HashSet: Stores data in a Hash Table TreeSet: Stores data in a Binary Tree Both implementations arrange the set elements so that finding, adding, and removing elements is efficient Set implementations arrange the elements so that they can locate them quickly Copyright © 2013 by John Wiley & Sons. All rights reserved.

Hash Table Concept Set elements are grouped into smaller collections of elements that share the same characteristic It is usually based on the result of a mathematical calculation on the contents that results in an integer value In order to be stored in a hash table, elements must have a method to compute their integer values 100 101 102 Copyright © 2013 by John Wiley & Sons. All rights reserved.

hashCode The method is called hashCode If multiple elements have the same hash code (so-called clash), they are stored in a LinkedList The elements must also have an equals method for checking whether an element equals another like: String, Integer, Point, Rectangle, Color, and all collection classes Set<String> names = new HashSet<String>(); Copyright © 2013 by John Wiley & Sons. All rights reserved.

Tree Concept Set elements are kept in sorted order Nodes are not arranged in a linear sequence but in a tree shape In order to use a TreeSet, it must be possible to compare the elements and determine which one is “larger” Copyright © 2013 by John Wiley & Sons. All rights reserved.

TreeSet Use TreeSet for classes that implement the Comparable interface String and Integer, for example The nodes are arranged in a ‘tree’ fashion so that each ‘parent’ node has two child nodes. The node to the left always has a ‘smaller’ value The node to the right always has a ‘larger’ value Set<String> names = new TreeSet<String>(); Copyright © 2013 by John Wiley & Sons. All rights reserved.

Iterators and Sets Iterators are also used when processing sets hasNext returns true if there is a next element next returns a reference to the value of the next element add via the iterator is not supported for TreeSet and HashSet Note that the elements are not visited in the order in which you inserted them. They are visited in the order in which the set keeps them: Seemingly random order for a HashSet Sorted order for a TreeSet Iterator<String> iter = names.iterator(); while (iter.hasNext()) { String name = iter.next(); // Do something with name } for (String name : names) { // Do something with name } Copyright © 2013 by John Wiley & Sons. All rights reserved.

Working With Sets (1) Copyright © 2013 by John Wiley & Sons. All rights reserved.

Working With Sets (2) Copyright © 2013 by John Wiley & Sons. All rights reserved.

SpellCheck.java (1) Copyright © 2013 by John Wiley & Sons. All rights reserved.

SpellCheck.java (2) Copyright © 2013 by John Wiley & Sons. All rights reserved.

Programming Tip 15.1 Use Interface References to Manipulate Data Structures It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set. This way, you have to change only one line if you decide to use a TreeSet instead. Set<String> words = new HashSet<String>(); Copyright © 2013 by John Wiley & Sons. All rights reserved.

Programming Tip 15.1 (continued) Unfortunately the same is not true of the ArrayList, LinkedList and List classes The get and set methods for random access are very inefficient (why) Also, if a method can operate on arbitrary collections, use the Collection interface type for the parameter: public static void removeLongWords(Collection<String> words) Copyright © 2013 by John Wiley & Sons. All rights reserved.

15.4 Maps A map allows you to associate elements from a key set with elements from a value collection. The HashMap and TreeMap classes both implement the Map interface. Use a map to look up objects by using a key. Copyright © 2013 by John Wiley & Sons. All rights reserved.

Maps Key Value Key Value The key “unlocks” the “data” (value) Map<String, Color> favoriteColors = new HashMap<String, Color>(); The key “unlocks” the “data” (value) A map is like a mathematical function Mapping between two sets. Copyright © 2013 by John Wiley & Sons. All rights reserved.

Working with Maps (Table 5) Copyright © 2013 by John Wiley & Sons. All rights reserved.

Key Value Pairs in Maps Each key is associated with a value Map<String, Color> favoriteColors = new HashMap<String, Color>(); favoriteColors.put("Juliet", Color.RED); favoriteColors.put(“Romeo", Color.GREEN); Color julietsFavoriteColor = favoriteColors.get("Juliet"); favoriteColors.remove("Juliet"); Copyright © 2013 by John Wiley & Sons. All rights reserved.

Iterating through Maps To iterate through the map, use a keySet to get the list of keys: Set<String> keySet = m.keySet(); for (String key : keySet) { Color value = m.get(key); System.out.println(key + "->" + value); } To find all values in a map, 1/ iterate through the key set and 2/ find the values that correspond to the keys. Copyright © 2013 by John Wiley & Sons. All rights reserved.

MapDemo.java Copyright © 2013 by John Wiley & Sons. All rights reserved.