Java Collection Framework. Interface Collection add(o) Add a new element clear() Remove all elements contains(o) Membership checking. IsEmpty() Whether.

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

Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
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.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Collections A First Glimpse. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector is a kind of collection.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
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.
CS Collection and Input/Output Classes CS 3331 Fall 2009.
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.
Advanced Java Session 3 New York University School of Continuing and Professional Studies.
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.
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.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
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.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
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.
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Set and Map IS 313, Skeletons  Useful coding patterns  Should understand how and why they work how to use  possible quiz material.
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.
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.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
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
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©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.
Java Collections CHAPTER 3-February-2003
Design & Analysis of Algorithm Map
Reference – Object Oriented Software Development Using Java - Jia
Ch 16: Data Structures - Set and Map
Efficiency of in Binary Trees
JCF Hashmap & Hashset Winter 2005 CS-2851 Dr. Mark L. Hornick.
CS240: Advanced Programming Concepts
Road Map CS Concepts Data Structures Java Language Java Collections
Introduction to Collections
Introduction to Collections
TCSS 342, Winter 2006 Lecture Notes
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
CSE 1020: The Collection Framework
Introduction to Collections
Presentation transcript:

Java Collection Framework

Interface Collection add(o) Add a new element clear() Remove all elements contains(o) Membership checking. IsEmpty() Whether it is empty iterator() Return an iterator remove(o) Remove an element size() The number of elements

Interface List add(i,o) Insert o at position i add(o) Append o to the end get(i) Return the i -th element remove(i) Remove the i -th element remove(o) Remove the element o set(i,o) Replace the i -th element with o

Interface Map Clear() Remove all mappings containsKey(k) Whether contains a mapping for k containsValue(v) Whether contains a mapping to v SetentrySet() Set of key-value pairs get(k) The value associated with k isEmpty() Whether it is empty keySet() Set of keys put(k,v) Associate v with k remove(k) Remove the mapping for k size() The number of pairs values() The collection of values

Concrete Collections concrete implements description collection HashSet Set hash table TreeSet SortedSet balanced binary tree ArrayList List resizable-array LinkedList List linked list Vector List resizable-array HashMap Map hash table TreeMap SortedMap balanced binary tree Hashtable Map hash table

Iterate Through Collections The Itertor interface: interface Iterator { boolean hasNext(); Object next(); void remove(); } The iterator() method defined in the Collection interface: Iterator iterator()

Using Set Set set = new HashSet(); // instantiate a concrete set //... set.add(obj); // insert an elements //... int n = set.size(); // get size //... if (set.contains(obj)) {...} // check membership // iterate through the set Iterator iter = set.iterator(); while (iter.hasNext()) { Object e = iter.next(); // downcast e //... }

Using Map Map map = new HashMap(); // instantiate a concrete map //... map.put(key, val); // insert a key-value pair //... // get the value associated with key Object val = map.get(key); map.remove(key); // remove a key-value pair //... if (map.containsValue(val)) {... } if (map.containsKey(kay)) {... } Set keys = map.keySet(); // get the set of keys // iterate through the set of keys Iterator iter = keys.iterator(); while (iter.hasNext()) { Key key = (Key) iter.next(); //... }

Counting Different Words public class CountWords { static public void main(String[] args) { Set words = new HashSet(); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String delim = " \t\n.,:;?!-/()[]\"\'"; String line; int count = 0;

Counting Different Words try { while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, delim); while (st.hasMoreTokens()) { count++; words.add( st.nextToken().toLowerCase()); } } catch (IOException e) {} System.out.println("Total number of words: " + count); System.out.println("Number of different words: " + words.size()); }

Word Frequency public class Count { public Count(String word, int i) { this.word = word; this.i = i; } public String word; public int i; }

Word Frequency (cont'd) public class WordFrequency { static public void main(String[] args) { Map words = new HashMap(); String delim = " \t\n.,:;?!-/()[]\"\'"; BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); String line, word; Count count;

Word Frequency (cont'd) (class WordFrequency continued.) try { while ((line = in.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, delim); while (st.hasMoreTokens()) { word = st.nextToken().toLowerCase(); count = (Count) words.get(word); if (count == null) { words.put(word, new Count(word, 1)); } else { count.i++; } } catch (IOException e) {}

Word Frequency (cont'd) (class WordFrequency continued.) Set set = words.entrySet(); Iterator iter = set.iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry) iter.next(); word = (String) entry.getKey(); count = (Count) entry.getValue(); System.out.println(word + (word.length() < 8 ? "\t\t" : "\t") + count.i); }

Word Frequency Output Using President Lincoln's The Gettysburg Address as the input, the output is: devotion 2 years 1 civil 1 place 1 gave 2 they 3 struggled men 2 remember 1 who 3 did 1 work 1 rather 2 fathers 1

Ordering and Sorting There are two ways to define orders on objects. Each class can define a natural order among its instances by implementing the Comparable interface. int compareTo(Object o) Arbitrary orders among different objects can be defined by comparators, classes that implement the Comparator interface. int compare(Object o1, Object o2)

Word Frequency II public class WordFrequency2 { static public void main(String[] args) { Map words = new TreeMap(); }

Word Frequency II Output Using President Lincoln's The Gettysburg Address as the input, the output is: a 7 above 1 add 1 address 1 advanced 1 ago 1 all whether 1 which 2 who 3 will 1 work 1 world 1 years 1

User-Defined Order Reverse alphabetical order of strings public class StringComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 != null && o2 != null && o1 instanceof String && o2 instanceof String) { String s1 = (String) o1; String s2 = (String) o2; return - (s1.compareTo(s2)); } else { return 0; }

Word Frequency III public class WordFrequency3 { static public void main(String[] args) { Map words = new TreeMap(new StringComparator()); }

Word Frequency III Output Using President Lincoln's The Gettysburg Address as the input, the output is: years 1 world 1 work 1 will 1 who 3 which 2 whether all 1 ago 1 advanced 1 address 1 add 1 above 1 a 7

Sorting public class CountComparator implements Comparator { public int compare(Object o1, Object o2) { if (o1 != null && o2 != null && o1 instanceof Count && o2 instanceof Count) { Count c1 = (Count) o1; Count c2 = (Count) o2; return (c2.i - c1.i); } else { return 0; }

Word Frequency IV public class WordFrequency4 { static public void main(String[] args) { List list = new ArrayList(words.values()); Collections.sort(list, new CountComparator()); Iterator iter = list.iterator(); while (iter.hasNext()) { count = (Count) iter.next(); word = count.word; System.out.println(word + (word.length() < 8 ? "\t\t" : "\t") + count.i); }

Word Frequency IV Output Using President Lincoln's The Gettysburg Address as the input, the output is: the 13 that 12 we 10 here 8 to 8 a 7 and consecrate 1 world 1 consecrated 1 remember 1 did 1 work 1 fathers 1