Back to Collections Lists: Sets Maps ArrayList LinkedList

Slides:



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

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++)
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.
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
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.
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.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 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 Unit 10 - Data Structures Objectives 1. Describe the usage of data structures. 2. Develop simple data structures. 3. Apply Java collections. 4. Apply.
(c) University of Washington14-1 CSC 143 Java Collections.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
1.0tCopyright © 1998 Purple Technology, Inc. 1 Java Collections Framework Authored by Alex Chaffee Copyright © 1998 Purple Technology, Inc. All rights.
CS-2852 Data Structures LECTURE 7A Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.
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:
Sadegh Aliakbary Sharif University of Technology Fall 2012.
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.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
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.
Starting Out with Java From Control Structures through Data Structures by Tony Gaddis and Godfrey Muganda Collections in Java.
CSE 143 Lecture 12: Sets and Maps reading:
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
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Java Collections CHAPTER 3-February-2003
Slides by Donald W. Smith
Using the Java Collection Libraries COMP 103 # T2
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs)
Chapter 19 Java Data Structures
Software Development Java Collections
Efficiency of in Binary Trees
Programming & Data Structures
Data Structures TreeMap HashMap.
Road Map CS Concepts Data Structures Java Language Java Collections
Java Collections Overview
TreeSet TreeMap HashMap
Part of the Collections Framework
Java Collections Framework
Collections in Java The objectives of this lecture are:
Iteration Abstraction
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
CS2110: Software Development Methods
Collections Framework
CSE 373 Java Collection Framework, Part 2: Priority Queue, Map
Containers and Iterators
slides created by Marty Stepp
Hashing in java.util
Web Design & Development Lecture 6
Set and Map IS 313,
Introduction to Java Collection
Presentation transcript:

Back to Collections Lists: Sets Maps ArrayList LinkedList No duplicates No order (TreeSets happen to have an order) Maps Mapping a key to a value E.g., our soccer players: map each player to a position Each player is unique, each position doesn’t have to be The player’s name should bring up their position

Map The Map interface maps unique keys to values. A key is an object that you use to retrieve a value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key. Examples: web page url (key) -> web page content (value) Word (key) -> count of word in document (value) Word(key)-> List of words that follow that word (value) Student name (key) -> class schedule (value) ClassID(key)->roster(list) of students (value)

Map Methods void clear( ) - Removes all key/value pairs from the map. Maps keys to values No duplicate keys Each key maps to a value Methods: void clear( ) - Removes all key/value pairs from the map. boolean containsKey(Object k) - Returns true if the invoking map contains k as a key. Otherwise, returns false. boolean containsValue(Object v) - Returns true if the map contains v as a value. Otherwise, returns false. Set entrySet( ) - Returns a Set that contains the entries in the map. In essence, this is turning the Map into a set (with each key-value pair as an object) Object get(Object k) - Returns the value associated with the key k. boolean isEmpty( ) - Returns true if the invoking map is empty. Otherwise, returns false. Set keySet( ) - Returns a Set that contains the keys from the map Object put(Object k, Object v) - Puts an entry in the map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned. void putAll(Map m) - Puts all the entries from m into this map. Object remove(Object k) - Removes the entry whose key equals k. int size( ) - Returns the number of key/value pairs in the map.

Map Implementations HashMap (uses hashing function on keys) Fast TreeMap (orders keys) Sorted ordering Key-ordered iteration LinkedHashMap (guess) Insertion-order iteration

Declaring Maps Declare types for both keys and values Class HashMap<K,V> HashMap<String, ArrayList<String>> map = new HashMap(); What type is the key? What type is the value?

HashMap<Integer, String> map = new HashMap(); map HashMap<Integer, String> map = new HashMap(); map.put(21, "Twenty One"); // which is the key, and which is the value? //map.put(21.0, "Twenty One"); //this will throw an error because 21.0 is not integer Integer key = 21; String value = map.get(key); // gets value associated with key System.out.println("Key: " + key +" value: "+ value); map.put(31, "Thirty One"); System.out.println("Size of Map: " + map.size()); System.out.println("Does HashMap contains 21 as key: " + map.containsKey(21)); System.out.println("Does HashMap contains 21 as value: " + map.containsValue(21)); System.out.println("Does HashMap contains Twenty One as value: " + map.containsValue("Twenty One")); map.put(41, "Thirty One"); System.out.println("Unsorted HashMap: " + map); TreeMap sortedHashMap = new TreeMap(map); // cool stuff System.out.println("Sorted HashMap: " + sortedHashMap); map.clear(); //clears hashmap , removes all element System.out.println("Is HashMap is empty: " + map.isEmpty());

Looping through map: How could this go wrong? More than one way: for (Integer key : map.keySet()) { … //code goes here System.out.println("Key : " + key.toString() + " Value : "+ map.get(key)); } How could this go wrong? we should use an Iterator

Traversing Collections (1) For-each loop: for (Object o : collection) System.out.println(o); Equivalent to: for (Iterator i = collection.iterator(); i.hasNext();) { Object o = i.next(); } Everything that inherits from Collections Interface has an iterator We should usually use the iterator: more efficient and better way to traverse the objects in a collection

How to use an iterator: Iterator enables you to cycle through a collection obtaining or removing elements ListIterator extends Iterator to allow bidirectional traversal of a list Can go backwards and forward in list. To use an iterator: Obtain an iterator (pointer) to the start of the collection call the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ) Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ).

Traversing Collections: Iterators Java Interface Object next() get the next element boolean hasNext() are there more elements? void remove() removes the previous element Only safe way to remove elements during iteration

public static void main(String args[]) { ArrayList al = new ArrayList(); // Create an array list al.add("C"); // add elements to the array list al.add("A"); al.add("E"); al.add("B"); al.add("D"); al.add("F"); System.out.print("Original contents of al: "); Iterator itr = al.iterator(); // Use iterator to display contents of al while(itr.hasNext()) { Object element = itr.next(); System.out.print(element + " "); } System.out.println(); ListIterator litr = al.listIterator(); while(litr.hasNext()) { // Modify objects being iterated Object element = litr.next(); litr.set(element + "+"); // concatenates “+” to each String System.out.print("Modified contents of al: "); itr = al.iterator(); // sets itr to initial address of ArrayList (i.e., first element in list) System.out.print("Modified list backwards: "); while(litr.hasPrevious()) { // Now, display the list backwards Object element = litr.previous();

ListIterator methods: void add(Object obj) Inserts obj into the list in front of the element that will be returned by the next call to next( ). boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false. boolean hasPrevious( ) Returns true if there is a previous element. Otherwise, returns false. Object next( ) Returns the next element. A NoSuchElementException is thrown if there is not a next element. int nextIndex( ) Returns the index of the next element. If there is not a next element, returns the size of the list. Object previous( ) Returns the previous element. A NoSuchElementException is thrown if there is not a previous element. int previousIndex( ) Returns the index of the previous element. If there is not a previous element, returns -1. void remove( ) Removes the current element from the list. An IllegalStateException is thrown if remove( ) is called before next( ) or previous( ) is invoked. void set(Object obj) Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( ).

Filter Algorithm void filter(Collection c) { Iterator i = c.iterator(); while( i.hasNext() ) { // if the next element does not // adhere to the condition, remove it if (!cond(i.next())) { i.remove(); }

TreeSets: How do TreeSets work? What makes TreeSets unique compared to HashSets? What if we put student objects into the tree? How about car objects?

Comparable Remember toString() method? Write it for every class You decide what should be the string representation of the object you are creating Java assumes a toString method in printing Every object has a built-in toString method Remember System.out.println(myObject); // gives you: 2@2a139a55 You overrode the built in toString method by writing your own toString method for the classes you were creating. Then everywhere you need a String representation of the object, the string returned from the toString method will be used

Comparables You now get to do something similar for comparing objects: You decide what will make one object greater than, less than, or equal to another object of the same class. So you decide if you want to compare students by last name, by lab score, by total score, or whatever you want.

public class Student2 implements Comparable<Student2> { String f,l; int g1,g2,g3; int total; public Student2(String f1, String l1, int g11, int g21, int g31) { f = f1; l = l1; g1 = g11; g2 = g21; g3 = g31; total = getTotal(); } public int compareTo(Student2 s2) { System.out.println(total + " " + s2.getTotal()); if (total > s2.getTotal()) { return 1; else if (total < s2.getTotal()) { return -1; else { return 0; } } private int getTotal() { return(g1 + g2 + g3); } public String toString() { String s = ""; s += l + " "+f+": "+total; return(s);

A couple of comments… The comparable interface only has one method – compareTo() All primitive wrapper classes implement the comparable interface Wrapper classes = Integer, Double, Character Our way of making objects out of primitive types CompareTo should return an int: 1 when comparing x to y, x is greater -1 when comparing x to y, y is greater 0 when x and y are considered equal You must write compareTo for every class with which you want to use Arrays.sort or any of the Collections sort method.

public static void main(String[] args) { Student2 s = new Student2("Harry","Jones",20,20,20); Student2 s2 = new Student2("Anne","Rivers",50,50,50); if (s.compareTo(s2)==1) { System.out.println("s is greater "); } else if (s.compareTo(s2)==-1) { System.out.println("s2 is greater"); else { System.out.println("equal"); } 60 150 s2 is greater

public static void main(String[] args) { Student2 s = new Student2("Harry","Jones",20,20,20); Student2 s2 = new Student2("Anne","Rivers",50,50,50); Student2 s3 = new Student2("Bill","Young",30,30,30); Student2 s4 = new Student2("Lisa","Smith",40,40,40); Student2 s5 = new Student2("Joe","Banks",10,10,10); TreeSet<Student2> tree = new TreeSet(); tree.add(s); tree.add(s2); tree.add(s3); tree.add(s4); tree.add(s5); System.out.println(tree); [Banks Joe: 30, Jones Harry: 60, Young Bill: 90, Smith Lisa: 120, Rivers Anne: 150]

public class Student2 implements Comparable<Student2> { String f,l; int g1,g2,g3; int total; public Student2(String f1, String l1, int g11, int g21, int g31) { f = f1; l = l1; g1 = g11; g2 = g21; g3 = g31; total = getTotal(); } public int compareTo(Student2 s2) { return(l.compareTo(s2.l)); private int getTotal() { return(g1 + g2 + g3); } public String toString() { String s = ""; s += l + " "+f+": "+total; return(s); } }

public static void main(String[] args) { Student2 s = new Student2("Harry","Jones",20,20,20); Student2 s2 = new Student2("Anne","Rivers",50,50,50); Student2 s3 = new Student2("Bill","Young",30,30,30); Student2 s4 = new Student2("Lisa","Smith",40,40,40); Student2 s5 = new Student2("Joe","Banks",10,10,10); TreeSet<Student2> tree = new TreeSet(); tree.add(s); tree.add(s2); tree.add(s3); tree.add(s4); tree.add(s5); System.out.println(tree); [Banks Joe: 30, Jones Harry: 60, Rivers Anne: 150, Smith Lisa: 120, Young Bill: 90]

Equals Why can’t we do: When will this be equal? Student2 s = new Student2("Harry","Jones",20,20,20); Student2 sa = new Student2("Harry","Jones",20,20,20); if (s == sa) { System.out.println("They're equal"); } else { System.out.println("Not equal"); When will this be equal?

Equals You can use the compareTo method to determine equality compareTo should return 0 when what you’ve determined to be equality is encountered We often write equals as well. Like toString There’s a built-in equals, but it always compares the actual object In other words, if they’re not literally the same object, they won’t be considered equal. We can override the built-in equals.

public class Student2 implements Comparable<Student2> { String f,l; int g1, g2, g3, total; public Student2(String f1, String l1, int g11, int g21, int g31) { f = f1; l = l1; g1 = g11; g2 = g21; g3 = g31; total = getTotal(); } public boolean equals(Student2 s2) { return(f.equals(s2.f)&&l.equals(s2.l) &&g1==s2.g1 && g2==s2.g2 && g3==s2.g3); public int compareTo(Student2 s2) { System.out.println(total + " " + s2.getTotal()); return(l.compareTo(s2.l)); private int getTotal() { int t = g1 + g2 + g3; return(t); public String toString() { String s = ""; s += l + " "+f+": "+total; return(s); } }

public static void main(String[] args) { Student2 s = new Student2("Harry","Jones",20,20,20); Student2 sa = new Student2("Harry","Jones",20,20,20); if (s == sa) { System.out.println("They're equal"); } else { System.out.println("Not equal"); if (s.equals(sa)) { System.out.println("they're equal"); System.out.println("nope"); Not equal they're equal

As a general rule In general, it is considered good coding practice to make equals and compareTo compare equally. It just makes sense… People expect it… So the compareTo function should’ve been:

compareTo and equals public boolean equals(Student2 s2) { return (f.equals(s2.f)&&l.equals(s2.l) && g1==s2.g1 && g2==s2.g2 && g3==s2.g3); } public int compareTo(Student2 s2) { if (total > s2.getTotal()) { return 1; } else if (total < s2.getTotal()) { return -1; else { if (l.compareTo(s2.l) != 0) { return l.compareTo(s2.l); else if (f.compareTo(s2.f) != 0){ return f.compareTo(s2.f); else if (g1>s2.g1) { return 1; } else if (g1 < s2.g1) {return -1; } else if (g2>s2.g2) { return 1; } else if (g2 < s2.g2) {return -1; } else if (g3>s2.g3) { return 1; } else if (g3 < s2.g3) {return -1; } else { return 0; }