0% found this document useful (0 votes)
1 views28 pages

module 2 collections

The document provides an overview of the Java Collections Framework, detailing its structure, goals, and recent enhancements such as generics and autoboxing. It explains various collection interfaces like Collection, List, Set, and their implementations, including LinkedList, ArrayList, and HashSet, along with their key features and methods. Additionally, it discusses common exceptions and methods associated with collections, emphasizing the importance of type safety and performance in managing groups of objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views28 pages

module 2 collections

The document provides an overview of the Java Collections Framework, detailing its structure, goals, and recent enhancements such as generics and autoboxing. It explains various collection interfaces like Collection, List, Set, and their implementations, including LinkedList, ArrayList, and HashSet, along with their key features and methods. Additionally, it discusses common exceptions and methods associated with collections, emphasizing the importance of type safety and performance in managing groups of objects.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Module-1: 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.

Dept.of ISE, KIT, Tiptur Naveen N Page 1


Module-1: Collections

2. Collections and Autoboxing


→ We have studied that Autoboxing converts primitive types into Wrapper class Objects. As
collections doesn't store primitive data types(stores only refrences), hence Autoboxing
facilitates the storing of primitive data types in collection by boxing it into its wrapper
type.
3. Using for-each loop
→ for-each version of for loop can also be used for traversing each element of a collection.
→ But this can only be used if we don't want to modify the contents of a collection and we
don't want any reverse access.
→ for-each loop can cycle through any collection of object that implements Iterable interface.
import java.util.*;
class ForEachDemo {
public static void main(String[] args) {
LinkedList< String> ls = new LinkedList< String>();
ls.add("a"); ls.add("b"); ls.add("c"); ls.add("d");
for(String str : ls) {
System.out.print(str+" ");
} } }
2. Draw a neat diagram to show collection hierarchy
Collection Hierarchy
All these Interfaces give several methods which are defined by collections classes which
implement these interfaces.

Dept.of ISE, KIT, Tiptur Naveen N Page 2


Module-1: Collections

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 3


Module-1: Collections

Most commonly thrown Exceptions in Collections interfaces


Exception Name Description
UnSupportedOperationException occurs if a Collection cannot be modified
ClassCastException occurs when one object is incompatible with another
NullPointerException occurs when you try to store null object in Collection
IllegalArgumentException thrown if an invalid argument is used
IllegalStateException thrown if you try to add an element to an already full Collection
Most commonly used methods in the collection interfaces.
Methods Description
boolean add( E obj ) Used to add objects to a collection. Returns true if obj
was added to the collection. Returns false if obj is already
a member of the collection, or if the collection does not
allow duplicates.
boolean addAll( Collection C ) Add all elements of collection C to the invoking
collection. Returns true if the element were added.
Otherwise, returns false.
boolean remove( Object obj ) To remove an object from collection. Returns true if the
element was removed. Otherwise, returns false.
int size() Returns number of elements present in collection.
void clear() Removes total number of elements from the collection.
Object[] toArray() Returns an array which consists of the invoking collection
elements.
Iterator iterator( ) Returns an iterator for the invoking collection.
Object get( int index ) Returns object stored at the specified index
Object get( int index ) Returns object stored at the specified index
Object poll() Removes element at the head of the queue and returns
null if queue is empty

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 4


Module-1: Collections

The standard collection classes are:


