Monday, August 20, 2012

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.

No comments:

Post a Comment

Thanks for your valuable comments