100% found this document useful (1 vote)
712 views

Interview Questions On Collection Framework

The document provides information about the Java Collections Framework including definitions of Collection, Collections Framework, benefits of the framework, the root interface in the collection hierarchy (Collection), difference between Collection and Collections classes, thread-safe collection classes, differences between List and Set interfaces, classes that implement List and Set, how to reverse a List using Collections.reverse(), make collections read-only, UnsupportedOperationException, concurrent collection classes, overview of ArrayList including differences from array and how to synchronize and remove duplicates from ArrayList.

Uploaded by

thopa jay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
712 views

Interview Questions On Collection Framework

The document provides information about the Java Collections Framework including definitions of Collection, Collections Framework, benefits of the framework, the root interface in the collection hierarchy (Collection), difference between Collection and Collections classes, thread-safe collection classes, differences between List and Set interfaces, classes that implement List and Set, how to reverse a List using Collections.reverse(), make collections read-only, UnsupportedOperationException, concurrent collection classes, overview of ArrayList including differences from array and how to synchronize and remove duplicates from ArrayList.

Uploaded by

thopa jay
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Short Answer 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.

2 Arrays are of the static type. ArrayList is of dynamic size.

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

5. When to use ArrayList and LinkedList in Java?


Before comparing differences of ArrayList and LinkedList, let's see What is common
between ArrayList and LinkedList in Java :
1) Both ArrayList and LinkedList are an implementation of List interface, which means you can
pass either ArrayList or LinkedList if a method accepts the java.util.List interface. 
2) Both ArrayList and LinkedList are not synchronized, which means you can not share them
between multiple threads without external synchronization.
3) ArrayList and LinkedList are ordered collection e.g. they maintain insertion order of elements
i.e. the first element will be added to the first position.
4) ArrayList and LinkedList also allow duplicates and null, unlike any other List implementation
e.g. Vector.
5) Iterator of both LinkedList and ArrayList are fail-fast which means they will
throw ConcurrentModificationException if a collection is modified structurally once Iterator is
created. They are different than CopyOnWriteArrayList whose Iterator is fail-safe.
LinkedList is fast for adding and deleting elements, but slow to access a specific
element. ArrayList is fast for accessing a specific element but can be slow to add to either end,
and especially slow to delete in the middle
6. Difference between ArrayList and HashSet in Java? 
Here are couple of differences between ArrayList and HashSet in Java:
1) First and most important difference between ArrayList and HashSet is
that ArrayList implements List interface while HashSet implements Set interface in Java.
2) Another difference between ArrayList and HashSet is that ArrayListallow
duplicates while HashSet doesn't allow duplicates. This is the side effect of fist difference and
property of implementing List and Set interface.

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:

ArrayList<T> al = new ArrayList<T>();


Vector<T> v = new Vector<T>();
Major Differences between ArrayList and Vector:
1. Synchronization : Vector is synchronized, which means only one thread at a time can
access the code, while arrayList is not synchronized, which means multiple threads can
work on arrayList at the same time. For example, if one thread is performing an add
operation, then there can be another thread performing a remove operation in a
multithreading environment.
If multiple threads access arrayList concurrently, then we must synchronize the block of
the code which modifies the list structurally, or alternatively allow simple element
modifications. Structural modification means addition or deletion of element(s) from the

6
list. Setting the value of an existing element is not a structural modification.

2. Performance: ArrayList is faster, since it is non-synchronized, while vector operations


give slower performance since they are synchronized (thread-safe). If one thread works on
a vector, it has acquired a lock on it, which forces any other thread wanting to work on it to
have to wait until the lock is released.
3. Data Growth: ArrayList and Vector both grow and shrink dynamically to maintain
optimal use of storage – but the way they resize is different. ArrayList increments 50% of
the current array size if the number of elements exceeds its capacity, while vector
increments 100% – essentially doubling the current array size.
4. Traversal: Vector can use both Enumeration and Iterator for traversing over elements of
vector while ArrayList can only use Iterator for traversing.

Note: ArrayList is preferable when there is no specific requirement to use vector.


Example:
// Java Program to illustrate use of ArrayList
// and Vector in Java
import java.io.*;
import java.util.*;   
class Nit{
    public static void main (String[] args) {
        // creating an ArrayList
        ArrayList<String> al = new ArrayList<String>();
          // adding object to arraylist
        al.add("Practice.nit.org");
        al.add("quiz.nit.org");
        al.add("code.nit.org");
        al.add("contribute.nit.org");
          // traversing elements using Iterator'
        System.out.println("ArrayList elements are:");

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

9. How to create and initialize ArrayList in one line?


using ArrayList constructor is traditional approach. We create a blank arraylist using
constructor and add elements to list using add() method. We can add elements either one by one,
or we can pass another collection to add all elements in one step.
Example:
Create arraylist with constructor
ArrayList<String> names = new ArrayList<>();
//1. Add elements one by one
names.add("alex");
names.add("brian");
names.add("charles");
System.out.println(names);
HashMap<String, Integer> details = new HashMap<>();
details.put("keanu", 23);
details.put("max", 24);
details.put("john", 53);
 
//2. Add elements from other collection
names.addAll(details.keySet());
System.out.println(names);
Example:
ArrayList<String> names = new ArrayList<String>( Arrays.asList("alex", "brian",
"charles") );

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. 

2) The second difference between ArrayList and HashMap is that ArrayList only stores one


object while HashMap stores two objects key and value.

3) The third difference between HashMap and ArrayList is that, keys of HashMap must


implements equals and hashCode method correctly, ArrayList doesn't have that requirement but
its good to have that because contains()  method of ArrayList will use equals() method to see if
that object already exists or not.

4) The fourth difference between HashMap and ArrayList is that ArrayList maintains the order


of object, in which they are inserted while HashMap doesn't provide any ordering guarantee.

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.

6) ArrayList get(index) method always gives an O(1) performance but HashMap get(key) can be


O(1) in the best case and O(n) in the worst case.

12. How to use ArrayList in Java?

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.

13. What is CopyOnWriteArrayListv vs ArrayListv in Java?

1) First and foremost difference between CopyOnWriteArrayList and ArrayList in Java is


that CopyOnWriteArrayList is a thread-safe collection while ArrayList is not thread-safe and can not be
used in the multi-threaded environment.

2) The second difference between ArrayList and CopyOnWriteArrayList is that Iterator of ArrayList is


fail-fast and throw ConcurrentModificationException once detect any modification in List once iteration
begins but Iterator of CopyOnWriteArrayList is fail-safe and doesn't
throw ConcurrentModificationException.

3) The third difference between CopyOnWriteArrayList vs ArrayList is that Iterator of former doesn't


support remove operation while Iterator of later supports remove() operation.  If you want to learn more
about collections, I suggest you go through Complete Java MasterClass, one of the best Java course on
Udemy.

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

14. How And Why To Synchronize Arraylist In Java?


First let's see why do we need to synchronize an ArrayList in Java. To understand that
an example is given below where an ArrayList instance is shared among three threads and
each thread is trying to insert ten elements in the ArrayList.
Without Synchronization Example:
public class SynchroProblem implements Runnable{
private List<Integer> numList;

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

public static void main(String[] args) {


List<Integer> numList = new ArrayList<Integer>();
// Creating three threads
Thread t1 = new Thread(new SynchroProblem(numList));
Thread t2 = new Thread(new SynchroProblem(numList));
Thread t3 = new Thread(new SynchroProblem(numList));
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Size of list is " + numList.size());
for(Integer i : numList){
System.out.println("num - " + i);
}
}
}

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-

 We can of course use a Vector which is synchronized.


 Collections class also provide a method synchronizedList(), which returns a
synchronized (thread-safe) list backed by the specified list.
 Another alternative is CopyOnWriteArrayList which is part of the java.util.concurrent
Package.

Let's see the same example used above with one change, now Collections.synchronizedList is
used to synchronize ArrayList.

With synchronization Example:

public class SynchroProblem implements Runnable{


private List<Integer> numList;

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

public static void main(String[] args) {


//List<Integer> numList = new Vector<Integer>();
// Synchronizing the list
List<Integer> numList = Collections.synchronizedList(new ArrayList<Integer>());
// Creating three threads
Thread t1 = new Thread(new SynchroProblem(numList));
Thread t2 = new Thread(new SynchroProblem(numList));
Thread t3 = new Thread(new SynchroProblem(numList));
t1.start();
t2.start();
t3.start();
try {
t1.join();
t2.join();
t3.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Size of list is " + numList.size());
for(Integer i : numList){
System.out.println("num - " + i);
}
}
}

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.

16.How To Loop/iterate An Arraylist In Java?


There are many ways to loop/iterate an arrayList in Java. Options are -
o for loop
o for-each loop
o iterator
o list iterator
o Java 8 forEach loop

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

      System.out.println("length of LinkedList: " + length);


      System.out.println("middle element of LinkedList : "  + middle);
   
    }
 

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?

Introduction to Linked Lists


LinkedList in Java. Linked List are linear data structures where the elements are not
stored in contiguous locations and every element is a separate object with a data part and address
part. The elements are linked using pointers and addresses. Each element is known as a node.

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.

Advantages of Linked Lists

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

Disadvantages of Linked Lists

 The memory is wasted as pointers require extra memory for storage.


 No element can be accessed randomly; it has to access each node sequentially.
 Reverse Traversing is difficult in linked list.

Applications of Linked Lists

 Linked lists are used to implement stacks, queues, graphs, etc.


 Linked lists let you insert elements at the beginning and end of the list.
 In Linked Lists we don't need to know the size in advance.

Types of Linked Lists


There are 3 different implementations of Linked List available, they are:

1. Singly Linked List


2. Doubly Linked List
3. Circular Linked List

Let's know more about them and how they are different from each other.

Singly Linked List


Singly linked lists contain nodes which have a data part as well as an address
part i.e. next, which points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal.

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.

2. How to use vector in java.

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.

3.What is difference between Arraylist and vector.

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

1) ArrayList is not Vector is synchronized.


synchronized.

2) ArrayList increments Vector increments 100% means doubles the


50% of current array size if the array size if the total number of elements
number of elements exceeds exceeds than its capacity.
from its capacity.

22
3) ArrayList is not a Vector is a legacy class.
legacy class. It is introduced in
JDK 1.2.

4) ArrayList is fast because it is Vector is slow because it is synchronized, i.e.,


non-synchronized. in a multithreading environment, it holds the
other threads in runnable or non-runnable state
until current thread releases the lock of the
object.

5) ArrayList uses A Vector can use the Iterator interface


the Iterator interface to traverse or Enumeration interface to traverse the
the elements. elements.

4.What is meaning of legacy.

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?

Enumeration means a list of named constant. In Java, enumeration defines a class type.


An Enumeration can have constructors, methods and instance variables. It is created
using enum keyword. Each enumeration constant is public, static and final by default.

An enumeration, or Enum , is a symbolic name for a set of values. Enumerations are


treated as data types, and you can use them to create sets of constants for use with variables and
properties.Ju

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?

ListIterator in Java is an Iterator which allows user to traverse Collection


like ArrayList and HashSet in both direction by using method previous() and next (). You can
obtain ListIterator from all List implementation including ArrayList and
LinkedList. ListIterator doesn’t keep current index and its current position is determined by call
to next() or previous() based on direction of traversing.
4. Difference between Iterator and ListIterator?

There are three Differences are there:

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.

5.What is the difference between Enumeration and Iterator?

Enumeration Iterator

Using Enumeration, you can only


traverse the collection. You can’t do any
modifications to collection while Using Iterator, you can remove an element of the
traversing it. collection while traversing it.

Enumeration is introduced in JDK 1.0 Iterator is introduced from JDK 1.2

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

Enumeration is fail-safe in nature. Iterator is fail-fast in nature.

Enumeration is not safe and secured due


to it’s fail-safe nature. Iterator is safer and secured than Enumeration.

 6. What do you understand by Iterator in the Java Collection Framework?


Both Iterator and ListIterator are used to iterate through elements of a collection class.
Using Iterator we can traverse in one direction (forward) while using ListIterator we can traverse
the collection class on both the directions(backward and forward).

7.How to use Iterator in Java?

‘Iterator’ is an interface which belongs to collection framework. It allows us to traverse


the collection, access the data element and remove the data elements of the collection.
java.util package has public interface Iterator and contains three methods:
1. boolean hasNext(): It returns true if Iterator has more element to iterate.
2. Object next(): It returns the next element in the collection until the hasNext()method return
true. This method throws ‘NoSuchElementException’ if there is no next element.
3. void remove(): It removes the current element in the collection. This method throws
‘IllegalStateException’ if this function is called before next( ) is invoked.

8. Which design pattern followed by Iterator?


It follows the iterator design pattern. An iterator design pattern provides us to navigate
through the collection of objects by using a common interface without letting us know about the
underlying implementation.

Enumeration is an example of an Iterator design pattern.

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.

Programs and Find Result on Collection Framework


1.What will be the output of the following program?
import java.util.*;
public class AddCollection1{
    public static void main(String args[]){
        List<String> list = new ArrayList<String>();
        Collections.addAll(list, "C", "C++", "C#", "JAVA");
        System.out.println(list);
        String[] strs = {".Net", "UNIX"};
        Collections.addAll(list, strs); //LINE A
        System.out.println(list);
        Collections.addAll(list);
        System.out.println(list);
    }
}
2. What will be the output of the following program?
import java.util.*;
public class Hackers{
    public static void main(String args[]){
        int i = 225;
        List list = new ArrayList();
        list.add(new Object());
        list.add("Hackers Hacks");
        list.add(i);
        System.out.println(list.get(1));
    }
}
3.What will be the output of the following program?
import java.util.*;
public class AddCollection2{
    public static void main(String args[]){
        List<String> list = new ArrayList<String>();
        Collections.addAll(list, "C", "C++", "C#", "JAVA");
        System.out.println(list);

26
        String[] strs = {".Net", "UNIX"};
        Collections.addAll(list, strs);
        System.out.println(list);
        Collections.addAll(list, list);
        System.out.println(list);
    }
}

4. What will be the output of the following program?


import java.util.*;
public class Welcome {
    public static void main(String[] args) {
        int n = 5, k = 3, count = 0;
        List<Integer> list = new ArrayList<Integer>();
        list.add(10);    list.add(18);
        list.add(27);    list.add(34);
        list.add(36);    list.add(49);
        list.add(56);    list.add(60);
        list.add(21);    list.add(45);
        list.add(12);    list.add(99);
        n = list.size();
        for (int i = 0; i < n; i++){
            if (list.get(i) % k == 0 && list.get(i) % (k - 1) != 0)
                count++;
        }
        System.out.println("Count is " + count);
    }
}
5. What will be the output of the following program?
import java.util.*;
public class Copy {
    public static void main(String[] args) {
        List<String> list1 = new ArrayList<String>();
        list1.add("M");
        list1.add("E");
        List<String> list2 = list1;
        list1.add("R");
        list1.add("I");
        list1.add("T");
        System.out.format("%s", list1);
27
        System.out.format("%s", list2);
    }
}

6. What will be the output of the following program?


import java.util.*;
public class CityDistances {
    static List<City> cities = new ArrayList<City>();
    public static void main(String[] args) {
        cities.add(new City("Delhi", 15, 15));
        cities.add(new City("Mumbai", 5, 50));
        cities.add(new City("Kolkata", 25, 50));
        cities.add(new City("Chennai", 25, 80));
        cities.add(new City("Bangalore", 15, 70));
        printDistance("Delhi", "Mumbai");
        printDistance("Delhi", "Hyderabad");
        printDistance("Kolkata", "Chennai");
        printDistance("Kolkata", "Bangalore");
        printDistance("Hyderabad", "Bangalore");
    }
    private static void printDistance(String name1, String name2) {
        City first = null, second = null;
        for (City city : cities) {
            if (city.equals(name1)) { first = city; }
            if (city.equals(name2)) { second = city; }
        }
        if (first != null && second != null && first != second) {
            int distance = (int) Math.sqrt((first.x - second.x) * (first.x - second.x) + (first.y - second.y
) * (first.y - second.y));
    System.out.print(first.name.charAt(0) + "->" + second.name.charAt(1) + "=" + distance + ",");
        } else {
            System.out.print("NA,");
        }
    }
}
class City {
    int x; int y; String name;
    public City(String name, int x, int y) {
        this.x = x; this.y = y; this.name = name;

28
    }
}

7. What will be the output of the following program?


import java.util.*;
public class CollectionProgram2{
    public static void main(String args[]) {
        Vector<String> vector = new Vector<String>();
        Enumeration<String> strs = null;
        vector.add("Merit ");
        vector.add("Campus ");
        vector.add("to ");
        vector.add("you ");
        vector.add("welcomes ");
        vector.add("become ");
        vector.add("a ");
        vector.add("good ");
        vector.add("");
        vector.add("programmer.");
        strs = vector.elements();
        Collections.swap(vector, 2, 4);
        while(strs.hasMoreElements() && !vector.isEmpty()){
            System.out.print(strs.nextElement());
        }
    }
}
8. What will be the output of the following program?
import java.util.*;
public class CollectionVector{
    public static void main(String args[]){
        Vector<String> vector = new Vector<String>();
        vector.add("one");
        vector.add("two");
        vector.add("three");
        vector.add("four");
        System.out.println("Original vector: " + vector);
        List<String> list = new ArrayList<String>();
        list.add("one");
        list.add("two");
        list.add("five");
        vector.addAll(list);
        System.out.print("After add all: " + vector);
    }
}

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

17. What will be the output of the following program?


import java.util.*;
public class HashTable{
    public static void main(String a[]){
        Hashtable<String, String> hashtable = new Hashtable<String, String>();
        hashtable.put("first", "1");
        hashtable.put("second", "2");
        hashtable.put("third", "3");
        hashtable.put("third", "4");
        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));
        }
    }
}
18. 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");

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

23.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.fill(array, 1, 4, 8);
for (int i = 0; i < 5 ; i++)
System.out.print(array[i]);
}
}
24. What will be the output of the following Java 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);
}
}
25.What will be the output of the following Java program?
import java.util.*;
class Collection_iterators {
public static void main(String args[]) {
ListIterator a = list.listIterator();
if(a.previousIndex()! = -1)
while(a.hasNext())
System.out.print(a.next() + " ");
else
System.out.print("EMPTY");
}
}
26.What will be the output of the following Java program?

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

38.What is the output of this program?


import java.util.*;
class stack {
public static void main(String args[]) {
Stack obj = new Stack();
obj.push(new Integer(3));
obj.push(new Integer(2));
obj.pop();
obj.push(new Integer(5));
System.out.println(obj);

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) + ", ");
        }
    }
}

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

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

45. 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>();
        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.");
        }
    }
}
46. What will be the output of the following program?
import java.util.*;
public class HashTable{
    public static void main(String a[]){
        Hashtable<String, String> hashtable = new Hashtable<String, String>();
        hashtable.put("first", "1");
        hashtable.put("second", "2");
        hashtable.put("third", "3");
        hashtable.put("third", "4");
        hashtable.put("five", "5");
        hashtable.put("six", "5");

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

51. What will be the output of the following program?


import java.util.HashSet;
public class HashSetExample {
public static void main(String args[]) {

45
// 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);

//Displaying HashSet elements


System.out.println(hset);
}
}

46

You might also like