Tuesday 21 February 2017

Java Collection Basic Questions Part 1

1) What is Collection ? A collection — sometimes called a container — is simply an object that groups multiple elements into a single un... thumbnail 1 summary
1) What is Collection ?

A collection — sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.For example; a jar of chocolates, list of names etc.

2) What is a Collections Framework ?

The Java Collections Framework is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes which have tons of useful functions which makes a programmer task super easy.

3) What are the benefits of Java Collections Framework ?

Reduced development effort by using core collection classes rather than implementing our own collection classes.
Code quality is enhanced with the use of well tested collections framework classes.
Reduced effort for code maintenance by using collection classes shipped with JDK.
Reusability and Interoperability(the ability of computer systems or software to exchange and make use of information).

4) What is the root interface in collection hierarchy ?

The root interface of Collection hierarchy in Java is Collection interface.
But the Collection interface extends Iterable interface. Due to this some people consider Iterable interface as the root interface.

Iterable interface is present in java.lang package but Collection interface is present in java.util package. Oracle Java API docs mention that Collection interface is a member of the Java Collections framework.Whereas, Iterable interface is not stated as a part of Java Collections framework in Java docs.Due to this Collection interface is the root of Collections Framework.

5) What is the benefit of Generics in Collections Framework?

Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.

6) What is the difference between Collection and Collections ?

Collection Interface :

Collection is a root level interface of the Java Collection Framework. Most of the classes in Java Collection Framework inherit from this interface. List, Set and Queue are main sub interfaces of this interface. JDK doesn’t provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. ArrayList, Vector, HashSet, LinkedHashSet, PriorityQueue are some indirect implementations of Collection interface. Map interface, which is also a part of java collection framework, doesn’t inherit from Collection interface. Collection interface is a member of java.util package.

Collections Class:

Collections is an utility class in java.util package. It consists of only static methods which are used to operate on objects of type Collection. For example, it has the method to find the maximum element in a collection, it has the method to sort the collection, it has the method to search for a particular element in a collection. Below is the list of some important methods of Collections class.

7) Which are some common methods in Collections utility class?

Collections.max() - This method returns maximum element in the specified collection.
Collections.min() - This method returns minimum element in the given collection.
Collections.sort() - This method sorts the specified collection.
Collections.shuffle() - This method randomly shuffles the elements in the specified collection.
Collections.synchronizedCollection() - This method returns synchronized collection backed by the specified collection.
Collections.binarySearch() - This method searches the specified collection for the specified object using binary search algorithm.
Collections.disjoint() - This method returns true if two specified collections have no elements in common.
Collections.copy() - This method copies all elements from one collection to another collection.
Collections.reverse()- This method reverses the order of elements in the specified collection.

8) Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).

9) Name the core Collection  interfaces ?

The core collection interfaces encapsulate different types of collections, which are shown in the figure below.

10) What is an Iterator?

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

11) What is difference between Enumeration and Iterator interface?

Iterator interface is introduced from JDK 1.2 where as Enumeration interface is there from JDK 1.0.

This is the main difference between Enumeration and Iterator interface. Enumeration only traverses the Collection object. You can’t do any modifications to Collection while traversing the Collection using Enumeration. Where as Iterator interface allows us to remove an element while traversing the Collection object. Iterator has remove() method which is not there in the Enumeration interface. Below is the list of Enumeration and Iterator methods.

Enumeration is a legacy interface used to traverse only the legacy classes like Vector, HashTable and Stack. Where as Iterator is not a legacy code which is used to traverse most of the classes in the collection framework. For example, ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, TreeMap etc.

As Iterator is fail-fast in nature and doesn’t allow modification of a collection by other threads while iterating, it is considered as safe and secure than Enumeration.

12) Why Iterator don’t have a method to get next element directly without moving the cursor?

It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.

13) What are different ways to iterate over a list?

There are 5 ways you can iterate through List :
For Loop
  • Advanced For Loop
  • Iterator
  • While Loop
  • Collections’s stream() util (Java8)
package interviewguess.com.tutorial;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * @author interviewguess.blogspot.com
 */
 
public class InterviewGuessIterateThroughList {
 
 public static void main(String[] argv) {
 
  // create list
  List list = new ArrayList();
 
  // add 4 different values to list
  list.add("Apple");
  list.add("Orange");
  list.add("Banana");
  list.add("Mango");
 
  // iterate via "for loop"
  System.out.println("==> For Loop Example.");
  for (int i = 0; i < list.size(); i++) {
   System.out.println(list.get(i));
  }
 
  // iterate via "New way to loop"
  System.out.println("\n==> Advance For Loop Example..");
  for (String temp : list) {
   System.out.println(temp);
  }
 
  // iterate via "iterator loop"
  System.out.println("\n==> Iterator Example...");
  Iterator iterator = list.iterator();
  while (iterator.hasNext()) {
   System.out.println(iterator.next());
  }
 
  // iterate via "while loop"
  System.out.println("\n==> While Loop Example....");
  int i = 0;
  while (i < list.size()) {
   System.out.println(list.get(i));
   i++;
  }
 
  // collection stream() util: Returns a sequential Stream 
                // with this collection as its source
  System.out.println("\n==> collection stream() util....");
  list.forEach((temp) -> {
   System.out.println(temp);
  });
 }
}

No comments

Post a Comment