Day 7&8 Collections
Day 7&8 Collections
Interfaces Implementations
Collections
Framework
▪ Implementations
▪ Concrete implementations of the interfaces.
▪ Can also be treated as reusable data structures.
▪ Are the algorithms / methods that perform the manipulations on these collections.
▪ There are other utility interfaces, viz. Comparator, Iterator, & Enumerator.
Collection Map
SortedSet
▪ List
▪ SortedSet
▪ SortedMap
▪ maintains keys in sorted order.
▪ is implemented by TreeMap.
Key Value
▪ Defines "natural order" for that object class; provides only one sort order
▪ Method to be override
• public int compareTo( Object o );
▪ Comparator
▪ Method to override
–public int compare(Object a, Object b)
▪ Iterator
• provides a way to iterate through any collection.
• Methods:
• boolean hasNext()
–returns true if iteration has any more elements
• Object next()
–returns the next element in the Collection
• void remove()
–removes the last element returned by the iterator
Implementations
Hash
Resizable Array Balanced Tree Linked List
Table
Set HashSet TreeSet
▪ Classes which implement the core interfaces must provide two constructors:
▪ A default, no-argument constructor, which creates an empty collection, and
▪ A constructor which takes a Collection as an argument and creates a new
collection with the same elements as the specified collection.
18 Copyright © 2016 Tech Mahindra. All Rights Reserved.
Collections Framework
-Algorithms
▪ These algorithms are static and come from the Collections class.
▪ Searching
▪ searches for a specific element using binary search
▪ Shuffling
▪ does the opposite of sorting by destroying the order
▪ Data Manipulation
▪ reverse (reverses the order of elements),
▪ fill (reinitializes the List to a specific value),
▪ copy (copies elements of one List into another),
▪ swap (swaps the elements at specified positions), and
▪ addAll (adds specified elements or an array to a Collection).
▪ ArrayList can hold only objects; however, autoboxing which makes it appear
that ArrayList can hold primitives too.
▪ Constructors
• ArrayList ()
• ArrayList (Collection c)
▪ Constructors
• Vector ()
• Vector (Collection c)
• Vector (int initialCapacity)
• Vector (int initialCapacity, int capacityIncrement)
▪ Both key and value should be objects; primitives should be wrapped before
they can be used.
▪ Constructors
• Hashtable ()
• Hashtable(int initialCapacity)
• Hashtable(int initialCapacity, float loadFactor)
• Hashtable(Map map)
▪ Constructors
• HashMap()
• HashMap(int initialCapacity)
• HashMap(int initialCapacity, float loadFactor)
• HashMap(Map map)
▪ Constructors
• TreeMap()
• TreeMap(Comparator c)
• TreeMap(Map m)
• TreeMap(SortedMap m)
▪ Constructors
• HashSet()
• HashSet(Collection c)
• HashSet(int initialCapacity)
• HashSet(int initialCapacity, float loadFactor)
▪ Constructors
• TreeSet()
• TreeSet(Collection c)
• TreeSet(Comparator c)
• TreeSet(SortedSet s)
▪ The StringTokenizer class allows a string to be broken down into tokens, and is
hence called lexical analyzer.
• int countTokens()
returns the number of tokens remaining
• String nextToken()
returns the next token
• Object nextElement()
returns the next token as an Object
Q3. Which implementation of the List interface provides for the fastest insertion
of a new element into the middle of the list?
Q4. _____ allows one null key and many null values
a. Hashtable b. HashMap
▪ Using Generics the Collection classes can be aware of the types they store
Explicit type
casting
36 Copyright © 2016 Tech Mahindra. All Rights Reserved.
With Generics
▪ No explicit type casting
▪ The compiler can now check the type correctness of the program at compile-
time
▪ Improved readability & robustness
No explicit type
casting
37 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Generics
▪ To iterate over generic collections, it’s a good idea to use a generic iterator
while(i.hasNext()) {
String s = i.next();
System.out.println(s);
}
38 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Writing your own generic types
▪ public class Box<T> {
private List<T> contents;
public Box() {
contents = new ArrayList<T>();
}
public T grab() {
if (contents.size() > 0) return contents.remove(0);
else return null;
}
▪ Box<String> myBox = new Box<String>();
▪ myBox.add(“Pen”);
40 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Enhanced for loop - “foreach”
▪ Consider the following example
Integer[] numArray = new Integer[...];
List numList = new LinkedList();
...
int sum = 0;
for (int i = 0; i < numArray.length; i++) {
Integer n = numArray[i];
sum += n.intValue();
}
41 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Enhanced for loop - “foreach”
▪ You can use following syntax
42 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Enhanced for loop - “foreach”
▪ Loop Syntax
for (declaration : expression)
statements
43 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Enhanced for loop - “foreach”
▪ The for-each loop cannot be used
44 Copyright © Tech
2016 Tech Mahindra. All Rights Reserved.
CONFIDENTIAL© Copyright 2008 Mahindra Limited
Summary
In this session, we have covered:
▪ Collection Framework
▪ Interfaces and classes in java.util package
▪ Utility classes
▪ StringTokenizer
▪ Generics
▪ Enhanced “foreach” loop
Disclaimer
Tech Mahindra Limited, herein referred to as TechM provide a wide array of presentations and reports, with the contributions of various
professionals. These presentations and reports are for informational purposes and private circulation only and do not constitute an offer to
buy or sell any securities mentioned therein. They do not purport to be a complete description of the markets conditions or developments
referred to in the material. While utmost care has been taken in preparing the above, we claim no responsibility for their accuracy. We shall
not be liable for any direct or indirect losses arising from the use thereof and the viewers are requested to use the information contained
herein at their own risk. These presentations and reports should not be reproduced, re-circulated, published in any media, website or
otherwise, in any form or manner, in part or as a whole, without the express consent in writing of TechM or its subsidiaries. Any
unauthorized use, disclosure or public dissemination of information contained herein is prohibited. Unless specifically noted, TechM is not
responsible for the content of these presentations and/or the opinions of the presenters. Individual situations and local practices and
standards may vary, so viewers and others utilizing information contained within a presentation are free to adopt differing standards and
approaches as they see fit. You may not repackage or sell the presentation. Products and names mentioned in materials or presentations
are the property of their respective owners and the mention of them does not constitute an endorsement by TechM. Information contained
in a presentation hosted or promoted by TechM is provided “as is” without warranty of any kind, either expressed or implied, including any
warranty of merchantability or fitness for a particular purpose. TechM assumes no liability or responsibility for the contents of a
presentation or the opinions expressed by the presenters. All expressions of opinion are subject to change without notice.