Collections Dwight Deugo Nesa Matic

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
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.
CSC 205 – Java Programming II Lecture 25 March 8, 2002.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
Java Collections Framework COMP53 Oct 24, Collections Framework A unified architecture for representing and manipulating collections Allows collections.
15-Jun-15 Lists in Java Part of the Collections Framework.
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 McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Chapter 10 2D Arrays Collection Classes. Topics Arrays with more than one dimension Java Collections API ArrayList Map.
Chapter 19 Java Data Structures
Java's Collection Framework
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.
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.
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.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
Data structures and algorithms in the collection framework 1.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
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.
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.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
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.
List data type(ADT). Lists Elements : a 1,a 2,a 3,… a i-1,a i, a i+1,…a n Null List contains: 0 elements Types of Operations on list 1.Insertion 2.Deletion.
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.
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.
University of Limerick1 Collections The Collection Framework.
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.
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.
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.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Java Collections CHAPTER 3-February-2003
Fundamental of Java Programming
Sixth Lecture ArrayList Abstract Class and Interface
Chapter 19 Java Data Structures
Java Collections Overview
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
Introduction to Collections
Hashing in java.util
Presentation transcript:

Collections Dwight Deugo Nesa Matic

2 © , Espirity Inc. Additional Contributors None as of September, 2004

3 © , Espirity Inc. Module Overview 1.Collections

4 © , Espirity Inc. Module Road Map 1.Collections  Generic collections  ArrayList  HashMap  Iterator  Vector  Enumeration  Hashtable

5 © , Espirity Inc. What are Collections? Collections are Java objects used to store, retrieve, and manipulate other Java objects  Any Java object may be part of a collection, so collection can contain other collections Unlike arrays, collections do not store primitives Unlike arrays, collections can store different objects  Not all objects in a collection must be the same Java type

6 © , Espirity Inc. Collection Architecture… Java collection architecture that includes:  Interfaces - abstract data types representing collections  Implementation - concrete implementation of collection interfaces  Algorithms - methods for manipulating collection objects

7 © , Espirity Inc. …Collection Architecture Collection framework benefits include:  Reusability  Uniformity  Faster development  Higher quality  Interoperability  Less programming

8 © , Espirity Inc. Interfaces Collection SetList SortedSet Map SortedMap Interfaces allow collections to be manipulated independently of the details of their representation.

9 © , Espirity Inc. Collection Interface Collection represents group of objects  These collection objects are known as collection elements There is no direct implementation of this interface in JDK  Concrete implementations are provided for subtypes Collections in general can allow duplicate elements, and can be ordered  Unordered collections that allow duplicate elements should implement directly Collection interface

10 © , Espirity Inc. Adding Elements In general two methods are defined for adding elements to the collection: /** * Adds element to the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean add(Object element); /** * Adds each element from collection c to the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean addAll(Collection c);

11 © , Espirity Inc. Removing Elements /** * Removes element from the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean remove(Object element); /** * Removes each element contained in collection c from the receiver. * Returns true if operation is successful, otherwise returns false. */ boolean removeAll(Collection c); Similarly to adding protocol, there are two methods are defined for removing elements from the collection:

12 © , Espirity Inc. Other Collection Protocol Includes methods for:  Checking how many elements are in the collection  Checking if an element is in the collection  Iterating through collection boolean contains(Object element); boolean containsAll(Collection c); int size(); boolean isEmpty(); void clear(); boolean retainAll(Collection c); Iterator iterator;

13 © , Espirity Inc. Iterating Through Collection Possible through use of Iterator interface, which defines protocol for iterating through underlying collection: /** * Returns whether or not the underlying collection has next * element for iterating. */ boolean hasNext(); /** * Returns next element from the underlying collection. */ Object next(); /** * Removes from the underlying collection the last element returned by next. */ void remove();

14 © , Espirity Inc. Set Interface Set is a collection that does not contain duplicate elements  This is supported by additional behavior in constructors and add(), hashCode(), and equals() methods  All constructors in a set must create a set that does not contain duplicate elements It is not permitted for a set to contain itself and an element If set element changes, and that affects equals comparisons, the behavior of a set is not specified

15 © , Espirity Inc. List Interface List represents an ordered collection  Also known as sequence Lists may contain duplicate elements Lists extend behavior of collections with operations for:  Positional Access  Search  List Iteration  Range-view

16 © , Espirity Inc. Map Interface Map is an object that maps keys to values  Keys must be unique, i.e. map cannot contain duplicate keys  Each key in the map can map to most one value, i.e. one key cannot have multiple values Map interface defines protocols for manipulating keys and values

17 © , Espirity Inc. Most Commonly Used Collections The most commonly used collections include:  Collection framework collections:  ArrayList  HashMap  HashSet  Legacy collections re-implemented with the collection framework:  Vector  Hashtable

18 © , Espirity Inc. ArrayList Represents resizable-array implementation of the List interface  Permits all elements including null It is generally the best performing List interface implementation Instances of this class have a capacity  It is size of the array used to store the elements in the list, and it’s always at least as large as the list size  It grows as elements are added to the list

19 © , Espirity Inc. ArrayList Examples //declare list ArrayList list = new ArrayList(); //add elements to the list list.add("First element"); list.add("Second element"); //get the list size int listSize = list.size(); //print the list size and the first element System.out.println(listSize); System.out.println(list.get(0)); //add first element in the list list.add(0,"Added element"); //get the list iterator Iterator iterator = list.iterator(); while(iterator.hasNext()){ //print next element of the list System.out.println(iterator.next()); } 2 First element Console Added element First element Second element Console

