Home > J2SE > Collection Framework – Question Answer way!

Collection Framework – Question Answer way!

Q. What is collection framework ?

A. The collection framework presents a set of standard utility classes for manging group of objects.

Arbitrary objects can be stored, retrieved and manipulated as elements of collection.

Q. Which package has collection framework ?

this framework is provided in java.util package

Q. What is Mathamatical concept of a set?

A. A set is just a group of unique items, meaning that the group contains no duplicates.

Some real-world examples of sets include the following:

  • The set of uppercase letters ‘A’ through ‘Z’
  • The set of nonnegative integers {0, 1, 2 …}

These examples show the basic properties of sets:

  • Sets contains only one instance of each item
  • Sets may be finite or infinite
  • Sets can define abstract concepts
The idea of a “connection pool” is a set of open connections to a database server.
Web servers have to manage sets of clients and connections.
File descriptors provide another example of a set in the operating system.
Q. What is Mathamatical concept of a Map?
A. It is a set of pairs, each pair representing a one-directional “mapping” from one element to another. Some examples of maps are:

  • The map of IP addresses to domain names (DNS)
  • A map from keys to database records
  • A dictionary (words mapped to meanings)
  • The conversion from base 2 to base 10
Q. Why Map don’t extend collection ?
A. The typical application of a Map is to provide access to values stored by keys. The set of collection operations are all there, but you work with a key-value pair, instead of an isolated element. Map is therefore designed to support the basic operations of get() and put() which are not required by Set.
!Note: When designing software with the Collections Framework, it is useful to remember the following hierarchical relationships of the four
basic interfaces of the framework:
  • The Collection interface is a group of objects, with duplicates allowed
  • Set extends Collection but forbids duplicates
  • List extends Collection also, allows duplicates and introduces positional indexing (order of element is retained)
  • Map extends neither Set nor Collection
The following table shows the six collection implementations introduced with the Java 2 framework
Interface Implementation Historical
Set(.) no duplicate(.)at most one null HashSet(.) No OrderHashing: Constant time for add, remove, contain, size

Key->Hashcode->Index

(.) no guaranty of order

TreeSet(.) Sorted

Assenting

(.) Use tree for storage

(.) large data, sorted order, found quickly

Comparator

LinkedHashSet(.) Insertion Order
List(.)allow duplicate(.)Positional indexing(.) Insertion Order ArrayList(.)notSynchronized(.)Random Access

(.)Easy Tail manipulation

(.)default size 0.

LinkedList(.)Sequential Access(.)Add Remove Element in between Vector
Stack(.)synchronized, make it slow(.) default size 10Then double
Map(.)Unique Key HashMap(.)Allow Null as key & value(.)unsynchronized(.)no order

(.) get/put constant time for larger map

TreeMap(.) Sorted in Key order(.)Natural ordering

Comparator

LinkeHashMap(.) Key insertion order. Hashtable
Properties(.)synchronized(.)can only store object the override hashCode() and equals()

Sting does.

Collection Interface
The Collection interface is used to represent any group of objects, or elements. You use the interface when you wish to work with a group of elements in as general a manner as possible.
UML Diagram for Collection Interface
Iterator Interface

UML Diagram for Iterator Interface

Q. What is the difference between HashSet & TreeSet
A. HashSet is not sorted while TreeSet is.
1) HashSet: For efficiency, objects added to a HashSet need to implement the hashCode() method in a manner that properly distributes the hash codes. While most system classes override the default hashCode() implementation in Object, when creating your own classes to add to a HashSet remember to override hashCode()
2) TreeSet: The TreeSet implementation is useful when you need to extract elements from a collection in a sorted manner. In order to work property, elements added to a TreeSet must be sortable.

To optimize HashSet space usage, you can tune the initial capacity and load factor. The TreeSet has no tuning options, as the tree is always balanced, ensuring log(n) performance for insertions, deletions, and queries.

!Note: All Collection concrete classes implements Cloneable & Serializable interface.

Q. Can an implementation of collection be changed ?

Each of the implementation of Collection interface provides a constructor for creating a collection based on elements of another Collection object passed as an argument. This interchangeability is true among Map implementation as well.

But Collection and Maps are not interchangeable.

Below example demonstrate use of HashSet, TreeSet and the way HashSet can be interchanged to TreeSet.

public class SetExample {
  public static void main(String args[]) {
    Set set = new HashSet();
    set.add("Bernadine");
    set.add("Elizabeth");
    set.add("Gene");
    set.add("Elizabeth");
    set.add("Clara");
    System.out.println(set);
    Set sortedSet = new TreeSet(set);
    System.out.println(sortedSet);
  }
}
Running the program produces the following output. Notice that the duplicate entry is only present once, and the second list output is sorted.
[Gene, Clara, Bernadine, Elizabeth]
[Bernadine, Clara, Elizabeth, Gene]
Q. What does  AbstractSet class overrides?
A.The AbstractSet class overrides the equals() and hashCode() methods to ensure two equal sets return the same hash code. Two sets are equal if they are the same size and contain the same elements. By definition, the hash code for a set is the sum of the hash codes for the elements of the set. Thus, no matter what the internal ordering of the sets, two equal sets will report the same hash code.

Q. How List is different from Set ?

A. List is an

Ordered collection

Permitting Duplicates

Ability to work with part of the list

Bidirectional Iterattion

Q. When to use LinkedList & when ArrayList?

 ArrayList: If you need to support random access, without inserting or removing elements from any place other than the end, than ArrayList offers the optimal collection

LinkedList: you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially then LinkedList offers the better implementation

!Note: Two List are equal if they are the same size and contain the same elements in the same order.

Q. How can we determine the length of an ArrayList ? 

A. a.size();

Q. What is Map.Entity?

A. The entrySet() method of Map returns a collection of objects that implement Map.Entry interface. Each object in the collection is a specific key-value pair in the underlying Map.

!Note : Both the key and value can be null. However, you should not add a Map to itself as a key or value.

Q. Difference between HashMap & TreeMap ?

A. HashMap: Deleting, and locating elements in a Map, the HashMap offers the best alternative

TreeMap: You need to traverse the keys in a sorted order, then TreeMap is your better alternative.

Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal. Using a HashMap requires that the class of key added have a well-defined hashCode() implementation. With the TreeMap implementation, elements added to the map must be sortable.

To optimize HashMap space usage, you can tune the initial capacity and load factor. The TreeMap has no tuning options, as the tree is always balanced.

!Note: Similar to the other abstract collection implementations, the AbstractMap class overrides the equals() and hashCode() methods to ensure two equal maps return the same hash code. Two maps are equal if they are the same size, contain the same keys, and each key maps to the same value in both maps. By definition, the hash code for a map is the sum of the hash codes for the elements of the map, where each element is an implementation of the Map.Entry interface. Thus, no matter what the internal ordering of the maps, two equal maps will report the same hash code.

Q. What is Comparator?

A. Defines how two objects are compared.

Q. What is Autoboxing and Unboxing

A. As Collection can not store primitives. Java perform the proper Autoboxing and Unboxing needed when storing or retrieving primitive types.

Q. Collection extends Iterable interface

A. Means can be cycled using for each type for loop.

Q. 

Categories: J2SE
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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

Follow

Get every new post delivered to your Inbox.