Presentation is loading. Please wait.

Presentation is loading. Please wait.

Collections Dwight Deugo Nesa Matic

Similar presentations


Presentation on theme: "Collections Dwight Deugo Nesa Matic"— Presentation transcript:

1 Collections Dwight Deugo (dwight@espirity.com) Nesa Matic (nesa@espirity.com) www.espirity.com

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

3 3 © 2003-2004, Espirity Inc. Module Overview 1.Collections

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

5 5 © 2003-2004, 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 6 © 2003-2004, 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 7 © 2003-2004, Espirity Inc. …Collection Architecture Collection framework benefits include:  Reusability  Uniformity  Faster development  Higher quality  Interoperability  Less programming

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

9 9 © 2003-2004, 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 10 © 2003-2004, 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 11 © 2003-2004, 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 12 © 2003-2004, 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 13 © 2003-2004, 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 14 © 2003-2004, 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 15 © 2003-2004, 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 16 © 2003-2004, 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 17 © 2003-2004, 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 18 © 2003-2004, 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 19 © 2003-2004, 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 20 © 2003-2004, 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 21 © 2003-2004, 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 22 © 2003-2004, 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 23 © 2003-2004, 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 24 © 2003-2004, 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 25 © 2003-2004, 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 26 © 2003-2004, 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 27 © 2003-2004, 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 28 © 2003-2004, 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 29 © 2003-2004, 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 30 © 2003-2004, 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 31 © 2003-2004, 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 32 © 2003-2004, 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 33 © 2003-2004, 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 34 © 2003-2004, 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 35 © 2003-2004, Espirity Inc. Labs! Lab: Collections


Download ppt "Collections Dwight Deugo Nesa Matic"

Similar presentations


Ads by Google