20 © , Espirity Inc. HashMap Collection that contains pair of objects  Values are stored at keys It is a hash table based implementation of the Map interface  Permits null values and null keys  The order of the map is not guaranteed Two parameters affect performance of a hash map:  Initial capacity, indicates capacity at the map creation time  Load factor, indicates how full the map should be before increasing its size  0.75 is the default

21 © , Espirity Inc. HashMap Example //create a number dictionary HashMap numberDictionary = new HashMap(); numberDictionary.put("1", "One"); numberDictionary.put("2", "Two"); numberDictionary.put("3", "Three"); numberDictionary.put("4", "Four"); numberDictionary.put("5", "Five"); //get an iterator of all the keys Iterator keys = numberDictionary.keySet().iterator(); while (keys.hasNext()) { String key = (String)keys.next(); String value = (String)numberDictionary.get(key); System.out.println("Number: " + key + ", word: " + value); } Number: 5, word: Five Number: 4, word: Four Number: 3, word: Three Number: 2, word: Two Number: 1, word: One Console

22 © , Espirity Inc. HashSet Concrete implementation of the Set interface  Backed up by an instance of HashMap  Permits null elements  Order is not guaranteed Performance of the set is affected by size of the set and capacity of the map  It is important not to set the initial capacity too high, or the load factor too low if performance of iteration is important Elements in the set cannot be duplicated

23 © , Espirity Inc. HashSet Example //create new set HashSet set = new HashSet(); //add elements to the set set.add("One"); set.add("Two"); set.add("Three"); //elements cannot be duplicated in the set set.add("One"); //print the set System.out.println(set); [One, Three, Two] Console

24 © , Espirity Inc. Comparable Interface Provides natural ordering for classes  Natural comparison method for classes is compareTo() method Objects that implement this interface can be:  Used as keys in a sorted map or elements in a sorted set  Sorted automatically by Collections.sort protocol It is strongly recommended that natural orderings be consistent with equals, and this is if:  object1.compareTo(object2)==0 has the same boolean value as object1.equals(object2)  Where object1 and object2 are of same type (instances of the same class)

25 © , Espirity Inc. SortedSet Interface Guaranties that its elements are sorted in the natural ordering  All elements of the set must implement the Comparable interface Comparator can be used instead of Comparable interface  Provided to the set at the set creation time  In this case comparator() method of the set returns the comparator object  It is null if natural ordering is used Class TreeSet is a concrete implementation of this interface

26 © , Espirity Inc. SortedMap Interface This interface is analogue map interface to SortedSet interface Guaranties that its keys are sorted in the natural ordering  All keys must implement the Comparable interface  Or Comparator can be at the map creation time Class TreeMap is a concrete implementation of this interface

27 © , Espirity Inc. Legacy Collections (before JDK 1.2) Collections used prior the collection framework was introduced  Collections prior JDK 1.2 Still exist in the JDK versions 1.2 and greater  Provides backwards capability for legacy Java code Still can be used, although classes from the framework are recommended  Legacy collections are re-implemented to follow the framework model  Vector, and Hashtable classes, and Enumeration interface are part of legacy collections

28 © , Espirity Inc. Vector Represents objects array that can grow  Elements can be accessed by index  Its size can grow or shrink to accommodate adding or removing items Optimize storage management by maintaining:  capacity – indicates vector size  capacityIncrement – represents chunk for which storage increases Equivalent to ArrayList class  Since JDK 1.2 Vector implements List interface Vectors are synchronized

29 © , Espirity Inc. Vector Example //declare vector Vector vector = new Vector(); //add elements to the vector vector.add("First element"); vector.add("Second element"); //get the vector size int vectorSize = vector.size(); System.out.println(vectorSize); System.out.println(vector.get(0)); 2 First element Console

30 © , Espirity Inc. Enumeration An interface used for iterating through collections prior the JDK 1.2  Replaced by Iterator in the collection framework  Does not allow underlying collection to be changed while looping through the collection Protocol:  hasMoreElements()  nextElement()

31 © , Espirity Inc. Enumeration example //declare vector Vector vector = new Vector(); //add elements to the vector vector.add("First element"); vector.add("Second element"); //get the vector size int vectorSize = vector.size(); //print the vector size and the first element System.out.println(vectorSize); System.out.println(vector.get(0)); //add first element in the vector vector.add(0,"Added element"); //get the vector elements Enumeration enumeration = vector.elements(); while(enumeration.hasMoreElements()){ //print next element of the vector System.out.println(enumeration.nextElement()); } 2 First element Console Added element First element Second element Console

32 © , Espirity Inc. Hashtable Similar to HashMap  Since JDK 1.2 it implements Map interface to be part of the collection framework Keys and values can be any type of object  Duplicate keys are not allowed It is synchronized collection

33 © , Espirity Inc. Hashtable example //create a number dictionary Hashtable numberDictionary = new Hashtable(); numberDictionary.put("1", "One"); numberDictionary.put("2", "Two"); numberDictionary.put("3", "Three"); numberDictionary.put("4", "Four"); numberDictionary.put("5", "Five"); //get an iterator of all the keys Iterator keys = numberDictionary.keySet().iterator(); while (keys.hasNext()){ String key = (String)keys.next(); String value = (String)numberDictionary.get(key); System.out.println("Number: " + key + ", word: " + value); } Number: 5, word: Five Number: 4, word: Four Number: 3, word: Three Number: 2, word: Two Number: 1, word: One Console

34 © , Espirity Inc. Review In this module we discussed:  Declaring and creating arrays  Initializing and using arrays  Collections Framework  ArrayList  HashMap  Iterator  HashSet  Vector, Enumeration and Hashtable

35 © , Espirity Inc. Labs! Lab: Collections