Collections Drill – I

1.How to find the maximum size of heap used in the memory in java ?
(): Returns the maximum amount of memory that the Java virtual machine will attempt to use
totalMemory(): Returns the total amount of memory in the Java virtual machine.
Also you can use -Xmx parameter to set the max heap size.

2.What is the difference between marshalling and unmarshalling ?
marshling is convert from byte code to network understand able format
unmarshsling is converting from network understand able fromat to byte code convertion.

3.What is the Collections API ?
The Collections API is a set of classes and interfaces that support operations on collections of objects.

4.What is the List interface ?
The List interface provides support for ordered collections of objects.

5.What is the Vector class ?
The Vector class provides the capability to implement a growable array of objects.

6.What is an Iterator interface ?
The Iterator interface is used to step through the elements of a Collection .

7.Which java.util classes and interfaces support event handling?
The EventObject class and the EventListener interface support event processing.

8.What is the GregorianCalendar class ?
The GregorianCalendar provides support for traditional Western calendars

9.What is the Locale class ?
The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region .

10.What is the SimpleTimeZone class ?
The SimpleTimeZone class provides support for a Gregorian calendar .

11.What is the Map interface ?
The Map interface replaces the JDK 1.1 Dictionary class and is used associate keys with values.

12.What is the highest-level event class of the event-delegation model ?
The java.util.EventObject class is the highest-level class in the event-delegation class hierarchy.

13.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.

14.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.

15.What is the typical use of Hashtable ?
Whenever a program wants to store a key value pair, one can use Hashtable.

16.I am trying to store an object using a key in a Hashtable. And some other object already exists in that location, then what will happen? The existing object will be overwritten? Or the new object will be stored elsewhere?
The existing object will be overwritten and thus it will be lost.

17.What is the difference between the size and capacity of a Vector?
The size is the number of elements actually stored in the vector, while capacity is the maximum number of elements it can store at a given instance of time.

18.Can a vector contain heterogenous objects ?
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object.

19.Can a ArrayList contain heterogenous objects ?
Yes a ArrayList can contain heterogenous objects. Because a ArrayList stores everything in terms of Object.

20.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.

21.Considering the basic properties of Vector and ArrayList, where will you use Vector and where will you use ArrayList ?
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.

22.Can a vector contain heterogenous objects ?
Yes a Vector can contain heterogenous objects. Because a Vector stores everything in terms of Object

23.How do I use an Iterator to go through a Collection ?
Collection collection = …;
Iterator iterator = collection.iterator();
while (iterator.hasNext()) {
Object element =;
// Do something with element

24.How do I use a ListIterator to go through a List backwards ?
List list = …;
ListIterator iterator = list.listIterator(list.size());
while (iterator.hasPrevious()) {
Object element = iterator.previous();
// Process element

25.How do I count the frequency of some word/object ?
The Map interface can be used to count the number of times a word/object appears. The following program demonstrates counting word frequency from the command line:

import java.util.*;

public class MapExample {
public static void main(String args[]) {
Map map = new HashMap();
Integer ONE = new Integer(1);
for (int i=0, n=args.length; i<n; i++) {
String key = args[i];
Integer frequency = (Integer)map.get(key);
if (frequency == null) {
frequency = ONE;
} else {
int value = frequency.intValue();
frequency = new Integer(value + 1);
map.put(key, frequency);
Map sortedMap = new TreeMap(map);

26. How do I sort objects into their reverse natural ordering ?
The Collections.reverseOrder() method returns a Comparator that sorts objects that implement the Comparable interface in reverse order.

27.How do I use Enumeration to iterate through a collection ?
Enumeration enum = …;
while (enum.hasMoreElements()) {
Object element = iterator.nextElement();
// process element

28.How do I make an array larger ?
You cannot directly make an array larger. You must make a new (larger) array and copy the original elements into it, usually with System.arraycopy(). If you find yourself frequently doing this, the Vector class does this automatically for you, as long as your arrays are not of primitive data types.

29.How do you store a primitive data type within a Vector or other collections class ?
You need to wrap the primitive data type into one of the wrapper classes found in the java.lang package, like Integer, Float, or Double, as in:

Integer in = new Integer(5);

30.How do I create linked lists if there are no pointers ?
No pointers does not mean no reference variables. You just can’t deference them as you can in C/C++ or perform pointer arithmetic. You can still use abstract data types that require dynamic data structures. See the LinkedList class for an example of a linked list implementation.

31.How do I use an array with the Collections Framework ?
The Arrays.asList() method provides a fixed-length List view of an array, where changes to the List are stored in the original array. The Arrays class also provides additional support methods for sorting and searching an array.

32.Which is faster, synchronizing a HashMap or using a Hashtable for thread-safe access ?
Because a synchronized HashMap requires an extra method call, a Hashtable is faster for synchronized access.

33.Which is the preferred collection class to use for storing database result sets ?
When retrieving database results, the best collection implementation to use is the LinkedList.
The benefits include:
Retains the original retrieval order
Has quick insertion at the head/tail
Doesn’t have an internal size limitation like a Vector where when the size is exceeded a new internal structure is created (or you have to find out size beforehand to size properly)
Permits user-controlled synchronization unlike the pre-Collections Vector which is always synchronized


ResultSet result = stmt.executeQuery(“…”);
List list = new LinkedList();
while( {

If there are multiple columns in the result set, you’ll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.

34.Why doesn’t the Iterator interface extend the Enumeration interface ?
If the Iterator interface extended the Enumeration interface, the Iterator interface would end up with five methods where two methods just called other methods in the interface. The designers of the framework wanted to get rid of the cumbersome Enumeration method names so had the Iterator interface stand on its own with new shorter method names.

35.How do I print a Collection ?
The Collection Framework implementation classes override the toString() method to print out all the elements of the collection. If you create your own custom implementation, as long as your class is a subclass of AbstractMap or AbstractCollection you’ll inherit this behavior. (Keep in mind that AbstractList and AbstractSet subclass AbstractCollection.)

36.How do I synchronize a collection ?
With the Collections Framework, the new implementations are all unsynchronized by default. If you need synchronized access, you must synchronize things yourself. The Collections class offers a wrapper method for each of the six core collection interfaces that add synchronization to an arbitrary collections implementation. To ensure thread-safety, direct access to the original backing collection must be avoided.
For example, the following will synchronize an arbitrary List and lose the original reference so you can’t access it directly:

List list = …;
list = Collections.synchronizedList(list);

37.How I do a case-sensitive sort in a language-insensitive manner ?
If you have an array of primitives or an array of equivalent objects that implement the Comparable interface, all you need to do is call the sort() method of the java.util.Arrays class. If the class doesn’t implement Comparable, you need to provide your own Comparator implementation to the sort() method.

38.How do I get the length of an array ?
To avoid getting an ArrayIndexOutOfBoundsException, you can check for the array length from either the length instance variable or using reflection and calling java.lang.reflect.Array.getLength(), passing the array as an argument to the method.
int length = args.length;
// or
int length2 = Array.getLength(args);

39.How can I speed up array accesses and turn off array bounds checking ?
You cannot. It is part of the security architecture of the Java runtime to ensure never accessing invalid memory space.

40.How do I get the list of system properties that tell me things like which version of Java a user is running and their platform-specific line separator ?
The System.getProperties() method will return the standard property set. However, in untrusted applets, you can only ask for specific properties, as in System.getProperty(“java.version”).

41.How do I sort an array ?
The Arrays class in java.util provides a series of sort() methods for sorting arrays. If the array is an array of primitives or an array of a class that implements Comparable then you can just call the method directly:


If, however, it is an array of objects that don’t implement the Comparable interface then you need to provide a custom Comparator to help you sort the elements in the array.

Arrays.sort(theArray, theComparator);

42.How can I implement a List (ordered collection) that keeps an index (i.e. a Map) of its contents ?
You can’t. Each of the Map and List interfaces define a remove(Object o) method. Each method returns a different type (Map returns an Object while List returns a boolean). Because the compiler doesn’t permit overloaded methods that differ by only return type, you cannot create a class that implements both the List and Map interface.

If you need a Map that maintains insertion order, see the LinkedHashMap added in Java 1.4.

43.Is there a way to create a homogenous collection in Java? How do I make a collection where all the elements within it are a specific data type ?
You can wait for Generics to be added to Java or…

You’d have to build one yourself. Basically, you’re creating a class that is a Proxy (Gang Of Four design pattern) around the actual Collection.

This works similarly to the way the (hidden) Synchronized versions in Collections work. They contain a reference to the original collection object that does the “real” work, but restrict access to it by synchronizing all the access methods.

What you’d be doing in this case is restricting access by keeping a reference to the Class object of the class you want to restrict your collection to contain, and throw IllegalArgumentExceptions whenever there’s an attempt to add an object not of that class.

There’s no way to enforce compile-time type safety in this manner. The API using “Object” references can’t be changed in Collection.

You can also wrap a collection by a Proxy that provides the alternative API that has type-safe method signatures. This is what’s done by the StringTokenizer API (which implements Enumeration, and wraps Enumeration with String versions of the same methods).

Otherwise, create your own class with its own signatures, and keep the Collection strictly private. This is best done if you are designing a class for others to use.

44.How does a Hashtable internally maintain the key-value pairs ?
The Hashtable class uses an internal (private) class named Entry to hold the key-value pairs. All entries of the Hashtable are stored in an array of Entry objects with the hash value of the key serving as the index. If two or more different keys have the same hash value these entries are stored as a linked list under the same index.

45.How do I look through each element of a HashMap ?
To go through all the elements of a HashMap, or any class that implements the Map interface, call the entrySet() or keySet() methods than loop through what is returned. The entrySet() returns a group of Map.Entry elements, whereas the keySet() method just returns a Set of key elements. If you then want what the key refers to, you’d have to look them up.
Once you have a Set to work with, you would then use an Iterator to go through all its elements. The following demonstrates:

Map map = some hash map
Set set = map.keySet();
Iterator it = set.iterator();
while (it.hasNext()) {

46.How do I create a read-only collection ?
The Collections class has six methods to help out here:
unmodifiableCollection(Collection c)
unmodifiableList(List list)
unmodifiableMap(Map m)
unmodifiableSet(Set s)
unmodifiableSortedMap(SortedMap m)
unmodifiableSortedSet(SortedSet s)

If you then get an Iterator from one of these unmodifiable collections, when you call remove() it will throw an UnsupportedOperationException

47.How can I process through the keys of a Hashtable in sorted order ?
In order to get all the keys for a Hashtable, you use the keys() method to get an Enumeration or the keySet() method to get a Set. If you are using Java 2, and can use the collections framework, what you should do is get the key set of the Hashtable and create a TreeSet from it. You can then get an iterator() from the created TreeSet that will have the keys in order. If you can’t use the collections framework, you’ll have the sort the Enumeration you get back from keys() yourself.

48.Which collections in Java are synchronized and which aren’t ?
The original collection classes in Java are all synchronized: Vector and Hashtable, along with their subclasses Stack and Properties. Those classes introduced with the Java 2 Collections Framework are all NOT synchronized by default, the sets, lists, and maps

49.What are the differences between ArrayList and LinkedList ?
An ArrayList is a List implementation backed by a Java array, similar to the Vector class. As the number of elements in the collection increases, the internal array grows to fit them. If there are lots of growth periods, performance degrades as the old array needs to be copied into the new array. However, random access is very quick as it uses an array index to access.
With a LinkedList, the List implementation is backed by a doubly linked list data structure, allowing easy inserts/deletions anywhere in the structure, but really slow random accesses as the access must start at an end to get to the specific position.

Which you use really depends on the type of operations you need to support.

50.How do I read input from a stream “one word at a time” ?           What you need to do is use the java.util.StringTokenizer or to parse your input into words. Each has a default set of delimiters like white space that can be changed. The following demonstrates the using of StringTokenizer to count words in a file.

import java.util.*;

public class Test {
static final Integer ONE = new Integer(1);

public static void main (String args[])
throws IOException {

Map map = new TreeMap();
FileReader fr = new FileReader(args[0]);
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
processLine(line, map);
static void processLine(String line, Map map) {
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
addWord(map, st.nextToken());
static void addWord(Map map, String word) {
Object obj = map.get(word);
if (obj == null) {
map.put(word, ONE);
} else {
int i = ((Integer)obj).intValue() + 1;
map.put(word, new Integer(i));
static void printMap(Map map) {
Set set = map.entrySet();
Iterator it = set.iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry);
System.out.println(entry.getKey() +
“: ” + entry.getValue());

51.Do the keys() and elements() methods of a Hashtable enumerate things in the same order ?
There is no requirement that the elements are returned in the same order, only that all of them are returned in the Enumeration. Your best bet for getting the element for a key is to loop through the keys() returned and fetch the element for each. Or, if you can use a HashMap instead of a Hashtable, work with the Map.Entry that is returned by the keySet(). This includes both the key and value together, not requiring a separate lookup.

52.How do I treat an object I get out of a Vector (collection) as the type I put into it  ?
When you get an object out of a Vector (or any collection), the object is returned as being of type Object. You need to cast it back into the object type you put into the data structure if you need to call or treat the object as the original type.
For instance, if you add an array to a vector:

String args[] = {“1”, “2”, “3”};
Vector v = new Vector();

Then, when you get the object out of the vector, you need to cast it back to the original type:
String args2[] = (String[])v.firstElement();

53.What is the difference between a singly linked list and doubley linked list ?
A singly linked list is one that has only a pointer/reference to the next element in the list. A doubley linked list has both a previous and next pointer/reference.

54.What is meant by natural ordering of objects in the context of the collections framework ?
Java documentation refers to the natural ordering of objects when describing various algorithms and data structures in the collections framework. Object ordering is obviously needed by the sorting algorithms. It is also needed by the specifications of the interfaces such as SortedSet, SortedMap, etc., and the data structures used for container classes such as TreeSet, TreeMap, etc. Unless instructed otherwise via a Comparator object supplied as an argument to the constructor, the default behavior of a class such as TreeSet is to store its objects in an ascending natural order.
The objects of a class exhibit natural ordering if the class has implemented the java.lang.Comparable interface. Such a class must provide an implementation for the compareTo method — referred to as the class’s natural comparison method — that can then be used by the algorithms and the data structures for comparing data objects. The compareTo method must return a negative integer, a zero, or a positive integer if the object on which it is invoked is less than, equal to, or greater than the argument object.

It is strongly recommended that a class’s natural ordering as dictated by the implementation of the compareTo method be consistent with equals. This consistency is achieved if and only if e1.compareTo( (Object) e2 ) == 0 has the same boolean value as e1.equals( (Object) e2 ) for every pair of objects e1 and e2 of the class. Lack of this consistency could elicit strange behavior from the data structures that need to compare objects.

Many of the system supplied classes possess natural ordering. These include String, Integer, Float, Double, Date, File and many others. For the String class, the natural order is lexicographic; it is chronological for the Date class; lexicographic on the pathname for the File class, etc.

55.What is a fail-fast iterator ?
An iterator is considered fail-fast if it throws a ConcurrentModificationException under either of the following two conditions:
In multithreaded processing: if one thread is trying to modify a Collection while another thread is iterating over it.

In single-threaded or in multithreaded processing: if after the creation of the Iterator, the container is modified at any time by any method other than the Iterator’s own remove or add methods.
Note in particular what is implied by the second condition: After we create a container’s iterator, during a loop that iterates over the container we must only use the remove (and when applicable add) methods defined for the iterator and that we must NOT use the same methods defined for the container itself. To illustrate this point, suppose we declare and initialize a List in the following manner
List list = new ArrayList();

Let’s say we wish to iterate over this list. We’d need to declare a ListIterator as follows:
ListIterator iter = list.listIterator();

Having created this iterator, we could now set up a loop like:
String str =;
// do something with str

Because iter is fail-fast, we are not allowed to invoke List’s add or remove methods inside the loop. Inside the loop, we are only allowed to use ListIterator’s add and remove methods. This makes sense because it is the Iterator object that knows where it is in a List as the List is being scanned. The List object itself would have no idea of that.
The Iterators supported by all the work-horse container classes, such as ArrayList, LinkedList, TreeSet, and HashSet, are fail-fast. The Iterator type retrofitted to the older container class Vector is also fail-fast. For associative containers, such as HashMap and the older HashTable, the Iterator type for the Collections corresponding to either the keys or the values or the <key, value> pairs are fail-fast with respect to the container itself. That means that even if you are iterating over, say, just the keys of the container, any illegal concurrent modifications to the underlying container would be detected.

One final note regarding iterators versus enumerations: It is also possible to use an Enumeration object returned by the elements() method for iterating over the older container types such as Vector. However, Enumerations do not provide a fail-fast method. On the other hand, the more modern Iterator returned by a Vector’s iterator() and listIterator() methods are fail-fast. Hence, iterators are recommended over enumerations for iterating over the elements of the older container types.

56.How do you sort the elements of a vector ?
Since the Vector class implements the List interface, you can call the Collections.sort() method to sort the elements in place. You can also manually insert elements into a Vector to keep the vector sorted. Of course, if keeping sorted access is such a big deal, you should consider using a different, more appropriate data structure like a TreeSet.
For 1.1 Java users, you’ll need to sort the elements yourself. There is no built-in support for this. A better option might be to sort the elements as you insert each element.

57.What is a WeakHashMap? What is its use and when should you use it ?
A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference. By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren’t used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn’t mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn’t externally referenced could stay around for a long time.

58.What is the function of a load factor in a Hashtable ?
The load factor determines how full a hashtable may get before it expands its capacity. I think that the comments on the Hashtable API docs explain it very well:
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

59.How do you control growth of vectors when their internal arrays are full ?
The vector constructor can include either an initial capacity or a capacity and growth increment. When not specified, the initial size of the vector is 10 and growth will double when necessary. Otherwise, initialize size and growth will grow when needed as specified by the arguments to the constructor.
If the argument to the constructor is a collection, the initial size of the internal structure is 10% larger than the collection. Since there is no second argument to control growth, the capacity will double when necessary.

60.How to sort the messages in JavaMail ?
Within the JavaMail classes there is no support for this. However, once you get the array of messages back from a folder, you can call the Arrays.sort() method in the collections framework to sort the messges. Since MimeMessage doesn’t implement Comparable, you’ll need to provide your own Comparator specifying how you want the messages to be sorted.

61.When did Strings start caching their hash codes ?
Starting with the 1.3 release of Java, the java.lang.String class will only calculate the hashcode once, when its first needed. Future calls to hashCode() will return the previously calculated value.

62.How can you retrieve the Hashtable’s load factor ?
There is no public interface to access the load factor setting.
Some choices you can do to expose this value…

Subclass Hashtable and add a read-only accessor method
Use reflection to access the private field (only possible in trusted environment)
Serialize the Hashtable and get the value from the stream (when reading back the stream, you’ll have to figure out where the appropriate field is)

63.Why can’t I add a collection to itself ?
This will cause a stack overflow exception to be generated on calls to methods like toString() and hashCode(), which recursively call the method on the elements of the collection.


One Response

  1. Can you explain, what if 10 objects have same hashcode, that means all of these objects are equal, even if equal returns false. Is it true if 2 objects are equal, then their hashcode will/shuld be equal. what happens if we put the 10 objects in hashset.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: