Introduction to Java 2 Programming Lecture 5 The Collections API.

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.
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4.
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.
Collections Chapter Java Collection Frameworks The Java collection framework is a set of utility classes and interfaces. Designed for working with.
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.
Computer Science 209 Software Development Equality and Comparisons.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
15-Jun-15 Lists in Java Part of the Collections Framework.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Lists and the Collection Interface Chapter 4. Chapter 4: Lists and the Collection Interface2 Chapter Objectives To become familiar with the List interface.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
© 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.
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.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
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.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
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.
111 © 2002, Cisco Systems, Inc. All rights reserved.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Chapter 18 Java Collections Framework
Computer Science 209 Software Development Java Collections.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
CSS446 Spring 2014 Nan Wang  Java Collection Framework ◦ LinkedList ◦ Set ◦ Map 2.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Generics and Collections Course Lecture Slides 19 th July 2010 “Never.
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.
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.
Maps Nick Mouriski.
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.
Topic 13 Iterators. 9-2 Motivation We often want to access every item in a data structure or collection in turn We call this traversing or iterating over.
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.
Collections Dwight Deugo Nesa Matic
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
CS202 Java Object Oriented Programming Introduction to Collection Classes Chengyu Sun California State University, Los Angeles.
Introduction to Java Collection. Java Collections What are they? –A number of pre-packaged implementations of common ‘container’ classes, such as LinkedLists,
Collections ABCD ABCD Head Node Tail Node array doubly linked list Traditional Arrays and linked list: Below is memory representation of traditional.
Using the Java Collection Libraries COMP 103 # T2
Java Collections Overview
Introduction to Collections
Introduction to Collections
Introduction to Collections
14.1 The java.util Package.
CS2110: Software Development Methods
Introduction to Collections
Introduction to Collections
Introduction to Java Collection
Presentation transcript:

Introduction to Java 2 Programming Lecture 5 The Collections API

Overview Collection classes –Types of collection –Working with Collections –Sorting

Collections Implementations of common data structures, such as Linked Lists, Sets, etc. –Part of the java.util package. –Also known as containers Advantages –Can hold any kind of object –Much more flexible than arrays Disadvantages –Not as efficient as arrays (for some uses) –Cant store primitive types –Not type-safe. Store references to Object

Types of Collection Two Types of Containers Collections –Group of objects, which may restricted or manipulated in some way –E.g. ordered to make a List or LinkedList –E.g. a Set, an unordered group which can only contain one of each item Maps –Associative array, Dictionary, Lookup Table, Hash –A group of name-value pairs

Java Collections

Collection Implementations Several implementations associated with each of the basic interfaces Each has its own advantages/disadvantages Maps –HashMap, SortedMap Lists –ArrayList, LinkedList Sets –HashSet, SortedSet

The Basics HashMap and ArrayList are most commonly encountered Usual object creation syntax Always refer to the objects via one of the Collections interfaces –Take advantage of polymorphism List myList = new ArrayList(); List otherList = new ArrayList(5); Map database = new HashMap(); Set things = new HashSet();

Adding Items For Collections, use add() List myList = new ArrayList(); myList.add(A String); myList.add(Other String); For Maps, use put() Map myMap = new HashMap(); myMap.put(google, mpMap.put(yahoo,

Copying Very easy, just use addAll() List myList = new ArrayList(); //assume we add items to the list List otherList = new ArrayList(); myList.addAll(myList);

Getting Individual Items Use get() Note that we have to cast the object to its original type. Collections… String s = (String)myList.get(1); //get first element String s2 = (String)myList.get(10); //get tenth element Maps… String s = (String)myMap.get(google); String s2 = (String)mpMap.get(yahoo);

Getting All items For Lists, we could use a for loop, and loop through the list to get() each item But this doesnt work for Maps. To allow generic handling of collections, Java defines an object called an Iterator –An object whose function is to walk through a Collection of objects and provide access to each object in sequence

Getting All items Get an iterator using the iterator() method Iterator objects have three methods: –next() – gets the next item in the collection –hasNext() – tests whether it has reached the end –remove() – removes the item just returned Basic iterators only go forwards –Lists objects have a ListIterator that can go forward and backward

Getting All items (List) Simple example: List myList = new ArrayList(); //we add items Iterator iterator = myList.iterator(); while (iterator.hasNext()) { String s = (String)iterator.next(); //do something with it }

Getting All Items (Map) Example of using a Map Note that we can get a Set of all keys ( keySet ) or Collection of all values ( values ) Map myMap = new HashMap(); //we add items Iterator iterator = myMap.keySet.iterator(); while (iterator.hasNext()) { String theKey = (String)iterator.next(); Object theValue = myMap.get(theKey); //do something useful }

Other Functions The java.util.Collections class has many useful methods for working with collections –min, max, sort, reverse, search, shuffle Virtually all require your objects to implement an extra interface, called Comparable

Comparable The Comparable interface labels objects that can be compared to one another. –Allows sorting algorithms to be written to work on any kind of object –so long as they support this interface Single method to implement public int compareTo(Object o); Returns –A negative number of parameter is less than the object –Zero if theyre equal –A positive number if the parameter is greater than the object

Comparable Example public class Person implements Comparable { private String ; private String lastName; public int compareTo(Object object) { Person other = (Person)object; //compare based on address only return other.get ().compareTo( ); }

Comparable Example Person a = new Dodds); Person b = new Builder); List people = new ArrayList(); People.add(a); People.add(b); Java.util.Collections.sort(people); //collection is now sorted by

Comparator Like Comparable, but is a stand-alone object used for comparing other objects –Useful when you want to use your criteria, not that of the implementor of the object. –Or altering the behaviour of a system Many of the methods in the Collections object also allow a Comparator to be specified Again method has single method: public int compare(Object obj1, Object obj2)

Comparator Example Java String comparison is lexicographic not alphabetic, I.e. based on the character set, not alphabetic order public class AlphaComparison implements Comparator { public int compare(Object obj1, Object obj2) { String s1 = ((String)o1).toLowerCase(); String s2 = ((String)o2).toLowerCase(); return s1.compareTo(s2); }

Comparator Example String one = One; String two = Two; String three = Three; List strings = new ArrayList(); strings.add(one); strings.add(two); strings.add(three); Collections.sort(strings, new AlphaComparison()); //now in alphabetical order