Collections Java Interview Questions – Set 05

What is an Iterator

Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that 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.

What is the Difference between the Iterator and ListIterator

Iterator : Iterator takes the place of Enumeration in the Java collections framework. One can traverse throughr the the collection with the help of iterator in forward direction only and Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics

ListIterator: An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive.

How do you get an immutable collection

This functionality is provided by the Collections class, which is a wrapper implementation using the decorator design pattern.

public class ReadOnlyExample {

public static void main(String args[ ]) {

Set<string> set = new HashSet<string>( );

set.add(“Java”);

set.add(“JEE”);

set.add(“Spring”);

set.add(“Hibernate”);

set = Collections.unmodifiableSet(set);

set.add(“Ajax”);                                           // not allowed.

}

}

Set & List interface extend Collection, so Why doesn’t Map interface extend Collection

Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun’s FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is “Key-value pairs”, but this provides a very limited (and not particularly useful) Map abstraction. You can’t ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There’s no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three “Collection view operations” on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That’s why we don’t have a map view operation on Lists.

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.

What does the following code do? Can the LinkedHashSet be replaced with a HashSet

import java.util.ArrayList;

import java.util.LinkedHashSet;

import java.util.List;

 

public class CollectionFunction {

    public <e> List<e> function (List <e> list) {

          return new ArrayList<e>(new LinkedHashSet<e>(list));

    }

}

The above code removes duplicates from a supplied list by passing it through an implementation of a Set interface. In this case, a LinkedHashSet is used to honor the ordering by implementing a SortedSet interface. If ordering is not required, the LinkedHashSet can be replaced with a HashSet.

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, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.

How can we make Hashmap synchronized

HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);

How to Make a Map or List as Thread-Safe or Synchronized Collection

Collections.synchronizedMap(new HashMap());

Collections.synchronizedList(List<T> list)