Sadegh Aliakbary Sharif University of Technology Fall 2010.

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.
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 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 
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
15-Jun-15 Lists in Java Part of the Collections Framework.
Professor Evan Korth (adapted from Sun’s collections documentation)
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
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.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Collections The objectives of this chapter are: To outline the Collections infrastructure in Java To describe the various collection classes To discuss.
12-Jul-15 Lists in Java Part of the Collections Framework.
The Java Collections Package C. DeJong Fall 2001.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Java's Collection Framework
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
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.
(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.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
תוכנה 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.
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.
1 Java Collection: Data structure framework. 2 Background collections store and organize objects for efficient access Java collections: traditional data.
The Java Collections Framework Based on
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
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.
1 Interfaces in Java’s Collection Framework Rick Mercer.
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.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Recitation 5 Enums and The Java Collections classes/interfaces 1.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
1 Collections. 2 Concept A collection is a data structure – actually, an object – to hold other objects, which let you store and organize objects in useful.
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
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Java Collections CHAPTER 3-February-2003
Java Collections OOP tirgul No
Advanced Programming in Java
Advanced Programming in Java
Advanced Programming in Java
Road Map CS Concepts Data Structures Java Language Java Collections
ظرف‌ها و ساختمان‌های داده Containers and Data Structures
Containers ב Java אליהו חלסצ'י תכנות מתקדם תרגול מספר 3
Part of the Collections Framework
Collections in Java The objectives of this lecture are:
Advanced Programming in Java
Containers and Iterators
Hashing in java.util
Web Design & Development Lecture 6
Set and Map IS 313,
Presentation transcript:

Sadegh Aliakbary Sharif University of Technology Fall 2010

Agenda More on Containers Collection Set Map LinkedList Iterator Fall 2010Sharif University of Technology2

Collection Collection is super-class of many containers public interface Collection Some methods: int size(); boolean isEmpty(); boolean contains(Object o); boolean add(E e); boolean remove(Object o); void clear(); Object[] toArray(); T[] toArray(T[] a); Fall 2010Sharif University of Technology3

Set A set is a an unordered list of disjoint elements {1,2,3,1,4,2} = {4,3,2,1} set.add(1) set.add(2) set.add(3) set.add(1) set.remove(1) Set  {3,2} Fall 2010Sharif University of Technology4

Set and equals() Method When set.add(value) is invoked It checks whether there is any element equal to value If any equal element found, add will return We should implement appropriate equals() method equals() is invoked implicitly Fall 2010Sharif University of Technology5

HashSet Set is an interface public interface Set extends Collection HashSet is one of its (popular) implementations Set and HashSet are generic classes public class HashSet implements Set Fall 2010Sharif University of Technology6

HashSet Example Set set= new HashSet (); set.add("Ali"); set.add("Taghi"); set.add("Ali"); for (String string : set) { System.out.println(string); } Fall 2010Sharif University of Technology7

HashSet Example Set set= new HashSet (); set.add(new Student("Ali")); set.add(new Student("Taghi")); set.add(new Student("Ali")); set.remove(new Student("Taghi")); for (Student student : set) { System.out.println(student); } Fall 2010Sharif University of Technology8

Set or List? List provides access via an index Set does not List is ordered Set checks for duplicates List is (usually) better in performance Set may be better in memory consumption Should we allow duplicates? If not, use sets Set is not implemented by a List Fall 2010Sharif University of Technology9

Map Map is not a collection Map is a table public interface Map Map is something like a List > First element of each pair is called the key Second element of each pair is called the value Duplicate for keys is not allowed Duplicate for values is possible Fall 2010Sharif University of Technology10

Map map.put( , “Ali Alavi”) map.put( , “Taghi Taghavi”) map.put( , “Naghi Naghavi”) Fall 2010Sharif University of Technology11

public interface Map { int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map m); void clear(); Set keySet(); Collection values(); Set > entrySet(); interface Entry { K getKey(); V getValue(); V setValue(V value); } Fall 2010Sharif University of Technology12

HashMap Map is an interface public interface Map { HashMap is one of its (popular) implementations public class HashMap implements Map Fall 2010Sharif University of Technology13

HashMap Example Map map = new HashMap (); map.put( , "Ali Alavi"); map.put( , "Taghi Taghavi"); map.put( , "Naghi Naghavi"); String name = map.get( ); System.out.println(name); Fall 2010Sharif University of Technology14

Map map = new HashMap (); map.put(new Student("Ali Alavi"), new Double(18.76)); map.put(new Student("Taghi Taghavi"), new Double(15.43)); map.put(new Student("Naghi Naghavi"), new Double(17.26)); map.put(new Student("Naghi Naghavi"), new Double(15.26)); map.remove(new Student("Naghi Naghavi")); Double average = map.get(new Student("Taghi Taghavi")); System.out.println("Avg of Taghi=" + average); for(Student student : map.keySet()){ System.out.println(student.toString()); } Double totalSum = 0.0; for(Double avg : map.values()){ totalSum += avg; } System.out.println("Total Average = " + (totalSum/map.size())); Fall 2010Sharif University of Technology15

LinkedList LinkedList and ArrayList are both subclass of List ArrayList is implemented by an array LinkedList is implemented by a doubly linked list It is used like an ArrayList Because they are brothers! (subclass of List) Fall 2010Sharif University of Technology16

LinkedList Example List list = new LinkedList (); list.add("Ali"); list.add("Taghi"); System.out.println(list.get(0)); list.remove("Taghi"); for (String string : list) { System.out.println(string); } Fall 2010Sharif University of Technology17

ArrayList vs. LinkedList LinkedList stores two links for each element if you want to do many insertions and removals in the middle of a list a LinkedList is better If not, an ArrayList is typically faster Fall 2010Sharif University of Technology18

Array, ArrayList and LinkedList Fall 2010Sharif University of Technology19

How to Test Performance? long start = System.currentTimeMillis(); doSomthing(); long end = System.currentTimeMillis(); System.err.println(end - start); Fall 2010Sharif University of Technology20

Iterator Iterator is a mechanism for walking on elements of a collection Before foreach (before Java5) it was the only mechanism iterator() is declared in Iterable interface Fall 2010Sharif University of Technology21

Iterator public interface Iterable { Iterator iterator(); } public interface Collection extends Iterable {…} Fall 2010Sharif University of Technology22

Iterator Class public interface Iterator { boolean hasNext(); E next(); void remove(); } Fall 2010Sharif University of Technology23

Iterator Example ArrayList arrayList = new ArrayList (); arrayList.add(4); arrayList.add(5); for (Integer next : arrayList) { System.out.println(next); } Iterator iterator = arrayList.iterator(); while(iterator.hasNext()){ Integer next = iterator.next(); System.out.println(next); } Fall 2010Sharif University of Technology24

Concurrent Modification Suppose some processes are modifying the same collection Java containers have a mechanism to prevent it Suppose you’re in the middle of iterating through a container And then some other process steps in and changes an object in that container Insert, remove, … there are many scenarios for disaster. Maybe you’ve already passed that element in the container Maybe it’s ahead of you Maybe the size of the container shrinks after you call size( ) Fall 2010Sharif University of Technology25

Fail Fast Aspect If a collection is modified by one of its methods after an iterator is created for that collection The iterator immediately becomes invalid Any operations performed with the iterator after this point throw ConcurrentModificationExceptions For this reason, iterators are said to be “fail fast” Fall 2010Sharif University of Technology26

ConcurrentModificationException public class FailFast { public static void main(String[] args) { Collection c = new ArrayList (); Iterator it = c.iterator(); c.add("An object"); String s = it.next(); } Fall 2010Sharif University of Technology27 //Exception line

ConcurrentModificationException ArrayList list = new ArrayList (); list.add(1); list.add(2); list.add(3); list.add(4); for (Integer integer : list) if(integer.equals(2)) list.remove(integer); Fall 2010Sharif University of Technology28 //Exception line

Arrays A utility class with many useful static methods For arrays With methods for Copy Fill Sort Search … Fall 2010Sharif University of Technology29

Arrays Long[] array = new Long[100]; Arrays.fill(array, 5); Long[] copy = Arrays.copyOf(array, 200); //An unmodifiable list: List asList = Arrays.asList(1, 2, 3, 4); List asList2 = Arrays.asList(array); Arrays.sort(array); Fall 2010Sharif University of Technology30

Collections A utility class for collections Copy Fill Sort Search … Fall 2010Sharif University of Technology31

Collections Fall 2010Sharif University of Technology32

Other Containers Fall 2010Sharif University of Technology33

hashCode() Fall 2010Sharif University of Technology34