Class Description
→ Java LinkedList class uses doubly linked list to store the elements.
→ It provides a linked-list data structure.
→ It inherits the AbstractList class and implements List and Deque interfaces.
→ The important points about Java LinkedList are:
i. Java LinkedList class can contain duplicate elements.
ii. Java LinkedList class maintains insertion order.
iii. Java LinkedList class is non-synchronized.
iv. In Java LinkedList class, manipulation is fast because no shifting needs to
be occurred.
v. Java LinkedList class can be used as list, stack or queue.
→ LinkedList is a generic class that has this declaration:
class LinkedList<E>
LinkedList
Here, E specifies the type of objects that the list will hold.
→ LinkedList has two constructors.
1. LinkedList() - It creates an empty LinkedList
2. LinkedList(Collection C) - It creates a LinkedList that is initialized
with elements of the Collection c
import java.util.*;
public class TestCollection { public static void main(String args[]) {
LinkedList<String> al=new LinkedList<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 ArrayList class uses a dynamic array for storing the elements.
→ It inherits AbstractList class and implements List interface.
→ The important points about Java ArrayList class are:
i. Java ArrayList class can contain duplicate elements.
ArrayList ii. Java ArrayList class maintains insertion order.
iii. Java ArrayList class is non synchronized.
iv. Java ArrayList allows random access because array works at the index basis.
v. In Java ArrayList class, manipulation is slow because a lot of shifting
needs to be occurred if any element is removed from the array list.

Dept.of ISE, KIT, Tiptur Naveen N Page 5


Module-1: Collections

→ ArrayList is a generic class that has this declaration:


class ArrayList<E>
Here, E specifies the type of objects that the list will hold.
→ ArrayList has three constructors.
1. ArrayList() - It creates an empty ArrayList
2. ArrayList(Collection C) - It creates an ArrayList that is initialized with
elements of the Collection C
3. ArrayList(int capacity) - It creates an ArrayList that has the specified
initial capacity
import java.util.*;
class TestCollection { public static void main(String args[]) {
ArrayList<String> al=new ArrayList<String>();
al.add("Ravi"); al.add("Vijay"); al.add("Ravi"); al.add("Ajay");
Iterator itr=al.iterator();
while(itr.hasNext()) { System.out.println(itr.next()); }
} }
→ The ArrayDeque class provides the facility of using deque and resizable-
array.
→ It inherits AbstractCollection class and implements the Deque interface.
→ The important points about ArrayDeque class are:
i. Unlike Queue, we can add or remove elements from both sides.
ii. Null elements are not allowed in the ArrayDeque.
iii. ArrayDeque is not thread safe, in the absence of external synchronization.
iv. ArrayDeque has no capacity restrictions.
v. ArrayDeque is faster than LinkedList and Stack.
ArrayDeque → ArrayDeque is a generic class that has this declaration:
class ArrayDeque<E>
Here, E specifies the type of objects stored in the collection.
→ ArrayDeque defines the following constructors:
1. ArrayDeque( ) – It builds an empty deque. Its starting capacity is 16.
2. ArrayDeque(int size) – It builds a deque that has the specified initial
capacity.
3. ArrayDeque(Collection c) – It creates a deque that is initialized with the
elements of the collection passed in c. .

Dept.of ISE, KIT, Tiptur Naveen N Page 6


Module-1: 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.

Dept.of ISE, KIT, Tiptur Naveen N Page 7


Module-1: Collections

→ HashSet has three constructors.


1. HashSet() - This creates an empty HashSet
2. HashSet(Collection C) - This creates a HashSet that is initialized with the
elements of the Collection C
3. HashSet(int capacity) - This creates a HashSet that has the specified initial
capacity
import java.util.*;
class TestCollection { public static void main(String args[]) {
HashSet<String> al=new HashSet<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 LinkedHashSet class is a Hash table and Linked list implementation of
the set interface.
→ It inherits HashSet class and implements Set interface.
→ The important points about Java LinkedHashSet class are:
i. Contains unique elements only like HashSet.
ii. Provides all optional set operations, and permits null elements.
iii. Maintains insertion order.
→ It is a generic class that has this declaration:
class LinkedHashSet<E>
Here, E specifies the type of objects that the set will hold.
→ LinkedHashSet has three constructors.
LinkedHashSet
1. HashSet() - This creates an empty HashSet
2. HashSet(Collection C) - This creates a HashSet that is initialized with
the elements of the Collection C
3. LinkedHashSet(int capacity) - This creates a HashSet that has the
specified initial capacity
import java.util.*;
class TestCollection { public static void main(String args[]) {
LinkedHashSet<String> al=new LinkedHashSet<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()); } } }

Dept.of ISE, KIT, Tiptur Naveen N Page 8


Module-1: Collections

→ 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.

Dept.of ISE, KIT, Tiptur Naveen N Page 9


Module-1: Collections

→ It has four Constructors.


1. TreeSet() - It creates an empty tree set that will be sorted in an
ascending order according to the natural order of the tree set
2. TreeSet( Collection C ) - It creates a new tree set that contains the
elements of the Collection C
3. TreeSet( Comparator comp ) - It creates an empty tree set that will be
sorted according to given Comparator
4. TreeSet( SortedSet ss ) - It creates a TreeSet that contains the elements
of given SortedSet
import java.util.*;
class TestCollection { public static void main(String args[]) {
TreeSet<String> al=new TreeSet<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()); }
} }
Most commonly thrown Exceptions in Collections classes
Exception Name Description
UnSupportedOperationException occurs if a Collection cannot be modified
ClassCastException occurs when one object is incompatible with another
NullPointerException occurs when you try to store null object in Collection
IllegalArgumentException thrown if an invalid argument is used
IllegalStateException thrown if you try to add an element to an already full Collection
Most commonly used methods in the collection classes
Methods Description
boolean add( E obj ) Used to add objects to a collection. Returns true if obj
was added to the collection. Returns false if obj is
already a member of the collection, or if the collection
does not allow duplicates.
boolean addAll( Collection C ) Add all elements of collection C to the invoking
collection. Returns true if the element were added.
Otherwise, returns false.
int size() Returns number of elements present in collection.
void clear() Removes total number of elements from the collection.
Iterator iterator( ) Returns an iterator for the invoking collection.

