Q1) What is difference between ArrayList and vector?
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe. |
||||||||||||||||||
Q2) How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
|
||||||||||||||||||
Q3) If an Employee class is present and its objects are
added in an arrayList. Now I want the list to be sorted on the basis of
the employeeID of Employee class. What are the steps?
Ans) 1) Implement Comparable interface for the
Employee class and override the compareTo(Object obj) method in which
compare the employeeID
2) Now call Collections.sort() method and pass list as an argument. |
||||||||||||||||||
Q4)What is difference between HashMap and HashTable?
Ans)
Both collections implements Map. Both collections store value as key-value pairs.
The key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is. |
||||||||||||||||||
Q5) What are the classes implementing List interface?
Ans) There are three classes that implement List interface: 1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be increased dynamically also operations like add,remove and get can be formed once the object is created. It also ensures that the data is retrieved in the manner it was stored. The ArrayList is not thread-safe. 2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around a synchronized block. 3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In First Out) operation for add operation. It is faster if than ArrayList if it performs insertion and deletion of elements from the middle of a list. |
||||||||||||||||||
Q6) Which all classes implement Set interface?
Ans)
A Set is a collection that contains no duplicate elements. More formally, sets contain
no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. HashSet,SortedSet and TreeSet are the commnly used class which implements Set interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows the data to be iterated in the ascending order or sorted on the basis of Comparator or Comparable interface. All elements inserted into the interface must implement Comparable or Comparator interface. TreeSet - It is the implementation of SortedSet interface.This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). The class is not synchronized. HashSet: This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will remain constant over time. This class permits the null element. This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets |
||||||||||||||||||
Q7) What is difference between List and a Set?
Ans) 1) List can contain duplicate values but Set doesnt allow. Set allows only to unique elements. 2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt ensures the sequence in which data can be retrieved.(Except HashSet) |
||||||||||||||||||
Q8) What is difference between Arrays and ArrayList ?
Ans)
Arrays are created of fix size whereas ArrayList is of not fix size. It means that once array is declared as :
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
List list = new ArrayList();
|
||||||||||||||||||
Q9) When to use ArrayList or LinkedList ?
Ans) 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.
Source : Read More - from java.sun |
||||||||||||||||||
Q10)
Consider a scenario. If an ArrayList has to be iterate to read data
only, what are the possible ways and which is the fastest?
Ans) It can be done in two ways, using for
loop or using iterator of ArrayList. The first option is faster than
using iterator. Because value stored in arraylist is indexed access. So
while accessing the value is accessed directly as per the index.
|
||||||||||||||||||
Q11)
Now another question with respect to above question is if accessing
through iterator is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the
array(add or remove operation) inside the loop whereas Iterator does.
Also Iterator can be used where there is no clue what type of
collections will be used because all collections have iterator.
|
||||||||||||||||||
Q12) Which design pattern Iterator follows?
Ans) It follows Iterator design pattern. Iterator
Pattern is a type of behavioral pattern.
The Iterator pattern is one, which allows you to navigate through a
collection of data using a common interface without knowing about the
underlying implementation.
Iterator should be implemented as an interface. This allows the
user to implement it anyway its easier for him/her to return data.
The benefits of Iterator are about their strength to provide a
common interface for iterating through collections without bothering
about underlying implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an example of the Iterator pattern. It represents and abstract means of iterating over a collection of elements in some sequential order without the client having to know the representation of the collection being iterated over. It can be used to provide a uniform interface for traversing collections of all kinds. |
||||||||||||||||||
Q13) Why is it preferred to declare:
List<String> list = new ArrayList<String>(); instead of
ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
|
||||||||||||||||||
Q14) What is difference between iterator access and index access?
Ans) Index based access allow access of the
element directly on the basis of index. The cursor of the datastructure
can directly goto the 'n' location and get the element. It doesnot
traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired element.So to reach the 'n'th element it need to traverse through n-1 elements. Insertion,updation or deletion will be faster for iterator based access if the operations are performed on elements present in between the datastructure. Insertion,updation or deletion will be faster for index based access if the operations are performed on elements present at last of the datastructure. Traversal or search in index based datastructure is faster. ArrayList is index access and LinkedList is iterator access. |
||||||||||||||||||
Q15) How to sort list in reverse order?
Ans) To sort the elements of the List in the
reverse natural order of the strings, get a reverse Comparator from the
Collections class with reverseOrder(). Then, pass the reverse
Comparator to the sort() method.
| ||||||||||||||||||
Q16) Can a null element added to a Treeset or HashSet?
Ans) A null element can be added only if the
set contains one element because when a second element is added then as
per set defination a check is made to check duplicate value and
comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element. |
||||||||||||||||||
Q17) How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
|
||||||||||||||||||
Q18) How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) A list implemenation can be made read only using Collections.unmodifiableList(list).
This method returns a new list. If a user tries to perform add
operation on the new list; UnSupportedOperationException is thrown.
|
||||||||||||||||||
Q19) What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe
implementation of Map interface. In this class put and remove method are
synchronized but not get method. This class is different from Hashtable
in terms of locking; it means that hashtable use object level lock but
this class uses bucket level lock thus having better performance.
|
||||||||||||||||||
Q20) Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
|
||||||||||||||||||
Q21) Which data structure HashSet implements
Ans) HashSet implements hashmap internally to
store the data. The data passed to hashset is stored as key in hashmap
with null as value.
|
||||||||||||||||||
Q22) Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
|
||||||||||||||||||
Q23) What is identityHashMap?
Ans) The IdentityHashMap uses == for equality
checking instead of equals(). This can be used for both performance
reasons, if you know that two different elements will never be equals
and for preventing spoofing, where an object tries to imitate another.
|
||||||||||||||||||
Q24) What is WeakHashMap?
Ans) A hashtable-based Map implementation with
weak keys. An entry in a WeakHashMap will automatically be removed when
its key is no longer in ordinary use. More precisely, the presence of a
mapping for a given key will not prevent the key from being discarded by
the garbage collector, that is, made finalizable, finalized, and then
reclaimed. When a key has been discarded its entry is effectively
removed from the map, so this class behaves somewhat differently than
other Map implementations.
What is an Iterator ?
47.How do you traverse through a collection using its Iterator?
To use an iterator to traverse through the contents of a collection, follow these steps:
48.How do you remove elements during Iteration?
Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.
49.What is the difference between Enumeration and Iterator?
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element
51.What is the List interface?
52.What are the main implementations of the List interface ?
The main implementations of the List interface are as follows :
53.What are the advantages of ArrayList over arrays ?
Some of the advantages ArrayList has over arrays are:
54.Difference between ArrayList and Vector ?
55.How to obtain Array from an ArrayList ?
Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList(); arrayList.add(… Object a[] = arrayList.toArray();
Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
58.How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, 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.
What is the Properties class? The properties class is a subclass of Hashtable that can be read from or written to a stream. It also provides the capability to specify a set of default values to be used. What is the Difference between the Iterator and ListIterator? Iterator : Iterator Can Only get Data From forward Direction . ListIterator: An iterator for lists that allows one to traverse the list in either direction.modify the list during iteration, and obtain the iterator’s current position in the list. A ListIterator has no current element. its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive. - |
Thursday, 11 July 2013
Collections Interview Questions
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment