Some Questions on Collections

11 Sep

1. What is the difference between a List and a Set?
List allows duplicates and maintains the order in which the elements were inserted on the other hand a Set doesn’t allow duplicates and no order is maintained.

2. Tell me some ways to make a synchronized list.
You can use Vector or can use a method provided in Collections class. Collections.SynchronizedList(List list) which returns a synchronized list.

3. What method should the key class of Hashmap override?
The class used as a Key must override equals() and hashCode() methods.

4. What is the key difference between Enumeration and Iterator?
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.

5. What is the difference between Vector and ArrayList?
Vector is synchronized whereas ArrayList is not.

6. Can a List contain heterogeneous objects?
Yes a List can contain heterogeneous objects. It also depends upon the type declaration of the List. From Java 1.5 onwards use

 List<Object> list = new ArrayList<Object>(); 

to declare a hetrogenous list.

7. How do I sort the Elements in a Collection?
You can use Collections.sort method to sort the elements.

1 Comment

Posted by on September 11, 2010 in Java, Java Collections


One response to “Some Questions on Collections

  1. ShamanOfJava

    November 17, 2011 at 9:11 am

    Hmm..Interview questions 🙂


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: