Java Interview Question Part - 3

Q3.What is the difference between an ArrayList and Vector?
Ans:  ArrayList is not thread safe and vector is thread safe because synchronization.
In vector class each method like add(),add(int i) is surrounded with synchronized block,
Both vector and ArrayList hold into their contents. A vector defaults to double the size of
it's array which ArrayList increase it's array size be 50 percentage .
vector is thread-safe that way the performance is slower than ArrayList.

Q2. Defference Between comparable and Comparator in java?
Ans: Comparable and comparator both are the generic interface in java used to compare the data element of object.
Comparable interface is present in the java.lang.package and
comparator interface is present in Java.util package .
The basic difference between Comparable and Comparator interfaces is the comparable interface provides
the single sorting sequence and Comparator interface provide the multiple sorting sequences.
The Comparable interface contains only single method
Public int compareTo(Object obj)  .In Comparator interface contain two methods Public int compare(Object obj1,Object obj2)
and boolean equals(Object obj).

Note: If you want to sorte the objects in natural ordering then you can used the Comparable interface
and If you want to sort objects based in any attribute then comparator interface is used.

Q3.What is the difference between HashMap and HashTable?
Ans: HashMap is not Synchronized in natural but HashTable is thread safe. HashMap is traversed using an iterator, HashTable can
enumerator or iterator. HashMap permit null values and only one null key, while HashTable  does not allow key or value as null.

Q4. What is difference between Enumeration and Iterator in Java?
Ans:Iterator interface introduced in JDK 1.2 and Enumerattion interface is ther from JDK 1.0
In both of the interfaces Enumeration can only traverses the Collection Object and you can not do any modifications to collection while traversing it.
In Iterator you can remove  an element of the colleciton while traversing it.

Q5. What is difference iterator and ListIterator ?
Ans:  Iterator is used for traversing List and Set both but ListIterator to traverse List Only.
We can traverse in only forward direction using Iterator, using ListIterator we can traverse a List in both direction (forward and backword).

In ListIterator using we can add element at any time while traversing.

Q6. Difference between ArrayList and LinkedList ?
Ans: ArrayList internally uses dynamic array to sore the elements and LinkedList internally uses Double Linked List to store the elements.
For manipulatation ArrayList is Slow becuase it's internally uses array and LinkList is faster  because it's uses Double Linked List.

ArrayList is goven good performance in Sorting and Accessing data and LinkedList is better for manipulating data. 

No comments: