Monday, May 4, 2009

Java Interview Questions : Collections I


1. What is the difference between the size and capacity of a Vector?

Ans. Vector is a grow-able collection of objects. The size tells us the number of elements actually stored in the vector, while it’s capacity tells us the maximum number of elements that it can store at a given instance of time. Capacity is increased automatically when the Vector is filled up with elements to a threshold level which is determined by it’s load factor.

2. What is the difference between an Iterator and a ListIterator?

Ans. Iterator is an interface which allows you to iterate all the elements in a collection, but only in the forward direction. While, ListIterator extends the Iterator, it has the added functionality of b-directional traversal of the collection.

3. How is a Set different from a List?

Ans. Set is a data structure in which no duplicates are allowed, and also it doesn’t preserve the order of the elements. List, on the other hand, allows duplicate elements to be present, and also maintains the order of the elements.

4. What is the difference between Enumeration and Iterator?

Ans. Both have the same functionality, i.e, traverse through all the elements in a collection. But they are different in only one respect, Enumeration allows you to only traverse and fetch elements from a collection, without any provision of manipulating the collection, i.e, addition, deletion, updation. Using an iterator, you can even manipulate the collection, in addition to traversal and fetching.

5. What are the differences between an ArrayList and a Vector?

Ans. Though the implementations for the both are the same, the Vector is synchronized while an ArrayList isn’t.

6. How will you remove duplicate elements in a List?

Ans. As we already know, a Set cannot contain duplicate elements, you just add the List elements to a Set. the duplicates will not be added.

7. Which data structure is to be used when fast iteration and random access is required?

Ans. ArrayList

8. When should we use LinkedList?

Ans. In LinkedList, new elements are added to the ends, ex, Queues and Stacks. However, you can still add or delete elements in a LinkedList in the middle, but this process eats up a lot of resources in breaking and making the links between two elements. So, when we don’t need any insertion or deletion in between, but only at the ends, we should use LinkedList.

9. What is the use of a hashCode() in Java?

Ans. They are used in certain collection classes where the elements are stored as key/value pairs, such as HashMap, Hashtable, where hashCodes are used for their storage and retrieval.

10. When you want to search an element by it’s index, which of these would you use?

Ans. ArrayList, of course.

No comments: