Showing posts with label java collections interview questions. Show all posts
Showing posts with label java collections interview questions. Show all posts

Friday, June 29, 2012

Java Collections Interview Questions - Part 2

As a continuation from the part 1 of questions on the Java Collections topic, this article is going to contain some more questions on the Java Collections area. If you want to visit the part 1 questions click here

Apart from the questions in the Part 1 and below, there are a few articles that I have put up (as part of the SCJP Certification series) on Collections that you might find useful. You can use them to revise/review your understanding of Java collections.

They are:

Introduction to Collections
ArrayList Basics
Sorting Collections
Searching Collections
Collections Summary


Questions:

1. What is the difference between java.util.Iterator and java.util.ListIterator?

Iterator - Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator - extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

2. What is the difference between the HashMap and a Map?

Map is an Interface which is part of Java collections framework. It stores data as key-value pairs.
Hashmap is class that implements that using hashing technique.

3. What does synchronized means in Hashtable context?

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
This adds an overhead which makes the Hashtable slower when compared to the Hashmap. You must choose a Hashmap when you want faster performance and choose the Hashtable when you want thread safety

4. Can we make a Hashmap thread safe? If so, how?

HashMap can be made thread safe by synchronizing it. Example:
Map m = Collections.synchronizedMap(hashMap);

5. Why should I always use ArrayList over Vector?
You should choose an ArrayList over a Vector because – not all systems are multi-threaded and thread safety is not a mandatory requirement. In such cases, using a Vector is not only overkill but also adds a lot of overhead which might slow down system performance. Even if you are just iterating through a vector to display its contents, the lock on it still needs to be obtained which makes it much slower. So, choose the ArrayList over a Vector unless your system is multi-threaded.

6. What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

7. What is the difference between Enumeration and Iterator?

The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

8. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort()? Which one is faster? Which one to use and when?

Actually speaking, the underlying sorting algorithm & mechanism is the same in both cases. The only difference is type of input passed to them. Collections.sort() has a input as List so it does a conversion of the List to an array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it.

9. What is java.util.concurrent BlockingQueue? How it can be used?

The BlockingQueue is available since Java 1.5. Blocking Queue interface extends collection interface, which provides you the power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

10. What is the ArrayBlockingQueue?

An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.

11. Why doesn't Map interface extend Collection?

Though the Map interface is part of collections framework, it does not extend collection interface. This was done as a design decision by Sun when the Collection framework was created. Think of it this way – A Map contains key-value pair data while a general collection contains only a bunch of values. If the map were to extend the collection class, what will we do with the keys and how will we link the values to their corresponding keys? Alternately, if the collection were to extend the Map, then, where will we go to get the key information for all the values that are already in the Collection?

Get the idea? For all practically purposes a Map is considered a collection because it contains a bunch of data in key-value pairs but it does not explicitly extend the collection interface.

12. Which implementation of the List interface (ArrayList or LinkedList) provides for the fastest insertion of a new element into the list?

LinkedList.

If you are surprised about the answer you see above, read the question again “Fastest Insertion of a new element into the list”. The question is about inserts and not reading data. So, the linkedlist is faster. Because, when an element is inserted into the middle of the list in an ArrayList, the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

13. Which implementation of the List Interface (ArrayList or LinkedList) provides for faster reads during random access of data?

ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.

14. Which implementation of the List Interface (ArrayList or LinkedList) uses more memory space for the same amount (number) of data?

Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. So, the LinkedList uses more memory space when compared to an ArrayList of the same size

15. Where will you use ArrayList and Where will you use LinkedList?

If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time (depending on the location of the object being added/removed) in an ArrayList.

If the purpose of your collection is to populate it once and read it multiple times from random locations in the list, then the ArrayList would be faster and a better choice because Positional access requires linear-time (depending on the location of the object being accessed) in a LinkedList and constant-time in an ArrayList.

In short - If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

16.Why insertion and deletion in ArrayList is slow compared to LinkedList?

ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.

During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

17.How do you traverse through a collection using its Iterator?

To use an iterator to traverse through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
3. Within the loop, obtain each element by calling next().

18.How do you remove elements during Iteration?

Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

19.What are the main implementations of the List interface?

The main implementations of the List interface are as follows :
ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

20.What are the advantages of ArrayList over arrays?

Some of the advantages ArrayList has over arrays are:
It can grow dynamically
It provides more powerful insertion and search mechanisms than arrays.

21.How to obtain Array from an ArrayList?

Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
arrayList.add(obj1);
arrayList.add(obj2);
arrayList.add(obj3);

Object a[] = arrayList.toArray();

22.Why are Iterators returned by ArrayList called Fail Fast?

Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. So, it is considered fail fast.

23.How do you sort an ArrayList (or any list) of user-defined objects?

Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

24.What is the Comparable interface?

The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

If object1 < object2: The value of i returned will be negative.

If object1 > object2: The value of i returned will be positive.

If object1 = object2: The value of i returned will be zero.

25.What are the differences between the Comparable and Comparator interfaces?

The Comparable uses the compareTo() method while the Comparator uses the compare() method
You need to modify the class whose instance is going to be sorted and add code corresponding to the Comparable implementation. Whereas, for the Comparator, you can have a separate class that has the sort logic/code.
In case of Comparable, Only one sort sequence can be created while Comparator can have multiple sort sequences.


If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list

Java Collections Interview Questions - Part 1 - Click Here

More Java & J2EE Interview Questions with Answers - Click Here

Tuesday, April 19, 2011

Java Collections Interview Questions - Part 1

The following are some questions you might encounter with respect to Java Collections in any Interview. Collections are an integral part of any Java application and it would be surprising if you did not get a few of the collection questions in an interview.

Apart from the questions below, there are a few articles that I have put up (as part of the SCJP Certification series) on Collections that you might find useful. You can use them to revise/review your understanding of Java collections.

They are:

Introduction to Collections
ArrayList Basics
Sorting Collections
Searching Collections
Collections Summary

Questions:

1. What's the main difference between a Vector and an ArrayList

Java Vector class is internally synchronized and ArrayList is not. Hence, Vectors are thread-safe while ArrayLists are not. On the Contrary, ArrayLists are faster and Vectors are not. ArrayList has no default size while vector has a default size of 10.

2. What's the difference between a queue and a stack?

Stacks works by last-in-first-out rule (LIFO), while queues use the first-in-first-out (FIFO) rule

3. what is a collection?

Collection is a group of objects.

There are two fundamental types of collections they are Collection and Map.

Collections just hold a bunch of objects one after the other while Maps hold values in a key-value pair.

Collections Ex: ArrayList, Vector etc.
Map Ex: HashMap, Hashtable etc

4. What is the Collections API?

The Collections API is a set of classes and interfaces that support operation on collections of objects. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming using the collections.

The purpose of the Collection API is to:

o Reduces programming efforts. - Increases program speed and quality.
o Allows interoperability among unrelated APIs.
o Reduces effort to learn and to use new APIs.
o Reduces effort to design new APIs.
o Encourages & Fosters software reuse.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.
Example of interfaces: Collection, Set, List and Map.

5. What is the List interface?

The List interface provides support for ordered collections of objects. Ex: ArrayList

6. What is the Vector class?

The Vector class provides the capability to implement a growable array of objects that is synchronzied and thread-safe.

7. What is an Iterator interface?

The Iterator interface is used to step through the elements of a Collection one by one. It is an easier way to loop through the contents of a collection when you do not know, how many objects are present in it. Also, it is a cleaner way to access the contents of a collection when compared to using a for loop and accessing entries using get(index) method.

Remember that, when using Iterators they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.

8. What is the Map interface?

A map is an object that stores associations between keys and values (key/value pairs). Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. Some maps can accept a null key and null values, others cannot.


9. What is the Collection interface?

The Collection interface provides support for the implementation of a mathematical bag - an unordered collection of objects that may contain duplicates.

10. What is the Set interface?

• The Set interface provides methods for accessing the elements of a finite mathematical set
• Sets do not allow duplicate elements
• Contains no methods other than those inherited from Collection
• It adds the restriction that duplicate elements are prohibited
• Two Set objects are equal if they contain the same elements


11. What are different types of collections?

* A regular collection has no special order and does not reject duplicates
* A list is ordered and does not reject duplicates
* A set has no special order but rejects duplicates
* A map supports storing data as key-value pairs

12. Difference between Hashtable and HashMap?

* Hashtable does not store null value, while HashMap does
* Hashtable is synchronized, while HashMap is not
* Hashtables are slower because of the synchronization overhead while HashMaps are faster

13.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
HashSet
TreeSet
LinkedHashSet
EnumSet

14.What is a HashSet ?
A HashSet is an unsorted, unordered Set. It uses the hashcode of the object being inserted to access the object. So, the more efficient your hashcode() implementation the better access performance you’ll get. Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

15.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

16.Difference between HashSet and TreeSet ?

HashSet does not store data in any Order while the TreeSet stores data in order. Also, you can elements of any type to the hash set while you can only add similar types of elements into a tree set.


17.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
HashMap
HashTable
TreeMap
EnumMap

18.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

19.How do you decide when to use HashMap and when to use TreeMap ?
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.

20. Can I store multiple keys or values that are null in a HashMap?

You can store only one key that has a value null. But, as long as your keys are unique, you can store as many nulls as you want in an HashMap

If you have any questions that you want answer for - please leave a comment on this page and I will answer them.

If you have any more questions on Collections that you have faced during your interviews and wish to add them to this collection - pls drop a note to [email protected] and I shall be glad to add them to this list.

More Java & J2EE Interview Questions with Answers - Click Here

Java Collections Interview Questions - Part 2
© 2013 by www.inheritingjava.blogspot.com. All rights reserved. No part of this blog or its contents may be reproduced or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written permission of the Author.

ShareThis

Google+ Followers

Followers