Interview Questions On Collection Framework
Interview Questions On Collection Framework
1 .What is Collection?
Collection : A collection (also called a container) is an object that groups multiple elements into
a single unit.
2 What is a Collections Framework?
Collections Framework : Collections framework provides a unified architecture for
manipulating and representing collections.
3 .What are the benefits of the Java Collections Framework?
Benefits of Collections Framework :
1. Improves program quality and speed
2. Increases the chances of reusability of software
3. Decreases programming effort.
4. What is the root interface in the collection hierarchy?
The root interface in the collection hierarchy is the Collection interface. Few interviewers
may argue that the Collection interface extends the Iterable interface. So iterable should be the
root interface. But you should reply Iterable interface present in java.lang package not in java.util
package. It is clearly mentioned in Oracle Collection docs, that Collection interface is a member
of the Java Collections framework. For the Iterable interface Oracle doc, the iterable interface is
not mentioned as a part of the Java Collections framework. So if the question includes collection
hierarchy, then you should answer the question as Collection interface (which is found in
java.util package).
5. What is the difference between Collection and Collections?
The Collection is an interface while Collections is a java class, both are present in java.util
package and part of the java collections framework.
6.Which collection classes are synchronized or thread-safe?
Stack, Properties, Vector, and Hashtable can be used in a multi-threaded environment
because they are synchronized classes (or thread-safe).
7.What is the difference between List and Set?
Set contains only unique elements while List can contain duplicate elements.
Set is unordered while the List is ordered. List maintains the order in which the objects are
added.
8.What is the difference between Map and Set?
Map object has unique keys each containing some value, while Set contains only unique
values.
9.What are the classes implementing List and Set interface?
Class implementing List interface : ArrayList, Vector, LinkedList
Class implementing Set interface : HashSet, TreeSet
10 How to reverse the List in Collections?
There is a built-in reverse method in the Collections class. reverse(List list) accepts the list
as a parameter.
1
11. How will you make Collections readOnly?
We can make the Collection readOnly by using the following lines code:
General : Collections.unmodifiableCollection(Collection c)
Collections.unmodifiableMap(Map m)
Collections.unmodifiableList(List l)
Collections.unmodifiableSet(Set s)
12. What is UnsupportedOperationException?
This exception is thrown to indicate that the requested operation is not supported.
Example of UnsupportedOperationException:
In other words, if you call add() or remove() method on the readOnly collection. We know
readOnly collection can not be modified. Hence, UnsupportedOperationException will be
thrown.
This concurrent Collection class was added in JDK 1.5
13. What are concurrentCollectionClasses?
In jdk1.5, Java Api developers had introduced a new package called java.util.concurrent that
has thread-safe collection classes as they allow collections to be modified while iterating. The
iterator is fail-safe that is it will not throw ConcurrentModificationException.
Some examples of concurrentCollectionClasses are :
a. CopyOnWriteArrayList
b. ConcurrentHashMap
ArrayList:
1.Explain ArrayList in short.?
Java ArrayList is perhaps the simplest and one of the most used data structure
implementation classes of the Java API Library. It is a part of the Java Collection
Framework under the java.util package. On one hand, it behaves like a normal array, providing
all the benefits of it and, on the other, it is a generic re-sizable collection implementation of
the List interface. Java ArrayList is especially used for managing a large number of objects. This
article attempts to provide some information of this utility class with a brief overview of its
structure.
2.How to remove duplicates from ArrayList in Java?
This is as task based question. Since List interface allows duplicates, ArrayList also allowed
it but if you remember Set interface doesn't allow duplicates, which means you can remove
duplicates from ArrayList by converting it into a Set and then back to ArrayList, but how will
you keep the order intact?
Example:
public class RemoveDuplicateArrayList {
public static void main(String[] args) {
List<String> l = new ArrayList<String>();
l.add("Mango");
l.add("Banana");
l.add("Mango");
l.add("Apple");
System.out.println(l.toString());
Set<String> s = new LinkedHashSet<String>(l);
System.out.println(s);
2
}
}
Output:
Before converting to set
[Mango, Banana, Mango, Apple]
After converting to set
[Mango, Banana, Apple]
3 . Difference between an array and ArrayList in Java?
The main differences between the Array and ArrayList are given below.
S Array ArrayList
N
1 The Array is of fixed size, means ArrayList is not of the fixed size we
we cannot resize the array as per can change the size dynamically.
need.
3 Arrays can store primitive data ArrayList cannot store the primitive
types as well as objects. data types it can only store the
objects.
4. How to synchronize ArrayList in Java?
This is a very good task based question. If you remember, ArrayList is not thread-safe, its
not synchronized either, which means you cannot share it between multiple threads if one of
them modifies it. Don't worry, you can synchronize ArrayList by
using Collections.synchronizedList() method. Check answer to understand steps.
Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
public class SynchronizedArrayListDemo {
public static void main(String args[]) {
// An ArrayList which is not synchronize
List<String> listOfSymbols = new ArrayList<String>();
listOfSymbols.add("RELIANCE");
listOfSymbols.add("TATA");
listOfSymbols.add("TECHMAH");
listOfSymbols.add("HDFC");
listOfSymbols.add("ICICI");
// Synchronizing ArrayList in Java
listOfSymbols = Collections.synchronizedList(listOfSymbols);
// While Iterating over synchronized list, you must synchronize
// on it to avoid non-deterministic behavior
3
synchronized(listOfSymbols){
Iterator<String> myIterator = listOfSymbols.iterator();
while(myIterator.hasNext()){
System.out.println(myIterator.next());
}
}
Output
RELIANCE
TATA
TECHMAH
HDFC
ICICI
4
3) Third difference between ArrayList and HashSet is that ArrayList is an ordered collection and
maintains insertion order of elements while HashSet is an unordered collection and doesn't
maintain any order.
4) Fourth difference between ArrayList and HashSet is that ArrayList is backed by an Array
while HashSet is backed by an HashMap instance.
5) Fifth difference between HashSet and ArrayList is that its index based you can retrieve object
by calling get(index) or remove objects by calling remove(index) while HashSet is completely
object based. HashSet also doesn't provide get() method.
7. How to loop over ArrayList in Java?
There are many ways to traverse over ArrayList, you can use classic for loop with index,
or you can take iterator from ArrayList and can use while loop in conjunction with
Iterator.hasNext() method, Or you can use new foreach loop introduced in Java 5, which doesn't
require an index. See the answer for live examples.
import java.util.ArrayList;
import java.util.Iterator;
public class ArrayListLoopExample {
public static void main(String args[]) {
//Creating ArrayList to demonstrate How to loop and iterate over ArrayList
ArrayList<String> games = new ArrayList<String>(10);
games.add("Cricket");
games.add("Soccer");
games.add("Hockey");
games.add("Chess");
System.out.println("original Size of ArrayList : " + games.size());
//Looping over ArrayList in Java using advanced for loop
System.out.println("Looping over ArrayList in Java using advanced for loop");
for(String game: games){
//print each element from ArrayList
System.out.println(game);
}
//You can also Loop over ArrayList using traditional for loop
System.out.println("Looping ArrayList in Java using simple for loop");
for(int i =0; i<games.size(); i++){
String game = games.get(i);
}
//Iterating over ArrayList in Java
Iterator<String> itr = games.iterator();
System.out.println("Iterating over ArrayList in Java using Iterator");
while(itr.hasNext()){
System.out.println("removing " + itr.next() + " from ArrayList in Java");
itr.remove();
}
5
System.out.println("final Size of ArrayList : " + games.size());
}
Output:
original Size of ArrayList : 4
Looping over ArrayList in Java using advanced for loop
Cricket
Soccer
Hockey
Chess
Looping ArrayList in Java using simple for loop
Iterating over ArrayList in Java using Iterator
removing Cricket from ArrayList in Java
removing Soccer from ArrayList in Java
removing Hockey from ArrayList in Java
removing Chess from ArrayList in Java
final Size of ArrayList : 0
8.Difference between Vector and ArrayList in Java?
Vector and ArrayList implements List interface, Vector is synchronized while ArrayList
is not synchronized, which means former is thread-safe and fast while later is not thread-safe and
slow.
ArrayList and Vectors both implement the List interface and both use (dynamically resizable)
arrays for its internal data structure, much like using an ordinary array.
Syntax:
6
list. Setting the value of an existing element is not a structural modification.
7
Iterator it = al.iterator();
while (it.hasNext())
System.out.println(it.next());
// creating Vector
Vector<String> v = new Vector<String>();
v.addElement("Practice");
v.addElement("quiz");
v.addElement("code");
// traversing elements using Enumeration
System.out.println("\nVector elements are:");
Enumeration e = v.elements();
while (e.hasMoreElements())
System.out.println(e.nextElement());
}
}
System.out.println(names);
8
10. How to sort ArrayList in Java?
You can easily sort ArrayList by using Collections.sort() method, all you need to make
sure is that elements implements either Comparable or Comparator interface. Former is used to
sort on natural order while later is used while sorting in custom order.
Example:
import java.util.ArrayList;
import java.util.Collections;
public class CollectionTest {
public static void main(String args[]) {
//Creating and populating ArrayList in Java for Sorting
ArrayList<String> unsortedList = new ArrayList<String>();
unsortedList.add("Java");
unsortedList.add("C++");
unsortedList.add("J2EE");
System.err.println("unsorted ArrayList in Java : " + unsortedList);
//Sorting ArrayList in ascending Order in Java
Collections.sort(unsortedList);
System.out.println("Sorted ArrayList in Java - Ascending order : " + unsortedList);
//Sorting ArrayList in descending order in Java
Collections.sort(unsortedList, Collections.reverseOrder());
System.err.println("Sorted ArrayList in Java - Descending order : " + unsortedList);
}
}
11 . Difference between HashMap and ArrayList in Java?
1) The first difference between ArrayList and HashMap is
that ArrayList implements List interface while HashMap implements Map interface in Java. See
the difference between list and map for more information.
9
5) Another difference between ArrayList and HashMap is that ArrayList allows duplicates
but HashMap doesn't allow duplicates key though it allows duplicate values.
1) When you need to maintain insertion order of elements i.e. the order on which you insert
object into collection.
2) You want fastest access of element by index. get(index) return object from ArrayList with
O(1) time, also known as constant time.
3) You don't mind duplicates. Like any other List implementation, ArrayList also allows
duplicates, you can add same object multiple times in ArrayList.
4) You don't mind null elements. ArrayList is fine, if you add null objects on it but beware of
calling methods on null object, you could get NullPointerException in Java.
5) You are not sharing this list in multi-threaded environment. Beware, ArrayList is not
synchronized, which means if multiple thread is using ArrayList same time and one thread calls
get(index) method, it could receive a totally different element, if earlier element has been
removed. This is just one of the case, there could be many multi-threading issues, if you share
ArrayList without proper synchronization.
10
Example:
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
public class CopyOnWriteArrayListExample{
public static void main(String args[]) {
CopyOnWriteArrayList<String> threadSafeList
= new CopyOnWriteArrayList<String>();
threadSafeList.add("Java");
threadSafeList.add("J2EE");
threadSafeList.add("Collection");
//add, remove operator is not supported by CopyOnWriteArrayList iterator
Iterator<String> failSafeIterator = threadSafeList.iterator();
while(failSafeIterator.hasNext()){
System.out.printf("Read from CopyOnWriteArrayList : %s %n",
failSafeIterator.next());
failSafeIterator.remove(); //not supported in CopyOnWriteArrayList in
Java
}
}
}
//Constructor
public SynchroProblem(List<Integer> numList){
this.numList = numList;
}
@Override
public void run() {
11
System.out.println("in run method");
for(int i = 0; i < 10; i++){
numList.add(i);
try {
// introducing some delay
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output:
in run method
in run method
in run method
Size of list is 27
num - null
num - 0
num - 0
num - 1
12
num - 1
num - 1
num - 2
num - 2
num - 2
num - 3
num - null
num - 3
num - 4
num - 4
num - 4
num - 5
num - 5
num - 5
num - 6
num - 6
num - 7
num - 7
num - 7
num - 8
num - 9
num - 9
num - 9
Options for synchronizing an ArrayList in Java
Now when we know ArrayList is not synchronized and sharing its instance among many threads
may give unpredictable result, we can focus on the other part; how to synchronize an ArrayList
in Java. The options we have are as following-
Let's see the same example used above with one change, now Collections.synchronizedList is
used to synchronize ArrayList.
//Constructor
public SynchroProblem(List<Integer> numList){
13
this.numList = numList;
}
@Override
public void run() {
System.out.println("in run method");
for(int i = 0; i < 10; i++){
numList.add(i);
try {
// introducing some delay
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Output
Size of list is 30
14
15. How to choose between ArrayList and Vector?
ArrayList is unsynchronized and not thread-safe, whereas Vectors are. Only one thread can
call methods on a Vector at a time, which is a slight overhead, but helpful when safety is a
concern. Therefore, in a single-threaded case, arrayList is the obvious choice, but where
multithreading is concerned, vectors are often preferable.
If we don’t know how much data we are going to have, but know the rate at which it grows,
Vector has an advantage, since we can set the increment value in vectors.
ArrayList is newer and faster. If we don’t have any explicit requirements for using either of
them, we use ArrayList over vector.
for-each loop is the best way to iterate a list if you just need to traverse sequentially through a
list.
LINKEDLIST:
1.Explain Linked List in short.?
A linked list may be defined as a linear data structure which can store a collection of items. In
another way, the linked list can be utilized to store various objects of similar types. Each element
or unit of the list is indicated as a node. Each node contains its data and the address of the next
node. It is similar to a chain. Linked lists are used to create graphs and trees.
2.How do you find the middle element of a singly linked list in one pass?
import test.LinkedList.Node;
/**
* Java program to find middle element of linked list in one pass.
* In order to find middle element of a linked list
* we need to find the length first but since we can only
* traverse linked list one time, we will have to use two pointers
* one which we will increment on each iteration while
* other which will be incremented every second iteration.
* So when the first pointer will point to the end of a
15
* linked list, second will be pointing to the middle
* element of a linked list
*
* @author nit
*/
public class LinkedListTest {
public static void main(String args[]) {
//creating LinkedList with 5 elements including head
LinkedList linkedList = new LinkedList();
LinkedList.Node head = linkedList.head();
linkedList.add( new LinkedList.Node("1"));
linkedList.add( new LinkedList.Node("2"));
linkedList.add( new LinkedList.Node("3"));
linkedList.add( new LinkedList.Node("4"));
//finding middle element of LinkedList in single pass
LinkedList.Node current = head;
int length = 0;
LinkedList.Node middle = head;
while(current.next() != null){
length++;
if(length%2 ==0){
middle = middle.next();
}
current = current.next();
}
if(length%2 == 1){
middle = middle.next();
}
16
}
class LinkedList{
private Node head;
private Node tail;
public LinkedList(){
this.head = new Node("head");
tail = head;
}
public Node head(){
return head;
}
public void add(Node node){
tail.next = node;
tail = node;
}
public static class Node{
private Node next;
private String data;
public Node(String data){
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Node next() {
return next;
}
17
public void setNext(Node next) {
this.next = next;
}
public String toString(){
return this.data;
}
}
}
Output:
length of LinkedList: 4
middle element of LinkedList: 2
3.What is linkedlist?
Linked List is a very commonly used linear data structure which consists of group
of nodes in a sequence.
Each node holds its own data and the address of the next node hence forming a chain like
structure.
Linked Lists are used to create trees and graphs.
They are a dynamic in nature which allocates the memory when required.
18
Insertion and deletion operations can be easily implemented.
Stacks and queues can be easily executed.
Linked List reduces the access time.
Let's know more about them and how they are different from each other.
19
Doubly Linked List
In a doubly linked list, each node contains a data part and two addresses, one for
the previous node and one for the next node.
Example:
import java.util.*;
public class Test
{
public static void main(String args[])
{
// Creating object of class linked list
LinkedList<String> object = new LinkedList<String>();
// Adding elements to the linked list
object.add("A");
object.add("B");
object.addLast("C");
object.addFirst("D");
object.add(2, "E");
object.add("F");
20
object.add("G");
System.out.println("Linked list : " + object);
// Removing elements from the linked list
object.remove("B");
object.remove(3);
object.removeFirst();
object.removeLast();
System.out.println("Linked list after deletion: " + object);
// Finding elements in the linked list
boolean status = object.contains("E");
if(status)
System.out.println("List contains the element 'E' ");
else
System.out.println("List doesn't contain the element 'E'");
// Number of elements in the linked list
int size = object.size();
System.out.println("Size of linked list = " + size);
// Get and set elements from linked list
Object element = object.get(2);
System.out.println("Element returned by get() : " + element);
object.set(2, "Y");
System.out.println("Linked list after change : " + object);
}
}
Output:
Linked list : [D, A, E, B, C, F, G]
Linked list after deletion: [A, E, F]
List contains the element 'E'
Size of linked list = 3
Element returned by get() : F
Linked list after change : [A, E, Y]
21
Vector:
1.What is a Vector in Java?
Vectors are similar to arrays, where the elements of the vector object can be accessed via an
index into the vector. Vector implements a dynamic array. Also, the vector is not limited to a
specific size, it can shrink or grow automatically whenever required. It is similar to ArrayList,
but with two differences :
Vector is synchronized.
Vector contains many legacy methods that are not part of the collections framework.
The Vector class implements a growable array of objects. Vectors basically fall in legacy classes
but now it is fully compatible with collections.
Vector implements a dynamic array that means it can grow or shrink as required. Like an array,
it contains components that can be accessed using an integer index
They are very similar to ArrayList but Vector is synchronised and have some legacy method
which collection framework does not contain.
It extends AbstractList and implements List interfaces.
rrayList and Vector both implements List interface and maintains insertion order.
However, there are many differences between ArrayList and Vector classes that are given below.
ArrayList Vector
22
3) ArrayList is not a Vector is a legacy class.
legacy class. It is introduced in
JDK 1.2.
Early versions of java did not include Collections framework. Instead it defined several
classes and one interface to store objects. When collection came these classes reengineered to
support the Collection interfaces. These old classes are known are legacy classes.
Following are the Legacy classes defined by Java.util package
1 Dictionary
2 HashTable
3 Properties
4 Stack
5 Vector
There is only one legacy Interface called Enumeration.
1.what is an enumeration?
2.What is an Iterator ?
23
The Iterator interface provides a number of methods that are able to iterate over
any Collection. Each Java Collection contains the Iterator method that returns
an Iterator instance. Iterators are capable of removing elements from the underlying collection
during the iteration.
3.What is an ListIterator?
We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator
can be used to traverse for List type Objects, but not for Set type of Objects.
By using Iterator we can retrieve the elements from Collection Object in forward direction
only whereas List Iterator, which allows you to traverse in either directions using hasPrevious()
and previous() methods.
ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not
add, only remove the elements.
Enumeration Iterator
Enumeration is used to traverse the Iterator is used to iterate most of the classes in the
24
legacy classes collection framework
like Vector, Stack and HashTable. like ArrayList, HashSet, HashMap, LinkedList etc.
Methods : hasMoreElements() and next
Element() Methods : hasNext(), next() and remove()
25
9. What is difference between fail-fast and fail-safe ?
The Iterator's fail-safe property works with the clone of the underlying collection and thus, it
is not affected by any modification in the collection. All the collection classes in java.util
package are fail-fast, while the collection classes in java.util.concurrent are fail-safe. Fail-fast
iterators throw a ConcurrentModificationException, while fail-safe iterator never throws such an
exception.
26
String[] strs = {".Net", "UNIX"};
Collections.addAll(list, strs);
System.out.println(list);
Collections.addAll(list, list);
System.out.println(list);
}
}
28
}
}
29
9. What will be the output of the following program?
import java.util.*;
public class VectorImplementation {
public static void main(String[] args) {
Vector vect = new Vector();
vect.add("One");
vect.add("Two");
vect.add("Three");
vect.add("Five");
vect.insertElementAt("Numbers In Words", 0);
vect.insertElementAt("Four", 4);
System.out.println("Size : " + vect.size());
for (int i = 0; i < vect.size(); i++) {
System.out.print(vect.elementAt(i) + " ");
}
vect.removeElement("Five");
System.out.println("\nSize : " + vect.size());
System.out.print(vect);
}
}
10. What will be the output of the following program?
import java.util.*;
public class SoftwareProgrammer {
public static void main(String[] args) {
Enumeration seasons;
Vector v = new Vector<>();
v.add("Winter");
v.add("Spring");
v.add("Rainy");
seasons = v.elements();
v.add("Summer");
while (seasons.hasMoreElements()) {
System.out.print(seasons.nextElement() + ", ");
}
}
}
11. What will be the output of the following program?
import java.util.*;
public class BinarySearch{
public static void main(String[] args){
Vector<String> characters = new Vector<String>();
characters.add("M");
characters.add("E");
30
characters.add("R");
characters.add("I");
characters.add("T");
Collections.reverse(characters);
Collections.sort(characters);
int position = Collections.binarySearch(characters, "I");
System.out.println("Character found at : " + position);
}
}
12. What will be the output of the following program?
import java.util.*;
public class PushPop{
private LinkedList list = new LinkedList();
public void push(Object v){
list.addFirst(v);
}
public Object pop(){
return list.removeFirst();
}
public Object top(){
return list.getFirst();
}
public static void main(String[] args){
PushPop stack = new PushPop();
for (int i = 40; i >= 30; i--)
stack.push(new Integer(i));
System.out.print(stack.top() + " ");
System.out.print(stack.pop() + " ");
stack.push(10);
System.out.print(stack.top() + " ");
System.out.print(stack.pop() + " ");
System.out.print(stack.pop());
}
}
13. What will be the output of the following program?
import java.util.*;
public class StackImplementation {
public static void main(String[] args) {
Stack bag = new Stack();
bag.push("Java."); bag.push(" ");
bag.push("Learn"); bag.push(" ");
bag.push("Can"); bag.push(" ");
bag.push("You"); bag.push(" ");
bag.push("Campus"); bag.push(" ");
31
bag.push("Merit"); bag.push(" ");
bag.push("In");
System.out.println(bag.peek());
if (!bag.empty()) {
System.out.print(bag.pop());
}
System.out.println("\n" + bag.search("Java."));
}
}
14. What will be the output of the following program?
import java.util.*;
public class TouchMe {
public static void main(String[] args) {
Dictionary d = new Hashtable();
d.put(1, "Mobile");
d.put(2, "Laptop");
d.put(3, "Desktop");
d.put(4, "Notebook");
for (int i = 1; i <= 4; i++) {
System.out.print(d.get(i) + ", ");
}
}
}
15. What will be the output of the following program?
import java.util.*;
public class TouchMe {
public static void main(String[] args) {
Dictionary d = new Hashtable();
d.put(1, "Mobile");
d.put(2, "Laptop");
d.put(3, "Desktop");
d.put(4, "Notebook");
System.out.print(d.get("1") + ", ");
System.out.print(d.get("2") + ", ");
System.out.print(d.get("3") + ", ");
System.out.print(d.get("4"));
}
}
16. What will be the output of the following program?
import java.util.*;
public class HashSearch1{
public static void main(String args[]) {
Hashtable<String, String> hm = new Hashtable<String, String>();
32
hm.put("A", "1");
hm.put("B", "2");
hm.put("C", "3");
if(hm.containsValue("A")){
System.out.println("The Hashtable contains value");
}
else {
System.out.println("The Hashtable does not contains value.");
}
if(hm.containsValue("2")){
System.out.println("The Hashtable contains value.");
}
else {
System.out.println("The Hashtable does not contains value.");
}
}
}
33
hashtable.put("second", "2");
hashtable.put("third", "3");
hashtable.put("third", "3");
hashtable.put("five", "5");
hashtable.put("six", "5");
List<String> list = new ArrayList<String>(hashtable.keySet());
Collections.sort(list);
for(String key : list){
System.out.println(key + " -> " + hashtable.get(key));
}
}
}
19. What will be the output of the following program?
import java.util.*;
public class PropertiesDemo {
public static void main(String args[]) {
Properties colours = new Properties();
colours.put("1", "Yellow");
colours.put("1", "Green");
colours.put("3", "Orange");
colours.put("4", "Red");
Set fruits = colours.keySet();
for (Object frt : fruits) {
System.out.println(frt + " is " + colours.getProperty("" + frt) + ".");
}
String str = colours.getProperty("5", "Not found");
System.out.println("5 is " + str + ".");
}
}
20. What will be the output of the following program?
import java.util.*;
public class Test {
public static void main(String[] args) {
Map hashMap = new HashMap();
Map weakHashMap = new WeakHashMap();
String keyHashMap = new String("Map");
String keyWeakHashMap = new String("WeakHashMap");
hashMap.put(keyHashMap, "Merit");
weakHashMap.put(keyWeakHashMap, "Campus");
System.gc();
System.out.println(hashMap.get("Map") + " " + weakHashMap.get("WeakHashMap"));
keyHashMap = null;
keyWeakHashMap = null;
System.gc();
34
System.out.println(weakHashMap.get("WeakHashMap") + " " + hashMap.get("Map") );
}
}
21. What will be the output of the following program?
import java.util.*;
public class Wonder {
private enum Gender {
M, F
}
public static void main(String[] args) {
printSize(new HashMap<Gender, Gender>());
printSize(new EnumMap<Gender, Gender>(Gender.class));
}
private static void printSize(Map<Gender, Gender> map) {
map.put(Gender.M, Gender.F);
map.put(Gender.F, Gender.M);
map.put(Gender.M, Gender.M);
map.put(Gender.F, Gender.F);
Set<Map.Entry<Gender, Gender>> set = new HashSet<Map.Entry<Gender, Gender>>(map
.entrySet());
for (Map.Entry<Gender, Gender> e : map.entrySet())
set.add(new AbstractMap.SimpleEntry<Gender, Gender>(e.getKey(), e.getValue()));
System.out.print(set.size());
}
}
22. What will be the output of the following program?
import java.util.HashSet;
public class HashSetExample {
public static void main(String args[]) {
// HashSet declaration
HashSet<String> hset =
new HashSet<String>();
// Adding elements to the HashSet
hset.add("Apple");
hset.add("Mango");
hset.add("Grapes");
hset.add("Orange");
hset.add("Fig");
//Addition of duplicate elements
hset.add("Apple");
hset.add("Mango");
//Addition of null values
hset.add(null);
hset.add(null);
35
//Displaying HashSet elements
System.out.println(hset);
}
}
36
import java.util.*;
class Collection_iterators{
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
27.What will be the output of the following Java program?
import java.util.*;
class Collection_iterators {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
28. What will be the output of the following Java program?
import java.util.*;
class Collection_iterators{
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.shuffle(list);
i.next();
i.remove();
while(i.hasNext())
37
System.out.print(i.next() + " ");
}
}
29.What will be the output of the following Java program?
import java.util.*;
class Arraylist{
public static void main(String args[]){
ArrayList obj1 = new ArrayList();
ArrayList obj2 = new ArrayList();
obj1.add("A");
obj1.add("B");
obj2.add("A");
obj2.add(1, "B");
System.out.println(obj1.equals(obj2));
}
}
30.What will be the output of the following Java program?
import java.util.*;
class Array {
public static void main(String args[]) {
int array[] = new int [5];
for (int i = 5; i > 0; i--)
array[5 - i] = i;
Arrays.sort(array);
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
31.What will be the output of the following Java program?
import java.util.*;
class Array {
public static void main(String args[]) {
int array[] = new int [5];
for (int i = 5; i > 0; i--)
array[5 - i] = i;
Arrays.sort(array);
System.out.print(Arrays.binarySearch(array, 4));
}
}
32.What will be the output of the following Java program?
import java.util.*;
class Array {
public static void main(String args[]) {
int array[] = new int [5];
for (int i = 5; i > 0; i--)
38
array[5 - i] = i;
Arrays.sort(array);
for (int i = 0; i < 5; ++i)
System.out.print(array[i]);;
}
}
33.What will be the output of the following Java program?
import java.util.*;
class Collection_Algos {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
34.What will be the output of the following Java program?
import java.util.*;
class Collection_Algos {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.shuffle(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
35.What will be the output of the following Java program?
import java.util.*;
class Collection_Algos {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
39
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
36.What will be the output of the following Java program?
import java.util.*;
class Collection_Algos {
public static void main(String args[]) {
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
37.What is the output of this program?
import java.util.*;
class Array {
public static void main(String args[]) {
int array[] = new int [5];
for (int i = 5; i > 0; i--)
array[5-i] = i;
Arrays.fill(array, 1, 4, 8);
for (int i = 0; i < 5 ; i++)
System.out.print(array[i]);
}
}
40
}
}
39.What is the output of this program?
import java.util.*;
class hashtable {
public static void main(String args[]) {
Hashtable obj = new Hashtable();
obj.put("A", new Integer(3));
obj.put("B", new Integer(2));
obj.put("C", new Integer(8));
obj.remove(new String("A"));
System.out.print(obj);
}
}
40.What is the output of this program?
import java.util.*;
class Bitset {
public static void main(String args[]) {
BitSet obj = new BitSet(5);
for (int i = 0; i < 5; ++i)
obj.set(i);
obj.clear(2);
System.out.print(obj);
}
}
41. What will be the output of the following program?
import java.util.*;
public class PushPop{
private LinkedList list = new LinkedList();
public void push(Object v){
list.addFirst(v);
}
public Object pop(){
return list.removeFirst();
}
public Object top(){
return list.getFirst();
}
public static void main(String[] args){
PushPop stack = new PushPop();
for (int i = 40; i >= 30; i--)
stack.push(new Integer(i));
System.out.print(stack.top() + " ");
System.out.print(stack.pop() + " ");
stack.push(10);
41
System.out.print(stack.top() + " ");
System.out.print(stack.pop() + " ");
System.out.print(stack.pop());
}
}
42. What will be the output of the following program?
import java.util.*;
public class StackImplementation {
public static void main(String[] args) {
Stack bag = new Stack();
bag.push("Java."); bag.push(" ");
bag.push("Learn"); bag.push(" ");
bag.push("Can"); bag.push(" ");
bag.push("You"); bag.push(" ");
bag.push("Campus"); bag.push(" ");
bag.push("Merit"); bag.push(" ");
bag.push("In");
System.out.println(bag.peek());
if (!bag.empty()) {
System.out.print(bag.pop());
}
System.out.println("\n" + bag.search("Java."));
}
}
43. What will be the output of the following program?
import java.util.*;
public class TouchMe {
public static void main(String[] args) {
Dictionary d = new Hashtable();
d.put(1, "Mobile");
d.put(2, "Laptop");
d.put(3, "Desktop");
d.put(4, "Notebook");
for (int i = 1; i <= 4; i++) {
System.out.print(d.get(i) + ", ");
}
}
}
42
d.put(2, "Laptop");
d.put(3, "Desktop");
d.put(4, "Notebook");
System.out.print(d.get("1") + ", ");
System.out.print(d.get("2") + ", ");
System.out.print(d.get("3") + ", ");
System.out.print(d.get("4"));
}
}
43
List<String> list = new ArrayList<String>(hashtable.keySet());
Collections.sort(list);
for(String key : list)
{
System.out.println(key + " -> " + hashtable.get(key));
}
}
}
47. What will be the output of the following program?
import java.util.*;
import java.util.Map.*;
public class HashTable{
public static void main(String args[]) {
Hashtable<String, String> hashtable = new Hashtable<String, String>();
hashtable.put("first", "1");
hashtable.put("second", "2");
hashtable.put("third", "3");
hashtable.put("third", "3");
hashtable.put("five", "5");
hashtable.put("six", "5");
List<String> list = new ArrayList<String>(hashtable.keySet());
Collections.sort(list);
for(String key : list){
System.out.println(key + " -> " + hashtable.get(key));
}
}
}
48. What will be the output of the following program?
import java.util.*;
public class PropertiesDemo {
public static void main(String args[]) {
Properties colours = new Properties();
colours.put("1", "Yellow");
colours.put("1", "Green");
colours.put("3", "Orange");
colours.put("4", "Red");
Set fruits = colours.keySet();
for (Object frt : fruits) {
System.out.println(frt + " is " + colours.getProperty("" + frt) + ".");
}
String str = colours.getProperty("5", "Not found");
System.out.println("5 is " + str + ".");
}
}
44
49. What will be the output of the following program?
import java.util.*;
public class Test {
public static void main(String[] args) {
Map hashMap = new HashMap();
Map weakHashMap = new WeakHashMap();
String keyHashMap = new String("Map");
String keyWeakHashMap = new String("WeakHashMap");
hashMap.put(keyHashMap, "Merit");
weakHashMap.put(keyWeakHashMap, "Campus");
System.gc();
System.out.println(hashMap.get("Map") + " " + weakHashMap.get("WeakHashMap"));
keyHashMap = null;
keyWeakHashMap = null;
System.gc();
System.out.println(weakHashMap.get("WeakHashMap") + " " + hashMap.get("Map") );
}
}
50. What will be the output of the following program?
import java.util.*;
public class Wonder {
private enum Gender {
M, F
}
public static void main(String[] args) {
printSize(new HashMap<Gender, Gender>());
printSize(new EnumMap<Gender, Gender>(Gender.class));
}
private static void printSize(Map<Gender, Gender> map) {
map.put(Gender.M, Gender.F);
map.put(Gender.F, Gender.M);
map.put(Gender.M, Gender.M);
map.put(Gender.F, Gender.F);
Set<Map.Entry<Gender, Gender>> set = new HashSet<Map.Entry<Gender, Gender>>(map
.entrySet());
for (Map.Entry<Gender, Gender> e : map.entrySet())
set.add(new AbstractMap.SimpleEntry<Gender, Gender>(e.getKey(), e.getValue()));
System.out.print(set.size());
}
}
45
// HashSet declaration
HashSet<String> hset =
new HashSet<String>();
46