Dept.of ISE, KIT, Tiptur Naveen N Page 10


Module-1: Collections

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);
} }

6. Write the difference between ArrayList and LinkedList


→ ArrayList and LinkedList both implements List interface and maintains insertion order.
Both are non-synchronized classes.
→ But there are many differences between ArrayList and LinkedList classes that are given
below.
ArrayList LinkedList
It uses dynamic array to store the elements. It uses doubly linked list to store the elements.
Manipulation is slow. Manipulation is faster.
ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List and
Deque interfaces.
ArrayList is better for storing and LinkedList is better for manipulating data.
accessing data.

Dept.of ISE, KIT, Tiptur Naveen N Page 11


Module-1: Collections

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 12


Module-1: Collections

NavigableMap Interface Methods


firstEntry() Returns a key-value mapping associated with the least
key in this map or null if the map is empty
lastEntry() Returns a key-value mapping associated with the greatest
key in the given map or null if the map is empty
SortedMap Interface Methods
firstKey() Returns the first (lowest) key currently in this map.
lastKey() Returns the last (highest) key currently in this map

Most commonly thrown Exceptions in Collections classes


Exception Name Description
UnSupportedOperationException thrown when an attempt is made to change an unmodifiable map.
ClassCastException occurs when one object is incompatible with the elements in a map

IllegalArgumentException thrown if an invalid argument is used


NullPointerException thrown if an attempt is made to use a null object and null is
not allowed in the map.

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 13


Module-1: Collections

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");

Dept.of ISE, KIT, Tiptur Naveen N Page 14


Module-1: Collections

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 15


Module-1: Collections

→ EnumMap has 2 constructors


1. EnumMap(Class keyType) - It is used to create an empty enum map with the specified
key
2. EnumMap(Map m) - It is used to create an enum map initialized from the specified
map
import java.util.*;
public class EnumMapExample {
public enum Days { Monday, Tuesday, Wednesday, Thursday };
public static void main(String[] args) {
EnumMap<Days, String> map = new EnumMap<Days, String>(Days.class);
map.put(Days.Monday, "1"); map.put(Days.Tuesday, "2");
map.put(Days.Wednesday, "3"); map.put(Days.Thursday, "4");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue()); }
} }

9. Briefly explain comparator interface with an example. OR Define comparator.


Explain with an example
Comparator Interface
→ Both Java TreeSet and TreeMap store elements in sorted order. However, it is
the Comparator that defines precisely what sorted order means.
→ Comparator is a generic interface that has this declaration:
interface Comparator<T>
Here, T specifies the type of objects being compared.
→ The Comparator interface defines two methods:
1. int compare(Object obj1, Object obj2) - Returns zero if the objects obj1 and obj2 are
equal. Returns a positive value if obj1 is greater than obj2 Otherwise a negative value is
returned.
2. boolean equals(Object obj) - Returns true if obj and the invoking object are
both Comparator objects and use the same ordering. Otherwise, it returns false.

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;

Dept.of ISE, KIT, Tiptur Naveen N Page 16


Module-1: Collections

// Compare based on tens place


return Integer.compare(tensPlace1, tensPlace2);
} }
public class RandomNumberSorter { public static void main(String[] args) {
int rangeStart = 10; // Specify the start of the range
int rangeEnd = 150; // Specify the end of the range
ArrayList<Integer> randomNumbers = new ArrayList<>();
// Generate random numbers within the range that are multiples of 2 and 5
for (int i = rangeStart; i <= rangeEnd; i++) {
if (i % 2 == 0 && i % 5 == 0) {
randomNumbers.add(i);
} }
// Shuffle the list of random numbers
Collections.shuffle(randomNumbers);
// Sort the numbers based on tens place using the custom comparator
Collections.sort(randomNumbers, new CustomComparator());
// Print the sorted numbers
System.out.println("Sorted random numbers based on tens place:");
for (int num : randomNumbers) {
System.out.print(num + " ");
} }

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

Dept.of ISE, KIT, Tiptur Naveen N Page 17


Module-1: Collections

 There is only one legacy interface called Enumeration


NOTE: All the legacy classes are synchronized
Enumeration interface
→ Enumeration interface defines method to enumerate through collection of objects.
→ This interface is superseded(replaced) by Iterator interface.
→ However, some legacy classes such as Vector and Properties defines several method in
which Enumeration interface is used.
→ It specifies the following two methods
1. boolean hasMoreElements() - It returns true while there are still more elements to
extract and returns false when all the elements have been enumerated.
2. Object nextElement() - It returns the next object in the enumeration
1. Vector class
→ Vector is similar to ArrayList which represents a dynamic array.
→ Vector is declared like this:
class Vector<E>
→ Here, E specifies the type of element that will be stored.
→ With the release of JDK 5, Vector also implements Iterable. This means that Vector is
fully compatible with collections, and a Vector can have its contents iterated by the for-
each loop.
→ Vector class has following 3 constructor
1. Vector() - This creates a default vector, which has an initial size of 10.
2. Vector(int size) - This creates a vector whose initial capacity is specified by size.
3. Vector(Collection c) - This creates a vector that contains the elements of collection c.
import java.util.*;
public class Test { public static void main(String[] args) {
Vector<Integer> ve = new Vector<Integer>();
ve.add(10); ve.add(20); ve.add(30); ve.add(40);
Enumeration en = ve.elements();
while(en.hasMoreElements()) { System.out.println(en.nextElement()); }
}}
2. Hashtable class
→ Like HashMap, Hashtable also stores key/value pair.
→ However neither keys nor values can be null.
→ It is declared like this:
class Hashtable<K, V>
Here, K specifies the type of keys, and V specifies the type of values.

Dept.of ISE, KIT, Tiptur Naveen N Page 18


Module-1: Collections

→ 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) );
}
}}

Dept.of ISE, KIT, Tiptur Naveen N Page 19


Module-1: Collections

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.

Dept.of ISE, KIT, Tiptur Naveen N Page 20


Module-1: Collections

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.

2. The copyOf( ) method


→ The copyOf( ) method was added by Java SE 6.
→ It returns a copy of an array and has the following forms:
1. static boolean[ ] copyOf(boolean[ ] source, int len)
2. static byte[ ] copyOf(byte[ ] source, int len)
3. static char[ ] copyOf(char[ ] source, int len)
4. static double[ ] copyOf(double[ ] source, int len)

Dept.of ISE, KIT, Tiptur Naveen N Page 21


Module-1: Collections

5. static float[ ] copyOf(float[ ] source, int len)


6. static int[ ] copyOf(int[ ] source, int len)
7. static long[ ] copyOf(long[ ] source, int len)
8. static short[ ] copyOf(short[ ] source, int len)
9. static <T> T[ ] copyOf(T[ ] source, int len)
 The original array is specified by source, and the length of the copy is specified by len.
 If the copy is longer than source, then the copy is padded with zeros (for numeric
arrays), nulls (for object arrays), or false (for boolean arrays).
 If the copy is shorter than source, then the copy is truncated.
 If len is negative, a NegativeArraySizeException is thrown.
 If source is null, a NullPointerException is thrown.

3. The copyOfRange( ) method


→ The copyOfRange( ) method was also added by Java SE 6.
→ It returns a copy of a range within an array and has the following forms:
1. static boolean[ ] copyOfRange(boolean[ ] source, int start, int end)
2. static byte[ ] copyOfRange(byte[ ] source, int start, int end)
3. static char[ ] copyOfRange(char[ ] source, int start, int end)
4. static double[ ] copyOfRange(double[ ] source, int start, int end)
5. static float[ ] copyOfRange(float[ ] source, int start, int end)
6. static int[ ] copyOfRange(int[ ] source, int start, int end)
7. static long[ ] copyOfRange(long[ ] source, int start, int end)
8. static short[ ] copyOfRange(short[ ] source, int start, int end)
9. static <T> T[ ] copyOfRange(T[ ] source, int start, int end)
 The original array is specified by source.
 The range to copy is specified by the indices passed via start and end.
 The range runs from start to end –1. If the range is longer than source, then the copy is
padded with zeros (for numeric arrays), nulls (for object arrays), or false (for boolean
arrays).

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[ ])

Dept.of ISE, KIT, Tiptur Naveen N Page 22


Module-1: Collections

4. static boolean equals(double array1[ ], double array2[ ])


5. static boolean equals(float array1[ ], float array2[ ])
6. static boolean equals(int array1[ ], int array2[ ])
7. static boolean equals(long array1[ ], long array2[ ])
8. static boolean equals(short array1[ ], short array2[ ])
9. static boolean equals(Object array1[ ], Object array2[ ])
 Here, array1 and array2 are the two arrays that are compared for equality.
5. The deepEquals( ) method
→ The deepEquals( ) method can be used to determine if two arrays, which might contain
nested arrays, are equal.
→ It has this declaration:
static boolean deepEquals(Object[ ] a, Object[ ] b)
 It returns true if the arrays passed in a and b contain the same elements. If a and b
contain nested arrays, then the contents of those nested arrays are also checked. It
returns false if the arrays, or any nested arrays, differ.

6. The fill( ) method


→ The fill( ) method assigns a value to all elements in an array.
→ In other words, it fills an array with a specified value.
→ The fill( ) method has two versions.
→ The first version, which has the following forms, fills an entire array:
1. static void fill(boolean array[ ], boolean value)
2. static void fill(byte array[ ], byte value)
3. static void fill(char array[ ], char value)
4. static void fill(double array[ ], double value)
5. static void fill(float array[ ], float value)
6. static void fill(int array[ ], int value)
7. static void fill(long array[ ], long value)
8. static void fill(short array[ ], short value)
9. static void fill(Object array[ ], Object value)
 Here, value is assigned to all elements in array.

→ 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)

Dept.of ISE, KIT, Tiptur Naveen N Page 23


Module-1: Collections

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.

7. The sort( ) method


→ The sort( ) method sorts an array so that it is arranged in ascending order. The sort( )
method has two versions.
→ The first version, shown here, sorts the entire array:
1. static void sort(byte array[ ])
2. static void sort(char array[ ])
3. static void sort(double array[ ])
4. static void sort(float array[ ])
5. static void sort(int array[ ])
6. static void sort(long array[ ])
7. static void sort(short array[ ])
8. static void sort(Object array[ ])
9. static <T> void sort(T array[ ], Comparator<? super T> c)
 Here, array is the array to be sorted. In the last form, c is a Comparator that is used to
order the elements of array.
 The last two forms can throw a ClassCastException if elements of the array being
sorted are not comparable.
→ The second version of sort( ) enables you to specify a range within an array that you want
to sort.
→ Its forms are shown here:
1. static void sort(byte array[ ], int start, int end)
2. static void sort(char array[ ], int start, int end)
3. static void sort(double array[ ], int start, int end)
4. static void sort(float array[ ], int start, int end)
5. static void sort(int array[ ], int start, int end)

Dept.of ISE, KIT, Tiptur Naveen N Page 24


Module-1: Collections

6. static void sort(long array[ ], int start, int end)


7. static void sort(short array[ ], int start, int end)
8. static void sort(Object array[ ], int start, int end)
9. static <T> void sort(T array[ ], int start, int end, Comparator c)
 Here, the range beginning at start and running through end–1 within array will be
sorted.
 In the last form, c is a Comparator that is used to order the elements of array.
 All of these methods can throw an IllegalArgumentException if start is greater than
end, or an ArrayIndexOutOfBoundsException if start or end is out of bounds.
 The last two forms can also throw a ClassCastException if elements of the array being
sorted are not comparable.
// Demonstrate Arrays
import java.util.*;
class ArraysDemo { public static void main(String args[]) {
int array[] = new int[10];
for(int i = 0; i < 10; i++) array[i] = -3 * i;
System.out.print("Original contents: ");
display(array);
Arrays.sort(array);
System.out.print("Sorted: ");
display(array);
Arrays.fill(array, 2, 6, -1);
System.out.print("After fill(): ");
display(array);
Arrays.sort(array);
System.out.print("After sorting again: ");
display(array);
System.out.print("The value -9 is at location ");
int index = Arrays.binarySearch(array, -9);
System.out.println(index); }
static void display(int array[]) {
for(int i: array)
System.out.print(i + " ");
System.out.println();
} }

Dept.of ISE, KIT, Tiptur Naveen N Page 25


Module-1: Collections

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()); } } }

Dept.of ISE, KIT, Tiptur Naveen N Page 26


Module-1: Collections

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)); } }

Dept.of ISE, KIT, Tiptur Naveen N Page 27


Module-1: Collections

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?

ArrayList<E> AbstractList<E> List Yes Yes No No

LinkedList<E> AbstractSequentialList<E> List<E>; Yes Yes No No


Deque<E>

Vector<E> AbstractList<E> List<E> Yes Yes No Yes

HashSet<E> AbstractSet<E> Set<E> No No No No

LinkedHashSet<E> HashSet<E> Set<E> No Yes No No

TreeSet<E> AbstractSet<E> Set<E>; No Yes Yes No


NavigableSet<E>;
SortedSet<E>

HashMap<K, V> AbstractMap<K, V> Map<K, V> No No No No

LinkedHashMap HashMap<K, V> Map<K, V> No Yes No No

Hashtable<K, V> Dictionary<K, V> Map<K, V> No No No Yes

TreeMap<K, V> AbstractMap<K, V> Map<K, V>; No Yes Yes No


NavigableMap<K, V>;
SortedMap<K, V>

Dept.of ISE, KIT, Tiptur Naveen N Page 28

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy