Showing posts with label Collection interview questions and answers. Show all posts
Showing posts with label Collection interview questions and answers. Show all posts

Tuesday, August 21, 2012

Vector Operations Using Java Programming


import java.util.Iterator;
import java.util.Vector;

public class VectorOperations {

public static void main(String args[]){
Vector vt=new Vector();

vt.add(21);
vt.add(12);
vt.add(57);
vt.add(29);
vt.add(43);

System.out.println("Vector"+vt);

//Adding elements in Vector
vt.add(2, 25);
System.out.println("Vector"+vt);
vt.addElement(23);
System.out.println("Vector"+vt);

//Vector Operations.
System.out.println("Capacity"+vt.capacity());
System.out.println("Conatains 43:"+vt.contains(43));
System.out.println("First element"+vt.firstElement());
System.out.println("Value at Index 4: "+vt.get(4));
System.out.println("Remove value at 3"+vt.remove(3));

vt.add(43);
vt.add(45);
vt.add(46);
vt.add(47);
vt.add(48);
vt.add(49);
vt.add(32);
vt.add(33);
vt.add(34);

System.out.println("Vector Elements afte insertion more than 10 elements");
Iterator it=vt.iterator();
while(it.hasNext())
System.out.print(" "+it.next());
}

}


Output:

Vector[21, 12, 25, 57, 29, 43, 23]
Capacity10
Conatains 43:true
First element21
Value at Index 4: 29
Remove value at 357
Vector Elements afte insertion more than 10 elements
 21 12 25 29 43 23 43 45 46 47 48 49 32 33 34

Queue Operations Using LinkedList in Java



import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;


public class QueueOperations {

public static void main(String args[]){

Queue que=new LinkedList();

//Insert elements into Queue
que.offer(12);
que.offer(25);
que.offer(75);
que.offer(9);

System.out.println("Queue"+que);

//Queue Operations
System.out.println("Queue Peek the elmenet  "+que.peek());
System.out.println("Queue Remove Element "+que.poll());

System.out.println("isEmpty :?"+que.isEmpty());
}
}

Output:
Queue[12, 25, 75, 9]
Queue Peek the elmenet  12
Queue Remove Element 12
isEmpty :?false

Stack Operations Using Java Programming


import java.util.Iterator;
import java.util.Stack;

public class StackOperations {

public static void main(String args[]){
Stack st=new Stack();

//Push the elments into stack
st.push(12);
st.push(9);
st.push(15);
st.push(76);
st.push(55);

//Elements in stack
System.out.println("Stack"+st);

//Pop the Elements
System.out.println("Top of the Stack:"+st.peek());
System.out.println("Pop the element from stack "+st.pop());

//Display elements using iterator
Iterator it=st.iterator();
while(it.hasNext())
System.out.println(it.next());

//Check stack is Empty or not
System.out.println("Stack is empty ?"+st.isEmpty());

}
}

Output:
Stack[12, 9, 15, 76, 55]
Top of the Stack:55
Pop the element from stack 55
12
9
15
76
Stack is empty ?false

Monday, August 20, 2012

Java Collection Programming Interview Questions



What is the Difference between Enumeration and Iterator interface?
1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
4. Enumeration act as read-only elements. Iterator we can manipulate the objects also like adding and removing the objects.

Where will you use Hashtable and where will you use HashMap?
The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one.
If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.

Which one will provide the faster insertion of a new element into the middle positoin. Vector / ArrayList / LinkedList 
ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

List - this is an ordered list of objects, insertion order is maintained and retrieval order is in the list order but items can also be random accessed, duplicate items are allowed, generally allow storage of null values (the ones below do), generally fast to iterate and find items by position but slow to do lockups

ArrayList - Unsychronized, nulls allowed (fastest)
Vector - Synchronized, only slightly slower in tests of sizes under 100000
Stack - Synchronized, same speed as Vector, LIFO queue
LinkedList - Unsynchronized, allows two way iteration and modification of items (like a stack or queue)

Set - this a set of items with no duplicates (no two items can compare as equal), ordering is typically inconsistent over multiple set iterations depending on the implementation but you should assume the order is effectively random unless the set specifies ordered iteration, generally ok to iterate and fast to do lookups
HashSet - Unsychronized (fastest), slower than HashMap which it is built on, allows nulls
LinkedHashSet - Unsychronized, ordered by insertion, allows nulls
TreeSet - Unsychronized, ordered by the natural ordering of the items or a comparator provided at construction, allows nulls but there are issues with removing them

Map - Stores key/value pairs (maps keys to values) where the keys must be unique, order of iteration over keys, values, or pairs is highly dependent on the implementation of the map, allowed nulls also vary by implementation, generally very fast to lookup keys and slow to lookup values
LinkedHashMap - Unsychronized, all iterators are ordered based on insertion order of the original key (does not change if a key is reinserted), allows null values but null keys are not allowed
TreeMap - Unsychronized, iterators are ordered by the natural or comparator ordering of the keys, allows null keys and values but the comparator needs to understand them

Reference: http://docs.oracle.com/javase/tutorial/collections/TOC.html


Collection interview Questions in Java 2


ArrayList vs LinkedList

Adding new elements is pretty fast for either type of list. For the ArrayList, doing  random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements, using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot of editing in the middle of the list.

Array vs ArrayList vs LinkedList vs Vector in java

Array vs ArrayList:
ArrayList is much better than Array, when the size need to be increased dynamically. Efficiency is possible with arrays. ArrayList permits null elements.
ArrayList has group of objects. Array it treated as an object.

LinkedList vs Vector:
A vector is a growable array which can store many objects of different classes.
A linked list is a linear list where each item has a link to the next item in the list. It can be used to implement queue or stack operations.

ArrayList vs LinkedList
Array list is better than linked list for accessing elements.Linked list is better than array list to perform insertion and deletion operations at arbitrary locations.

Vector Vs ArrayList
Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
ArrayList has no default size while vector has a default size of 10.

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.

equals vs toString vs hashcod are methods in Object

Sort Diff b/w Arrays and Collections

Both use the same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array.