Java Collection framework tips

What is a Collection? 
• An object that groups multiple elements into a single unit.
 • Sometimes called a container

     img courtesy -

There are two ways to traverse collections:
1) using Iterators.
2) with the (enhanced) for-each construct


• An Iterator is an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired.

• You get an Iterator for a collection by calling its iterator method.

• Suppose collection is an instance of a Collection. Then to print out each element on a separate line:

Iterator it = collection.iterator(); 
while (it.hasNext())

 • Note that next() does two things:
                    1. Returns the current element (initially the first element)
                    2. Steps to the next element and makes it the current element. 

    Levels of Abstraction 

• Recall that Java supports three levels of abstraction: –

 - Interface 

             • Java expression of an ADT
             • Includes method declarations with arguments of specified types, but with empty bodies

 – Abstract Class 

             • Implements only a subset of an interface.
             • Cannot be used to instantiate an object. 

– (Concrete) Classes 

            • May extend one or more abstract classes
            • Must fully implement any interface it implements 
            • Can be used to instantiate objects. 

Iterating Over a Map 

• Because Map does not extend Iterable, but Collection (hence Set) does extend Iterable, you can (only) iterate over a Map using one of its three views:
           – Keys: Set keySet() 
           – Values: Collection values() 
           – Pairs: Set> entrySet()

 What is the root interface in collection hierarchy ? 

Root interface in collection hierarchy is Collection interface . Few interviewer may argue that 
Collection interface extends Iterable interface. So iterable should be the root interface. But you should reply iterable interface present in java.lang package not in java.util package .It is clearly mentioned in Oracle Collection  docs , that Collection interface is a member of the Java Collections framework.  For Iterable interface Oracle doc , iterable interface is not mentioned as a part of the Java Collections framework .So if the question includes  collection hierarchy , then you should answer the question as Collection interface (which is found in java.util package).

 What is the difference between Collection and Collections ?

Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.

 Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe). 

You may also like

No comments: