module 2 collections
module 2 collections
1. Define collection framework in java? Mention some of the goals of Collections. Briefly
explain recent changes to collections with an example OR Define collection. List out
some of the goals of collection framework. How recent changes to collection will be
useful? Explain
Collection Framework
→ Collection framework represents a unified architecture for storing and manipulating group
of objects. It has:
1. Interfaces and its implementations i.e. classes
2. Algorithm
The Collections Framework was designed to meet several goals.
→ First, the framework had to be high-performance.
→ Second, the framework had to allow different types of collections to work in a similar
manner and with a high degree of interoperability.
→ Third, extending and/or adapting a collection had to be easy.
→ Finally, mechanisms were added that allow the integration of standard arrays into the
Collections Framework.
→ Algorithms operate on collections and are defined as static methods within the
Collections class.
→ An iterator provides a means of enumerating the contents of a collection.
→ Maps store key/value pairs.
→ Maps are part of the Collections Framework, they are not “collections” in the strict use of
the term.
Recent Changes to Collections
→ Recently, the Collections Framework underwent a fundamental change that significantly
increased its power and streamlined its use.
→ The changes were caused by the
1. addition of generics,
2. autoboxing/unboxing,and
3. the for-each style for loop, by JDK5
1. Why Collections were made Generics?
→ Generics added type safety to Collection framework.
→ Earlier collections stored Object class references which meant any collection could store
any type of object.
→ Hence there were chances of storing incompatible types in a collection, which could
result in run time mismatch. Hence Generics was introduced through which you can
explicitly state the type of object being stored.
3. List and explain different collection interfaces with methods and exceptions OR List
and give brief description on Java collection interfaces OR Write short notes on
i)Collection ii)Deque iii)List iv)Queue v)Set vi)SortedSet vii)NavigableSet
Collection Interfaces
Collection → Enables you to work with groups of object; it is at the top of
Collection hierarchy
→ Its general declaration is, interface Collection < E >
Here, E specifies the type of objects that the collection will hold.
Deque → Extends Queue to handle double ended queue.
→ Its general declaration is, interface Deque < E >
Here, E specifies the type of objects that the Deque will hold.
List → The List interface extends Collection
→ Allows random access and insertion, based on position.
→ It allows Duplicate elements.
→ Its general declaration is, interface List < E >
Here, E specifies the type of objects that the List will hold.
Queue → It extends collection interface.
→ It defines behaviour of queue, that is first-in, first-out.
→ Its general declaration is, interface Queue < E >
Here, E specifies the type of objects that the Queue will hold.
Set → It extends Collection interface
→ It doesn't allow insertion of duplicate elements.
→ Its general declaration is, interface Set < E >
Here, E specifies the type of objects that the Set will hold.
SortedSet → SortedSet interface extends Set interface
→ It arranges added elements in an ascending order.
→ Its general declaration is, interface SortedSet < E >
Here, E specifies the type of objects that the SortedSet will hold.
NavigableSet → NavigabeSet interface extends SortedSet interface
→ It allows retrieval of elements based on the closest match to a given
value or values.
→ Its general declaration is, interface NavigableSet < E >
Here, E specifies the type of objects that the NavigableSet will hold.
4. List and explain different collection classes with methods and exceptions OR List and
give brief description on Java collection classes with an example each OR Write short
notes on i)LinkedList ii)ArrayList iii)Arraydeque iv)EnumSet v)HashSet
vi)LinkedHashSet vii)PriorityQueue viii)TreeSet
The Collection classes
There are some standard classes that implements Collection interface. Some of the classes
provide full implementations that can be used as it is. Others are abstract classes, which
provide skeletal implementations that can be used as a starting point for creating concrete
collections.
import java.util.*;
class TestCollection { public static void main(String args[]) {
ArrayDeque<String> al=new ArrayDeque<String>();
al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()) { System.out.println(itr.next()); }
} }
→ Java EnumSet class is the specialized Set implementation for use with enum
types.
→ It inherits AbstractSet class and implements the Set interface.
→ The important points about ArrayDeque class are:
i. It is not synchronized.
ii. Null elements are not allowed in the EnumSet.
→ It is a generic class that has this declaration:
class EnumSet<E extends Enum<E>>
Here, E specifies the elements
EnumSet import java.util.*;
enum days {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
public class EnumSetExample { public static void main(String[] args) {
Set<days> set1 = EnumSet.allOf(days.class);
System.out.println("Week Days:"+set1);
Set<days> set2 = EnumSet.noneOf(days.class);
System.out.println("Week Days:"+set2);
} }
→ Java HashSet class is used to create a collection that uses a hash table for
storage.
→ It inherits the AbstractSet class and implements Set interface.
→ The important points about Java HashSet class are:
HashSet i. HashSet stores the elements by using a mechanism called hashing.
ii. HashSet contains unique elements only.
→ HashSet is a generic class that has this declaration:
class HashSet<E>
Here, E specifies the type of objects that the set will hold.
→ The PriorityQueue class provides the facility of using queue. But it does not
orders the elements in FIFO manner.
→ It inherits AbstractQueue class.
→ PriorityQueue is a generic class that has this declaration:
class PriorityQueue<E>
Here, E specifies the type of objects stored in the queue.
→ PriorityQueue defines the six constructors shown here:
1. PriorityQueue( ) - The first constructor builds an empty queue. Its
starting capacity is 11.
2. PriorityQueue(int capacity) - The second constructor builds a queue that
has the specified initial capacity.
3. PriorityQueue(int capacity, Comparator comp) - The third constructor
PriorityQueue builds a queue with the specified capacity and comparator.
4. PriorityQueue(Collection c)
5. PriorityQueue(PriorityQueue c)
6. PriorityQueue(SortedSet c)
The last three constructors create queues that are initialized with
the elements of the collection passed in c.
import java.util.*;
class TestCollection { public static void main(String args[]) {
PriorityQueue<String> al=new PriorityQueue<String>();
1. al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay");
2. Iterator<String> itr=al.iterator();
3. while(itr.hasNext()) { System.out.println(itr.next()); }
} }
→ Java TreeSet class implements the Set interface that uses a tree for storage.
→ It inherits AbstractSet class and implements NavigableSet interface.
→ The objects of TreeSet class are stored in ascending order.
→ The important points about Java TreeSet class are:
i. Contains unique elements only like HashSet.
TreeSet
ii. Access and retrieval times are quiet fast.
iii. Maintains ascending order.
→ TreeSet is a generic class that has this declaration:
class TreeSet<E>
Here, E specifies the type of objects that the set will hold.
5. How will you obtain all contents of ArrayList? Explain with an example OR Write a
java program to Obtaining an Array from an ArrayList OR Write a short note on
Getting array from an ArrayList
Getting Array from an ArrayList
→ toArray() method is used to get an array containing all the contents of the ArrayList.
→ Following are some reasons for why you can need to obtain an array from your
ArrayList:
i. To obtain faster processing for certain operations.
ii. To pass an array to methods which do not accept Collection as arguments.
iii. To integrate and use collections with legacy code.
import java.util.*;
class ArrayListToArray {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1); al.add(2); al.add(3); al.add(4);
System.out.println("Contents of al: " + al);
Integer ia[] = new Integer[al.size()];
ia = al.toArray(ia);
int sum = 0;
for(int i : ia) sum += i;
System.out.println("Sum is: " + sum);
} }
7. Define Map. List and give brief description of Map interfaces OR What is Map?
Briefly explain different Map interfaces
→ A Map stores data in key and value association. Both key and values are objects.
→ The key must be unique but the values can be duplicate.
Map Interfaces
1. Map
→ Maps unique key to value.
→ Map is generic and is declared as shown here:
interface Map<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
2. Map.Entry
→ Describe an element in key and value pair in a map. Entry is sub interface of Map.
→ Map.Entry is generic and is declared like this:
interface Map.Entry<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
3. NavigableMap
→ Extends SortedMap to handle the retrieval of entries based on closest match searches
→ NavigableMap is a generic interface that has this declaration:
interface NavigableMap<K,V>
Here, K specifies the type of the keys, and V specifies the type of the values associated with the
keys.
4. SortedMap
→ Extends Map so that key are maintained in an ascending order.
→ SortedMap is generic and is declared as shown here:
→ interface SortedMap<K, V>
→ Here, K specifies the type of keys, and V specifies the type of values.
Commonly used Methods defined by Map
Method Name Description
Map Interfaces Methods
Object get(Object k) Returns values associated with the key k.
Object put(Object k, Object v) Stores an entry in map.
Object putAll(Map m) Put all entries from m in this map.
Set entrySet() Returns Set that contains the entries in a map.
Map.Entry Interface Methods
K getKey() It is used to obtain a key
V getValue() It is used to obtain value.
8. List and explain different Map classes with an example. OR Briefly describe different
Map classes. OR Write short notes on i)HashMap ii)TreeMap iii)LinkedHashMap
iv)EnumMap
Map Classes
1. HashMap class
→ Java HashMap class implements the map interface by using a hashtable.
→ It inherits AbstractMap class and implements Map interface.
→ The important points about Java HashMap class are:
i. A HashMap contains values based on the key.
ii. It contains only unique elements.
iii. It may have one null key and multiple null values.
iv. It maintains no order.
→ HashMap is a generic class that has this declaration:
class HashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
→ HashMap has four constructor.
1. HashMap() - It is used to construct a default HashMap.
2. HashMap(Map m) - It is used to initializes the hash map by using the elements of the
given Map object m.
3. HashMap(int capacity) - It is used to initializes the capacity of the hash map to the
given integer value, capacity.
4. HashMap(int capacity, float fillRatio) - It is used to initialize both the capacity and fill
ratio of the hash map by using its arguments.
import java.util.*;
class TestCollection { public static void main(String args[]) {
HashMap<Integer,String> hm=new HashMap<Integer,String>();
hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue()); }
} }
2. TreeMap class
→ Java TreeMap class implements the Map interface by using a tree.
→ It provides an efficient means of storing key/value pairs in sorted order.
→ The important points about Java TreeMap class are:
i. A TreeMap contains values based on the key. It implements the NavigableMap interface
and extends AbstractMap class.
ii. It contains only unique elements.
iii. It cannot have null key but can have multiple null values.
iv. It is same as HashMap instead maintains ascending order.
→ TreeMap is a generic class that has this declaration:
class TreeMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
→ TreeMap has 4 constructors
1. TreeMap() - It is used to construct an empty tree map that will be sorted using the
natural order of its key.
2. TreeMap(Comparator comp) - It is used to construct an empty tree-based map that will
be sorted using the comparator comp.
3. TreeMap(Map m) - It is used to initialize a tree map with the entries from m, which
will be sorted using the natural order of the keys.
4. TreeMap(SortedMap sm) - It is used to initialize a tree map with the entries from the
SortedMap sm, which will be sorted in the same order as sm.
import java.util.*;
class TestCollection { public static void main(String args[]) {
TreeMap<Integer,String> hm=new TreeMap<Integer,String>();
hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue()); }
} }
3. LinkedHashMap class
→ Java LinkedHashMap class is Hash table and Linked list implementation of the Map
interface, with predictable iteration order.
→ It inherits HashMap class and implements the Map interface.
→ The important points about Java LinkedHashMap class are:
i. A LinkedHashMap contains values based on the key.
ii. It contains only unique elements.
iii. It may have one null key and multiple null values.
iv. It is same as HashMap instead maintains insertion order.
→ LinkedHashMap is a generic class that has this declaration:
class LinkedHashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
→ LinkedHashMap has 4 constructors
1. LinkedHashMap() - It is used to construct a default LinkedHashMap.
2. LinkedHashMap(int capacity) - It is used to initialize a LinkedHashMap with the given
capacity
3. LinkedHashMap(int capacity, float fillRatio) - It is used to initialize both the capacity
and the fillRatio.
4. LinkedHashMap(Map m) - It is used to initialize the LinkedHashMap with the
elements from the given
import java.util.*;
class TestCollection { public static void main(String args[]) {
LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();
hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue()); }
} }
4. EnumMap class
→ Java EnumMap class is the specialized Map implementation for enum keys.
→ It inherits Enum and AbstractMap classes.
→ It is a generic class that has this declaration:
class EnumMap<K extends Enum<K>, V>
Here, K specifies the type of key, and V specifies the type of value.
import java.util.*;
class CustomComparator implements Comparator<Integer> {
public int compare(Integer num1, Integer num2) {
int tensPlace1 = (num1 / 10) % 10;
int tensPlace2 = (num2 / 10) % 10;
10. What are legacy classes? Explain different legacy classes defined by java.util package.
OR Define legacy classes. List and explain legacy classes available in java.util package
Legacy Classes
→ Early version of java did not include the Collections framework. It only defined several
classes and interfaces that provide methods for storing objects. When Collections
frameworks were added in J2SE 1.2, the original classes were reengineered to support the
collection interface. These classes are also known as Legacy classes.
→ All legacy classes and interface were redesign by JDK 5 to support Generics.
→ The following are the legacy classes defined by java.util package
1. Vector
2. HashTable
3. Properties
4. Stack
5. Dictionary
→ There is one more difference between HashMap and Hashtable that is Hashtable is
synchronized while HashMap is not.
→ Hashtable has following four constructor
1. Hashtable() - This is the default constructor. The default size is 11.
2. Hashtable(int size) - This creates a hash table that has an initial size specified by size.
import java.util.*;
class HashTableDemo { public static void main(String args[]) {
Hashtable<Integer, String> hm = new Hashtable<Integer, String>();
hm.put(100,"Amit"); hm.put(101,"Vijay"); hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()) {
System.out.println(m.getKey()+" "+m.getValue()); }
}}
3. Properties class
→ Properties class extends Hashtable class.
→ It is used to maintain list of value in which both key and value are String
→ Properties defines the following instance variable:
Properties defaults;
This variable holds a default property list associated with a Properties object
→ Properties class define two constructor
1. Properties() - This creates a Properties object that has no default values
2. Properties(Properties propdefault) - This creates an object that uses prop default for its
default values.
→ One advantage of Properties over Hashtable is that we can specify a default property that
will be useful when no value is associated with a certain key.
import java.util.*;
public class Test { public static void main(String[] args) {
Properties pr = new Properties();
pr.put("Java", "James Ghosling");
pr.put("C++", "Bjarne Stroustrup");
Set< ?> creator = pr.keySet();
for(Object ob: creator)
{
System.out.println(ob+" was created by "+ pr.getProperty((String)ob) );
}
}}
4. Stack class
→ Stack class extends Vector.
→ It follows last-in, first-out principle for the stack elements.
→ Stack was retrofitted for generics and is declared as shown here:
class Stack<E>
Here, E specifies the type of element stored in the stack.
→ It defines only one default constructor
Stack() - This creates an empty stack
→ If you want to put an object on the top of the stack, call push() method. If you want to
remove and return the top element, call pop() method. An EmptyStackException is
thrown if you call pop() method when the invoking stack is empty.
import java.util.*;
class StackDemo { public static void main(String args[]) {
Stack<Integer> st = new Stack<Integer>();
st.push(11); st.push(22);
st.push(33); st.push(44);
System.out.println(st);
System.out.println("\nAfter Inserting elements");
for(Integer aa:st)
System.out.println(aa);
st.pop(); st.pop();
System.out.println("\nAfter popping out two elements");
for(Integer aa:st)
System.out.println(aa);} }
5. Dictionary class
→ Dictionary is an abstract class.
→ It represents a key/value pair and operates much like Map.
→ It is declared as shown here:
class Dictionary<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
→ Although it is not currently deprecated, Dictionary is classified as obsolete, because it is
fully superseded by Map class.
11. Write a short note on Arrays class methods. OR List and explain different Arrays
class methods. OR With an example briefly explain Arrays class methods.
Arrays
→ The Arrays class provides various methods that are useful when working with arrays.
→ These methods help bridge the gap between collections and arrays.
→ The asList( ) method returns a List that is backed by a specified array. In other words,
both the list and the array refer to the same location.
→ It has the following signature:
static <T> List asList(T ... array)
Here, array is the array that contains the data.
1. binarySearch( ) method
→ The binarySearch( ) method uses a binary search to find a specified value. This method
must be applied to sorted arrays.
1. static int binarySearch(byte array[ ], byte value)
2. static int binarySearch(char array[ ], char value)
3. static int binarySearch(double array[ ], double value)
4. static int binarySearch(float array[ ], float value)
5. static int binarySearch(int array[ ], int value)
6. static int binarySearch(long array[ ], long value)
7. static int binarySearch(short array[ ], short value)
8. static int binarySearch(Object array[ ], Object value)
9. static <T> int binarySearch(T[ ] array, T value, Comparator c)
Here, array is the array to be searched, and value is the value to be located.
The last two forms throw a ClassCastException if array contains elements that cannot
be compared (for example, Double and StringBuffer) or if value is not compatible with
the types in array.
In the last form,the Comparator c is used to determine the order of the elements in
array.
In all cases, if value exists in array, the index of the element is returned. Otherwise, a
negative value is returned.
4. equals( ) method
→ The equals( ) method returns true if two arrays are equivalent. Otherwise, it returns false.
→ The equals( ) method has the following forms:
1. static boolean equals(boolean array1[ ], boolean array2[ ])
2. static boolean equals(byte array1[ ], byte array2[ ])
3. static boolean equals(char array1[ ], char array2[ ])
→ The second version of the fill( ) method assigns a value to a subset of an array.
→ Its forms are shown here:
1. static void fill(boolean array[ ], int start, int end, boolean value)
2. static void fill(byte array[ ], int start, int end, byte value)
3. static void fill(char array[ ], int start, int end, char value)
4. static void fill(double array[ ], int start, int end, double value)
5. static void fill(float array[ ], int start, int end, float value)
6. static void fill(int array[ ], int start, int end, int value)
7. static void fill(long array[ ], int start, int end, long value)
8. static void fill(short array[ ], int start, int end, short value)
9. static void fill(Object array[ ], int start, int end, Object value)
Here, value is assigned to the elements in array from position start to position end–1.
These methods may all throw an IllegalArgumentException if start is greater than end,
or an ArrayIndexOutOfBoundsException if start or end is out of bounds.
12. What is the importance of Generics in Java? What are the advantages of Generics?
Explain with an example. OR What is the use of Generics in Java. Give an example
Generics in Java
→ The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.
→ Before generics, we can store any type of objects in collection i.e. non-generic. Now
generics, forces the java programmer to store specific type of objects.
Advantage of Java Generics
→ There are mainly 3 advantages of generics. They are as follows:
1. Type-safety: We can hold only a single type of objects in generics. It doesn’t allow
storing other objects.
2. Type casting is not required: There is no need to typecast the object.
Before Generics, we need to type cast.
List list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);//typecasting
After Generics, we don't need to typecast the object.
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0);
3. Compile-Time Checking: It is checked at compile time so problem will not occur at
runtime. The good programming strategy says it is far better to handle the problem at
compile time than runtime.
List<String> list = new ArrayList<String>();
list.add("hello");
list.add(32);//Compile Time Error
→ Syntax to use generic collection: Class or Interface<Type>
→ Example to use Generics in java: ArrayList<String>
import java.util.*;
class TestGenerics { public static void main(String args[]) {
ArrayList<String> list=new ArrayList<String>();
list.add("rahul"); list.add("jai");
//list.add(32);//compile time error
String s=list.get(1);//type casting is not required
System.out.println("element is: "+s);
Iterator<String> itr=list.iterator();
while(itr.hasNext()) { System.out.println(itr.next()); } } }
13. Write a short note on collection algorithms OR With an example briefly explain
collection algorithms
The Collection Algorithms
→ The Collections Framework defines several algorithms that can be applied to collections
and maps.
→ These algorithms are defined as static methods within the Collections class.
→ All these algorithms are type safe.
→ Several of the methods can throw a ClassCastException, which occurs when an attempt is
made to compare incompatible types
→ An UnsupportedOperationException, which occurs when an attempt is made to modify an
unmodifiable collection.
→ An attempt to insert an incompatible element will cause a ClassCastException. It is helpful during
debugging because it ensures that the collection always contains valid elements.
→ The set of methods that begins with unmodifiable returns views of the various collections
that cannot be modified.
→ These will be useful when you want to grant some process read-but not write-capabilities
on a collection.
→ Collections defines three static variables: EMPTY_SET, EMPTY_LIST, and
EMPTY_MAP. All are immutable.
import java.util.*;
class AlgorithmsDemo { public static void main(String args[]) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.add(-8); ll.add(20); ll.add(-20); ll.add(8);
// Create a reverse order comparator.
Comparator<Integer> r = Collections.reverseOrder();
// Sort list by using the comparator.
Collections.sort(ll, r);
System.out.print("List sorted in reverse: ");
for(int i : ll) System.out.print(i+ " ");
// Shuffle list.
Collections.shuffle(ll);
// Display randomized list.
System.out.print("List shuffled: ");
for(int i : ll) System.out.print(i + " ");
System.out.println("Minimum: " + Collections.min(ll));
System.out.println("Maximum: " + Collections.max(ll)); } }
Summarization of collection interfaces and classes with Map interfaces and classes
→ The Java collection framework is very powerful and includes numerous capabilities such
as cloning, return values, removing elements, and more.
→ The following table summarizes the principal classes in Java collections framework for
quick reference:
→ From the below table we can conclude the following characteristics of the main
collections in Java Collection Frameworks:
→ All lists allow duplicate elements which are ordered by index.
→ All sets and maps do not allow duplicate elements.
→ All list elements are not sorted.
→ Generally, sets and maps do not sort its elements, except TreeSet and TreeMap – which
sort elements by natural order or by a comparator.
→ Generally, elements within sets and maps are not ordered, except
for: LinkedHashSet and LinkedHashMap have elements ordered by insertion order.
→ TreeSet and TreeMap have elements ordered by natural order or by a comparator.
→ There are only two collections are thread-safe: Vector and Hastable. The rest are not
thread-safe.
Principal Base class Base interfaces Allow Ordered Sorted Thread
collection class duplicate ? ? -safe?
elements?