Java Collections interview question answers

What is the Collection framework in Java?

The primary purpose of the Collection Framework is used to store objects. It provides classes and interfaces such as List, ArrayList, Queue, Set, Vector, Stack, and HashSet, etc.

What are the main differences between array and collection?

  1. Arrays are always of fixed size whereas, size can be changed dynamically in the case of Collection.
  2. Array has no ready-made? methods for sorting, searching, etc. but Collection has readymade methods to use.
  3. Arrays stores homogeneous data. Collections stores both homogeneous as well as heterogeneous data.
  4. Arrays are recommended for performance, whereas Collections are not.
  5. Arrays use more memory space as compared to Collections.

Difference between ArrayList and LinkedList?

  1. ArrayList uses a dynamic array whereas, LinkedList uses a doubly linked list.
  2. ArrayList is not efficient for manipulation but LinkedList is efficient for manipulation.
  3. ArrayList is better to store and fetch data but LinkedList is better to manipulate data.
  4. ArrayList provides random access but LinkedList does not provide random access.
  5. ArrayList takes less memory whereas, LinkedList takes more memory.

Difference between Iterator and Enumeration?

  1. Iterator is an improved version of Enumeration.
  2. Iterator is a universal and it is applicable for all the collection classes such as HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet whereas, Enumeration is not a universal cursor as it applies only to legacy classes such as Vector, Hashtable.
  3. Iterator has remove() method so Iterator can read and remove both but Enumeration only can read as Enumeration does not have the remove() method.

Difference between List and Set?

  1. List can contain duplicate elements whereas Set can not contain duplicate element.
  2. List maintain insersion order but Set is an unordered collection which does not maintain insertion order.
  3. List interface can allow any number of null values but Set interface allows only one single null value.

Difference between HashSet and TreeSet?

  1. HashSet and TreeSet, both are classes and both classes implements Set interface.
  2. HashSet impended by hash table but TreeSet implemented by a Tree structure.
  3. HashSet does not maintains order but TreeSet maintains ascending order.
  4. The prformance of HashSet is faster than TreeSet.

Difference between Set and Map?

  1. Set and Map bth are interface.
  2. Set contains values only whereas Map contains key and values both.
  3. Set contains unique values whereas Map can contain unique Keys.

Difference between HashMap and TreeMap?

  1. HashMap does not maintains the order whereas, TreeMap maintains the ascending order.
  2. HashMap is implemented by hash table whereas TreeMap is implemented by a Tree structure.
  3. HashMap may contain a null key but TreeMap does not contain a null key.

Difference between HashMap and Hashtable?

  1. HashMap is not synchronized but Hashtable is synchronized.
  2. HashMap can contain one null key and multiple null values but Hashtable cannot contain any null key or null value.
  3. HashMap is not thread-safe but Hashtable is thread-safe, and it can be shared between various threads.

Difference between Collection and Collections?

  1. The Collection is an interface whereas Collections is a class.
  2. The Collection interface is used in data structure like List, Set, and Queue. But, Collections class is used to sort and synchronize the collection elements.

What is hash collision in Hashtable?

If two different keys are providing the same hash value that is called hash collision.

What is the default size of load factor in hashing?

The default size of load factor is 0.75. The initial capacity is 16 so formula is
16 * 0.75 = 12
12 is the default capacity of Map.

Difference between between Array and ArrayList?

  1. Size of an Array is fixed size, means we cannot resize the array as per need but the size of ArrayList is not fixed, we can change the size dynamically.
  2. Arrays can store primitive data types as well as objects but ArrayList cannot store the primitive data types it can only store the objects.

Convert ArrayList to Array?

public class ConvertArrayListtoArray {
public static void main(String args[]) {
    List<String> monthList = new ArrayList<>();
    monthList.add("January");
    monthList.add("February");
    monthList.add("March");
    monthList.add("April");
    //Converting Arraylist to Array
    String[] array = monthList.toArray(new String[monthList.size()]);
    for(String s: array){
        System.out.println(s);
    }
 }
}
Output: 
    January
    February
    March
    April

Convert Array to ArrayList?

public class ConvertArrayListtoArray {
public static void main(String args[]) {
    List<String> monthList = new ArrayList<>();
    monthList.add("January");
    monthList.add("February");
    monthList.add("March");
    monthList.add("April");
    //Converting Arraylist to Array
    String[] array = monthList.toArray(new String[monthList.size()]);
    for(String s: array){
        System.out.println(s);
    }

    List<String> monthList1 = new ArrayList<>();
    //Converting Array to Arraylist    
    monthList1 = Arrays.asList(array);
 }
}
Output: 
    January
    February
    March
    April

How to make Java ArrayList Read-Only?

ArrayList can be Read-only by calling the Collections.unmodifiableCollection().

public class UnmodifiableCollectionExample {
public static void main(String args[]) {
    List<String> monthList = new ArrayList<>();
    monthList.add("January");
    monthList.add("February");
    monthList.add("March");
    monthList.add("April");

    //Converting to a immutable Arraylist    
    Collection<String>
            unModifiedlist = Collections
            .unmodifiableCollection(monthList);
    //exception here  
    unModifiedlist.add("May");
  }
}
Output:
   Exception in thread "main" java.lang.UnsupportedOperationException

What is LinkedHashSet?

LinkedHashSet maintain insertion order also it can not store duplicate object.

Reverse ArrayList?

Collections.reverse(list)

How to synchronize ArrayList?

Collections.synchronizedList(list);

What is the time complexity for accessing an element in an array?

What is the time complexity of ArrayList?

  1. add() - O(1) time, but when a new array has to be created and all the elements copied to it O(n) time.
  2. add(index, element) - O(n) time
  3. get() - O(1) time
  4. remove() - O(n) time
  5. indexOf() - O(n) time
  6. contains() - O(n) as it also call indexOf()

What is the time complexity of LinkedList?

LinkedList is a linear data structure that consists of nodes holding a data field and a reference to another node.

  1. add() - O(1) as its only update a tail.
  2. add(index, element) - O(n) time
  3. get() - O(n) time
  4. remove(element) - O(n) time
  5. remove(index) - O(n) time
  6. indexOf() - O(n) time
  7. contains() - O(n) as it also call indexOf()

What is the time complexity of Set?

  1. add() - O(1)
  2. remove(index) - O(1) time
  3. contains() - O(1) time

What is the time complexity of Map?

  1. HashMap collisions - O(n) to O(log(n))
  2. put() - O(1) time
  3. get() - O(1) time

What is Data Structure?

Data structure is a logical way that defines how data will organize within a program. Data structure is a important function for the application's performance prospective.

  1. Database Design
  2. Generic
  3. Block Chain
  4. File Processing

find the smallest and largest element in an array?

public class SmallestLargestNumberArray {
public static void main(String[] args){
    Integer[] array = {4,7,2,8,2,300,23,50,250,450};

    Integer samllest = array[0];
    Integer largest = array[0];

    for(int i=0;i< array.length;i++){
        if(array[i]<samllest){
            samllest = array[i];
        }else if(array[i]>largest){
            largest = array[i];
        }
    }
    System.out.println("Smallest number ="+samllest);
    System.out.println("Largest number ="+largest);
  }
}

What is multi dimensional array?

The Multi Dimensional array is an array that contains other arrays. Basically, the Multi Dimensional array is array of arrays.

public class MultiDimentationalArrayExample {
    public static void main(String args[]){
        Integer[][] array = new Integer[10][20];

        for(int i=0;i<10;i++){
            for(int j=0;j<20;j++){
                array[i][j] = i*j;
            }
        }
    }
}

Create Custom LinkedList?

public class LinkedListCustom { 
    private Node head;
    public LinkedListCustom(Node head) {
        this.head = head;
    }
    public LinkedListCustom() {} 
    public void add(int data){
        Node newElement = new Node(data);
        if(this.head == null){
            head = newElement;
        }else {
            Node currentNode = head;
            while(currentNode.getNextNode() != null){
                currentNode = currentNode.getNextNode();
            }
            currentNode.setNextNode(newElement);
        }
    }
    public void addHead(int data){
        Node newNode = new Node(data);
        newNode.setNextNode(head);
        head = newNode;
    }
    public void insertAt(int index, int data){
        Node nodeToBeInserted = new Node(data);
        Node node = head;
        for(int i = 0; i< index -1; i++){
            node = node.getNextNode();
        }
        nodeToBeInserted.setNextNode(node.getNextNode());
        node.setNextNode(nodeToBeInserted);
    }
    public void deleteNodeAt(int index){
        Node node = head;
        for(int i = 0; i< index -1; i++){
            node = node.getNextNode();
        }
        node.setNextNode(node.getNextNode().getNextNode());
    }
    public void display(){
        if(head != null){
            Node currentNode = head;
            while(currentNode.getNextNode() != null){
                System.out.println(currentNode.getData());
                currentNode = currentNode.getNextNode();
            }
            System.out.println(currentNode.getData());
        }
    }
}
    

class Node{
    private int data;
    private Node nextNode;
    public Node(int data) {
        this.data = data;
    }
    public int getData() {
        return data;
    }
    public void setData(int data) {
        this.data = data;
    }
    public Node getNextNode() {
        return nextNode;
    }
    public void setNextNode(Node nextNode) {
        this.nextNode = nextNode;
    }
}

class DemoLinkedList{
    public static void main(String args[]){
        LinkedListCustom l = new LinkedListCustom();
        l.add(6);
        l.display();
    }
}

Create Custom HashMap?

public class HashMapCustomImplementation<K, V> {
    private int capacity=16;
    private Entry<K, V>[] table;

    public HashMapCustomImplementation(){
        table = new Entry[capacity];
    }

    public HashMapCustomImplementation(int capacity){
        this.capacity = capacity;
        table = new Entry[capacity];
    }
    private int index(K key){
        if(key == null){
            return 0;
        }
        return Math.abs(key.hashCode() % capacity);
    }
    public void put(K key, V value){
        int index = index(key);
        Entry newEntry = new Entry(key, value, null);
        if(table[index] == null){
            table[index] = newEntry;
        }else {
            Entry<K, V> previousNode = null;
            Entry<K, V> currentNode = table[index];
            while(currentNode != null){
                if(currentNode.getKey().equals(key)){
                    currentNode.setValue(value);
                    break;
                }
                previousNode = currentNode;
                currentNode = currentNode.getNext();
            }
            if(previousNode != null)
                previousNode.setNext(newEntry);
        }
    }

    public void display(){
        for(int i = 0; i < capacity; i++){
            if(table[i] != null){
                Entry<K, V> currentNode = table[i];
                while (currentNode != null){
                    System.out.println(String.format("Key is %s and value is %s", currentNode.getKey(), currentNode.getValue()));
                    currentNode = currentNode.getNext();
                }
            }
        }
    }

}

class Entry<K, V>{
    private K key;
    private V value;
    private Entry<K, V> next;

    public Entry(K key, V value, Entry<K, V> next) {
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public K getKey() {
        return key;
    }
    public void setKey(K key) {
        this.key = key;
    }
    public V getValue() {
        return value;
    }
    public void setValue(V value) {
        this.value = value;
    }
    public Entry<K, V> getNext() {
        return next;
    }
    public void setNext(Entry<K, V> next) {
        this.next = next;
    }
}

class DemoHashMap{
    public static void main(String args[]){
        HashMapCustomImplementation<Integer, String> map = new HashMapCustomImplementation<Integer, String>();
        map.put(1,"One");
        map.put(2,"Two");
        map.display();;
    }
}