Beginner Level ( yr): Java Collections Interview Questions and Answers Q1 What is Collection? What is a Collections Framework? What are the benefits of. + Java Collections Framework Interview Questions and Answers, Question1: What is the difference between ArrayList and Vector? Question2: What is the. + Java Collections Interview Questions and Answers, Question1: What is Java Collections Framework? What are the benefits of using Collections framework.

Java Collection Framework Interview Questions Answers Pdf

Language:English, Dutch, Japanese
Published (Last):03.03.2016
ePub File Size:30.87 MB
PDF File Size:9.28 MB
Distribution:Free* [*Registration needed]
Uploaded by: ROSALINDA

Top 50 Core Java Interview Questions and Answers on Collections. In-depth guide with answers to wow the interviewer. Bonus: 20+ Videos & PDF interview. Java Collections interview questions and answers for experienced/beginner programmers. A must read coming What are the basic interfaces of Java Collections Framework? .. elements. Download java collections pdf for more information. Java Interview Questions iii. 4 Java Collections. 8. What are the basic interfaces of Java Collections Framework? 8. Why.

Here I am listing some important java collections interview questions and answers for helping you in interview. Java 8 has brought major changes in the Collection API.

Some of the changes are:.

Top 50 Java Collections Interview Questions and Answers

Collections are used in every programming language and initial java release contained few classes for collections: Vector , Stack , Hashtable , Array. But looking at the larger scope and usage, Java 1. Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package.

Some of the benefits of collections framework are;. Java 1. 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. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way.

Collection is the root of the collection hierarchy. A collection represents a group of objects known as its elements. Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards. List is an ordered collection and can contain duplicate elements.

List is more like array with dynamic length. A Map is an object that maps keys to values.

A map cannot contain duplicate keys: Each key can map to at most one value. Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. A lot of the Collection implementations have a public clone method. This is because Collection is an abstract representation. What matters is the implementation. The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.

So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized. If Map extends Collection interface, then where are the elements? 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. Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs.

But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration.

The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException. Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException.

By design, all the collection classes in java. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException. Check this post for ConcurrentHashMap Example.

This allows collection classes to chose whether iterator is fail-fast or fail-safe. UnsupportedOperationException is the exception used to indicate that the operation is not supported. UnmodifiableCollection throws this exception for all add and remove operations. HashMap stores key-value pair in Map. Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode and equals method in put and get methods.

When we call put method by passing key-value pair, HashMap uses Key hashCode with hashing to find out the index to store the key-value pair. The Entry is stored in the LinkedList, so if there are already existing entry, it uses equals method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and store this key-value Entry. Below image will explain these detail clearly. The other important things to know about HashMap are capacity, load factor, threshold resizing.

HashMap initial default capacity is 16 and load factor is 0. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. HashMap uses Key object hashCode and equals method to determine the index to put the key-value pair.

These methods are also used when we try to get value from HashMap. The implementation of equals and hashCode should follow these rules. We can use any class as Map Key, however following points should be considered before using them. HashMap and Hashtable both implements Map interface and looks similar, however there are following difference between HashMap and Hashtable. For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative.

If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

Arrays can contain primitive or Objects whereas ArrayList can contain only Objects. Arrays are fixed size whereas ArrayList size is dynamic. Although ArrayList is the obvious choice when we work on list, there are few times when array are good to use.

ArrayList and LinkedList both implement List interface but there are some differences between them. Download java collections pdf for more information. EnumSet is Set implementation to use with enum types.

All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created. EnumSet is not synchronized and null elements are not allowed. Check this post for java enum tutorial. Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment.

By design Iterator implementation in java. But Iterator implementation in java. BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element. Check this post for use of BlockingQueue for producer-consumer problem.

Search This Blog

Both Queue and Stack are used to store data before processing them. Queue is an interface whose implementation classes are present in java concurrent package. There is also Deque interface that allows elements to be retrieved from both end of the queue. Stack is a class that extends Vector whereas Queue is an interface. Collections is a utility class consists exclusively of static methods that operate on or return collections. This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc.

Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo T obj method which is used by sorting methods. But, in most real life scenarios, we want sorting based on different parameters.

Java Collections Interview Questions

This is the situation where we need to use Comparator interface because Comparable. Comparator interface compare Object o1, Object o2 method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

Check this post for use of Comparable and Comparator interface to sort objects. Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic. Comparator interface is used to provide different algorithms for sorting and we can chose the comparator we want to use to sort the given collection of objects.

If we need to sort an array of Objects, we can use Arrays. If we need to sort a list of objects, we can use Collections. Both these classes have overloaded sort methods for natural sorting using Comparable or sorting based on criteria using Comparator. Collections internally uses Arrays sorting method, so both of them have same performance except that Collections take sometime to convert list to array. We can create a read-only collection using Collections. We can use Collections. Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching.

Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.

Some of them are sorting, searching, shuffling, min-max values. The Big-O notation describes the performance of an algorithm in terms of number of elements in a data structure. Since Collection classes are actually data structures, we usually tend to use Big-O notation to chose the collection implementation to use based on time, memory and performance.

Example 1: Example 2: A linear search on array or list performance is O n because we need to search through entire list of elements to find the element. PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation.

Java PriorityQueue is not thread-safe and provided O log n time for enqueing and dequeing operations. Check this post for java priority queue example. As you can see from above code that IF generics would have been supporting sub-typing, we could have easily add a Double to the list of Long that would have caused ClassCastException at runtime while traversing the list of Long.

Vector, Stack, Hashtables, Array. But looking at the larger scope and usage, Java 1. Some of the benefits of collection framework are 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.

Reusability and Interoperability Reduced effort for code maintenance by using collection classes shipped with JK. All Rights Reserved. Garbage Collection. These classes are described in great detail in the video - https: HashSet implements set interface. So, HashSet does not allow duplicates. However, HashSet does not support ordering. The order in which elements are inserted is not maintained.

Sachin is Duplicate. So will not be added. LinkedHashSet implements set interface and exposes similar operations to a HashSet. Difference is that LinkedHashSet maintains insertion order. When we iterate a LinkedHashSet, we would get the elements back in the order in which they were inserted. TreeSet implements this interface. Let's look at an example with TreeSet.

Note that elements in TreeSet are sorted. Lower method finds the highest element lower than specified element. Floor method finds the highest element lower than or equal to specified element. Corresponding methods for finding lowest number higher than specified element are higher and ceiling. HashMap and TreeMap. These classes are explained in detail in this video - https: HashMap implements Map interface — there by supporting key value pairs. TreeMap is similar to HashMap except that it stores keys in sorted order.

We will now insert a Cricketer with key dravid. In sorted order,dravid comes before sachin. So, the value with key dravid is inserted at the start of the Map. We will now insert a Cricketer with key ponting. In sorted order, ponting fits in between dravid and sachin. TreeMap is a good example of a NavigableMap interface implementation. Note that keys in TreeMap are sorted. Corresponding methods for finding lowest key higher than specified key are higher and ceiling.

A few examples using the Map created earlier below. Synchronized collections are implemented using synchronized methods and synchronized blocks. Only one thread can executing any of the synchronized code at a given point in time. This places severe restrictions on the concurrency of threads — thereby affecting performance of the application.

Post Java 5, collections using new approaches to synchronization are available in Java. These are called concurrent collections. More details below. Examples of new approaches are:. We would discuss each of these approaches in detail below.

40 Java Collections Interview Questions and Answers

Copy on Write collections are typically used in Subject — Observer scenarios, where the observers very rarely change. Most frequent operations would be iterating around the observers and notifying them. Compare and Swap is one of the new approaches Java 5 introduced in java to handle synchronization. In traditional approach, a method which modifies a member variable used by multiple threads is completely synchronized — to prevent other threads accessing stale value.

In compare and swap approach, instead of synchronizing entire method, the value of the member variable before calculation is cached.

After the calculation, the cached value is compared with the current value of member variable. If the value is not modified, the calculated result is stored into the member variable.

If another thread has modified the value, then the calculation can be performed again. Or skipped — as the need might be. When 10 methods are declared as synchronized, only one of them is executed by any of the threads at any point in time. This has severe performance impact. Another new approach introduced in Java 5 is to use lock and unlock methods.Generics, dynamic growing 7 What is BlockingQueue, how it is different than other collection classes flow control 8 How do you iterator over Synchronized HashMap, do you need to lock iteration and why?

Example below shows how to iterate around an ArrayList. Regards, Gautam. Threshold is capacity multiplied by load factor and whenever we try to add an entry, if map size is greater than threshold, HashMap rehashes the contents of map into a new array with a larger capacity. If we need to sort a list of objects, we can use Collections.

Thanks a lot for this blog!! HashSet maintains no order whereas TreeSet maintains ascending order. It provides one method named compareTo. HashMap uses Key object hashCode and equals method to determine the index to put the key-value pair.

Why there are no concrete implementations of Iterator interface?

JOSEFINA from Palm Bay
I do love reading novels delightfully . Please check my other posts. I take pleasure in tag.