CS 3331 1 Collection and Input/Output Classes CS 3331 Fall 2009.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Chapter 6 The Collections API. Simple Container/ Iterator Simple Container Shape [] v = new Shape[10]; Simple Iterator For( int i=0 ; i< v.length ; i++)
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 
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
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.
Professor Evan Korth (adapted from Sun’s collections documentation)
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 8.
Java Collection Framework. Interface Collection add(o) Add a new element clear() Remove all elements contains(o) Membership checking. IsEmpty() Whether.
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.
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
Java's Collection Framework
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
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.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities Chapter 4.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
Last Class. To organize data to be able to perform operations on those data efficiently. Data Structure Could be implemented in many different ways. The.
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.
(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.
Object Oriented Programming Ders 10: Data Structures Mustafa Emre İlal
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
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.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
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.
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.
1 Copyright © 2011 Tata Consultancy Services Limited COLLECTIONS By TEAM 5 Rajendhiran Sivan Christi Yashwanth Bijay Smruthi Satyajit.
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.
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
CSE 143 Lecture 11: Sets and Maps reading:
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.
COMP2402 The Java Collections Framework II: Implementations and Algorithms Pat Morin.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Reference – Object Oriented Software Development Using Java - Jia
Road Map CS Concepts Data Structures Java Language Java Collections
Part of the Collections Framework
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Introduction to Java Collection
Presentation transcript:

CS Collection and Input/Output Classes CS 3331 Fall 2009

2 CS 3331 Outline Collection classes  Collection interfaces  Implementation classes  Iterators  Ordering Input/output classes

3 CS 3331 Collection Classes in Java Major types of collections  Sets, bags, lists, maps  Defined in the java.util package Interfaces of collections

4 CS 3331 Collection Interface Method Description add(o) Add a new element addAll(c) Add all elements of c remove(o) Remove an element removeAll(c) Remove all elements found in c retainAll(c) Retain only elements found in c clear() Remove all elements contains(o) Membership testing containsAll(c) Membership testing isEmpty() Whether it is empty size() The number of elements iterator() Return an iterator

5 CS 3331 Set Interface Method Description add(o) Add an element if not already present addAll(c) Add each elements of c if not present

6 CS 3331 Exercise Define a set-intersection method. public static Set union(Set x, Set y) { Set s = new HashSet(); // HashSet will be discussed later. s.addAll(x); s.addAll(y); return s; } public static Set intersection(Set x, Set y) { // WRITE YOUR CODE HERE }

7 CS 3331 List Interface Method Description add(i, o) Insert o at the i-th position add(o) Append o at the end addAll(i, c) Insert all elements of c starting at the i-th position addAll(c) Append all elements of c at the end remove(i) Remove i-th element remove(o) Remove the first occurrence of o set(i, o) Replace i-th element with o get(i) Return i-th element indexOf(o) Return the index of the first occurrence of o lastIndexOf(o) Return the index of the last occurrence of o listIteratpr() Return a list iterator listIterator(i) Return a list iterator for the sublist starting from i subList(i, j) Retrun a sublist between index iand j

8 CS 3331 Map Interface Method Description put(k,v) Associate v with k remove(k) Remove the mapping for k clear() Remove all mappings get(k) The value associated with k containsKey(k) Whether contains a mapping for k containsValue(v) Whether contains a mapping to v size() The number of pairs isEmpty() Whether it is empty ….

9 CS 3331 Map Interface (Cont.) Method Description entrySet() Set of key-value pairs keySet() Set of keys values() The collection of values k1 k2 k3. kn v1 v2 v3. vn keySet() values() entrySet()

10 CS 3331 Outline Collection classes Collection interfaces  Implementation classes  Iterators  Ordering Input/output classes

11 CS 3331 Implementation of Collections Why different implementations?  Bounded vs. unbounded  Time and space complexity of operations Sets Class Interface Description HashSet Set Hash table LinkedHashSet Set Hash table & DLL TreeSet SortedSet Balanced binary tree

12 CS 3331 Implementation (Cont.) Lists Class Interface Description ArrayList List Resizable array LinkedList List Doubly linked list Vector List Legacy of JDK 1.0

13 CS 3331 Implementation (Cont.) Maps Class Interface Description HashMap Map Hash table IdentityHashMap Map Hash table with identity comparison LinkedHashMap Map Hash table and DLL TreeMap SortedMap Balanced binary tree Hashtable Map Legacy of JDK 1.0

14 CS 3331 Example (JDK 1.5 or above) Counting word frequency public static void frequence(String[] words) { Map map = new LinkedHashMap (); for (String w: words) { if (!map.containsKey(w)) { map.put(w, 1); } else { map.put(w, 1 + map.get(w)); } for (String k: map.keySet()) { System.out.println(k + “:\t” + map.get(k)); }

15 CS 3331 Example (JDK 1.4 or below) Counting word frequency public static void frequence(String[] words) { Map map = new LinkedHashMap(); for (int i = 0; i < words.length; i++) { if (!map.containsKey(words[i])) { map.put(words[i], new Integer(1)); } else { map.put(words[i], new Integer(1 + ((Integer) map.get(words[i])).intValue()); } for (Iterator i = map.keySet().iterator(); i.hasNext(); ) { String word = (String) i.next(); System.out.println(word + “:\t” + map.get(word)); }

16 CS 3331 Exercise Write a method that counts the number of different words /** Returns the number of different words in the array words. */ public static int numOfDifferentWords(String[] words) { // WRITE YOUR CODE HERE }

17 CS 3331 Iterators of Collections Iterator ListIterator Method Description add(o) Insert o in the current position remove() Remove the last element set(o) Replace the current element with o hasNext() More element in the forward? hasPrevious() More element in the reverse? next() Return the next element nextIndex() Return the next index previous() Return the previous element previousIndex() Return the previous index

18 CS 3331 Group Work: Set Implementation Work in group of two or three to write class ArraySet that implements the Set interface. You should use an array to store the elements. Method Description add(o) Add a new element addAll(c) Add all elements of c remove(o) Remove an element removeAll(c) Remove all elements found in c retainAll(c) Retain only elements found in c clear() Remove all elements contains(o) Membership testing containsAll(c) Membership testing isEmpty() Whether it is empty size() The number of elements iterator() Return an iterator

19 CS 3331 Outline Collection classes Collection interfaces Implementation classes Iterators  Ordering Input/output classes

20 CS 3331 Ordering and Sorting Partial order (or order)  Binary relation that is transitive  Total order if a < b and b < a implies a = b How to define order on objects?  Natural order by implementing the Comparable interface  Arbitrary order by comparators (classes implementing the Comparator interface)

21 CS 3331 Comparable Interface Method compareTo:  Result < 0, if the receiver precedes o  Result = 0, if neither the receiver precedes o, nor o precedes the receiver  Result > 0, if o precedes the receiver Properties (or constraints)  a.compareTo(b) > 0 implies that b.compareTo(a) < 0  a.compareTo(b) 0  a.compareTo(b) = 0 implies that b.compareTo(a) = 0;  Consistent with the definition of equals, i.e., a.equals(b) is true iff a.compareTo(b) is 0 public interface Comparable { int compareTo(Object o); }

22 CS 3331 Exercise Define a natural order for the Person class based on the person’s name. (Hint: the String class implements the Comparable interface.) public class Person implements Comparable { private String name; public int compareTo(Object other) { // YOUR CODE HERE … }

23 CS 3331 Comparator Interface Method compare:  Result < 0, if o1 precedes o2  Result = 0, if neither o1 precedes o2, nor o2 precedes o1  Result > 0, if o2 precedes o1 Properties (or constraints)  c.compare(a,b) > 0 implies that c.compare(b,a) < 0  c.compare(a,b) 0  c.compare(a,b) = 0 implies that c.compare(a,b) = 0;  Consistent with equals, i.e., c.compare(a,b) is 0 iff a.equals(b) and b.equals(a) public interface Comparator { int compare (Object o1, Object o2); }

24 CS 3331 Exercise Define a total ordering for the Person class based on the person’s SSN. Public class Person { ensures \result > 0; public int getSSN() { /*… */ } // other declarations … } public class PersonComparator implements Comparator { public int compare(Object p1, Object p2) { // YOUR CODE HERE … }

25 CS 3331 Sorted Collections Interfaces  SortedSet and SortedMap Implementations  TreeSet and TreeMap Example SortedSet s1 = new TreeSet(); SortedSet s2 = new TreeSet(new PersonComparator()); SortedMap m1 = new TreeMap(); SortedMap m2 = new TreeMap(new PersonComparator());

26 CS 3331 SortedSet Interface Method Description comparator() Return the comparator first() Return the first (lowest) element last() Return the last (highest) element headSet(o) Return elements less than o tailSet(o) Return elements greater than or equal to o subSet(o1,o2) Return elements between o1 and o2

27 CS 3331 Exercise Write a method that, given an array of Person objects, returns a sorted array of the argument array. Assume that the Person class has a natural order defined. public static Person[] Person[] persons) { // YOUR CODE HERE … }

28 CS 3331 SortedMap Interface Method Description comparator() Return the comparator firstKey() Return the first (lowest) key lastKey() Return the last (highest) key headMap(k) Return maplets less than k tailMap(k) Return maplets greater than or equal to k subMap(k1,k2) Return maplets between k1 and k2

29 CS 3331 Outline Collection classes Collection interfaces Implementation classes Iterators Ordering Input/output classes

30 CS 3331 Input/Output Classes Two types of input/output  Stream I/O Sequential reading and writing Opened for reading or writing, but not both Byte streams vs. character streams  Random access I/O Non-sequential reading and writing Can be opened for both reading and writing

31 CS 3331 Byte Streams

32 CS 3331 Character Streams

33 CS 3331 Example Usage Reading lines from file String fileName = …; BufferedReader reader = new BufferedReader( new InputStreamReader(new FileInputStream(fileName))); String line; while ((line = reader.readLine()) != null) { // do something with line … }

34 CS 3331 Decorator Pattern To add additional responsibility or capability to an object dynamically