Pages

Thursday, 12 December 2013

Core Java - Collections Framework (FAQ's)




Collection Framework :   
Framework which defines interfaces & classes to be used to represent a group of individual objects as single entity.























1.    What is Collection ?

Collection is an interface which is used to represent a group of individual objects as a single entity. This interface contains most commonly used methods, applicable to any collection type. Methods present inside collection interface are:

boolean add(object o);
boolean remove(object o);
boolean contains(object o);
boolean addAll(Collection c);
boolean removeAll(Collection c);
boolean retainAll(Collection);
boolean containsAll(Collection c);
boolean isEmpty();
int size();
void clear();
Iterator iterator();
Object[] toArray();




2.    What is basic difference between Arrays & Collections ?

  • Arrays are fixed in size & can hold only homogeneous data elements. Collections are grow-able in size and can hold homogeneous & heterogeneous data elements.
  • Arrays can hold both objects and primitives but collections can hold only objects.
  • Arrays dont have ready made data support but collections have ready made data support because for every collection class underlying data structure is available.

Example:
Arrays        -->  No underlying Data Structure.
ArrayList     -->  Underlying Data Structure is "Resizable or Grow-able Array".
Vector        -->  Underlying Data Structure is "Resizable or Grow-able Array".
LinkedList    -->  Underlying Data Structure is "Double LinkedList". 
HashSet       -->  Underlying Data Structure is "HashTable".  
LinkedHastSet -->  Underlying Data Structure is "LinkedList & HashTable".
TreeSet       -->  Underlying Data Structure is "Balanced Tree".





3.  Why we use List interface ?

List interface is used to represent group of individual objects as single entity where duplicate data elements are allowed & insertion order is preserved using index.

Methods defined in List interface are:
Object get(int index);
Object remove(int index);
Object set(int index, Object new);
void add(int index, Object o);
boolean addAll(int index, Collection c);
int indexOf(object o);
ListIterator listIterator();




4.    What are similarities & differences between ArrayList & Vector ?

Similarities:
For both Arraylist & Vector,

  • Underlying data structure is same "Resizable or Grow-able Array".
  • Heterogeneous objects are allowed.
  • Null insertion is allowed.
  • Duplicate objects are allowed.
  • Insertion order will be preserved.


Differences:
In ArrayList, no method is synchronized, results multiple threads can operate on ArrayList objects simultaneously, thus Arraylist objects are not Thread safe.  But in Vector, all methods are synchronized, results only one thread at a time can operate on Vector object which makes them Thread safe.

In ArrayList, performance is relatively high as no thread has to wait for another thread to finish the task. In Vector, performance is low as one thread operating on vector object, other has to wait till it completes.




5.    What is Iterator ? What is ListIterator ? What are the basic differences between them ?

Iterator:
It's a java cursor used to retrieve object one by one from any collection. We can read & remove collection objects using Iterator concept. It is also called as universal cursor.
Iterator Methods: hasNext(), next() & remove().
Limitations of Iterator: Uni-directional cursor (only read objects in forward direction). Add & replace is not possible with Iterator

ListIterator:
ListIerator is child interface of Iterator interface. It's a java cursor used to read, replace, add & remove collection objects one by one from List.
Iterator Methods: hasnext(), hasPrevious(), next(), previous(), nextIndex(), previousIndex(), add(object new), set(object new) & remove().
Limitations of Iterator: Applicable only to List objects

Differences between Iterator & listIterator:

  • Iterator is applicable to collection objects & listIterator to List objects.
  • Iterator is uni-directionl (forward only) & listIterator is Bi-directional (forward & backward).
  • Using iterators we can read & remove collection objects. using listIterator we can read, remove, add & replace list objects.
  • We can define iterator using iterator() method of collection interface & listIterator using listIterator() method.




6.    What is Enumeration ?

It is a java cursor used to get objects one by one from the collection. It is used for only legacy classes (Vector & Stack). It is Uni-directional (can read object in forward direction only). element() method is used to create enumeration object.
Enumeration Methods: hasMoreElements() & nextElements().
Limitations of Enumeration: It's applicable only to legacy classes (not an universal cursor). Only capable of read operation.




7.    What is "Set" interface ?

Set is child interface of collection. Set represents group of individual objects where duplicates are not allowed & insertion order is not preserved. Set doesn't contain any specific methods, so we have to use the common methods of collection interface.




8.    What is HashSet ? What is LinkedHashSet ? What are the basic differences between them ?

HashSet: Represent represents group of individual objects as single entity where,
Heterogeneous objects allowed.
Null insertion allowed.
Insertion order is not preserved.
Duplicates are not allowed.

Underlying Data Structure - Hash Table.
Implements - Cloneable & Serializable interface
Best use - for frequent search operation (Search based on Hash code of object).

LinkedHashSet:
LinkedHashSet is child class of HashSet.
Duplicates are not allowed.
Insertion order is preserved.
Best use - for developing cache based application where duplicates are not allowed & insertion order need to be preserved.

Differences between HashSet & LinkedHashSet:

Underlying Data Structure for HashSet is "HashTable" & for LinkedHashSet is "LinkedList & Hashtable".
Insertion order is not preserved for HashSet & for LinkedHashSet insertion order ispreserved.


9.      SortedSet/NavigableSet/TreeSet ??
10.    Map (HashMap -> LinkedHashMap) ??
11.    WeakHashMap/IdentityHashMap() ??
12.    SortedMap/NavigableMap()/TreeMap ??
13.    Dictionary/HashTable/Properties ??
14.    Queue/PriorityQueue/BlockingQueue ??
15.    Sorting (Comparable/Comparator) ??
16.    Cursors (Enumeration/Iterator/ListIterator) ??
17.    Utility Classes (Collections/Arrays) ??





More Java Interview questions:

Java.lang Package      |       Exception handling      |       Access Modifiers      |       Interfaces
OOPS concepts         





8 comments:

rmouniak said...

Thanks for sharing this good blog.This is very important and imformative blog for Java .It's very interesting and useful for students
Java Online Training Hyderabad

Dipanwita said...

Excellent blog. java training in chennai

Dipanwita said...

This is a great blog. Loved it. java training in chennai

Anonymous said...

Сумки из кожи вообще не стареют, актуальны всегда и при грамотном использовании сливаются практически с любой верхней. Кожаная сумка выделяется долгим временем ношения и прекраснымстильным внешним видом. При хорошем уходе сумка из естественного природного материала проработает намного дольше, нежели из искусственного, а также с годами сумочка становится еще лучше, раскрывая свой потенциал. Выбрать сумку из кожи нужно воспользовавшись каталогом кожаная сумка, где в наличии достаточно вариаций сумочек. На портале вы обнаружите отзывы клиентов, которые помогут вам сориентироваться и сделать крутой выбор.

jenani said...

Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.
Java Training in Chennai

Java Training in Velachery

Java Training in Tambaram

Java Training in Porur

Java Training in Omr

Java Training in Annanagar

subathara said...

Nice article..content of the article is real and give a valid information.
Digital Marketing Training in Velachery

Digital Marketing Training in Tambaram

Digital Marketing Training in Porur

Digital Marketing Training in Omr

Digital MarketingTraining in Annanagar

Amrita Bansal said...

Very useful post and I think it is rather easy to see from the other comments as well that this post is well written and useful. I bookmarked this blog a while ago because of the useful content and I am never being disappointed. Keep up the good work.

SQL Training in Gurgaon
Advanced Excel /VBA training in Gurgaon
Tableau Training in Gurgaon

Shrof amir said...

Thanks for sharing wonderful article. mobile repair course in hyderabad