Wednesday, July 6, 2016

Java List Interview Questions Answers

When the contains() method of list throws NullPointerException ?
Ans : if the specified element is null and this list does not permit null elements.

Is it safe to modify the array of object returned by the toArray() method of list ?
Ans : The returned array will be "safe" in that no references to it are maintained by this list.  (In other words, this method must allocate a new array even if this list is backed by an array). The caller is thus free to modify the returned array.

Explain Remove method of list
Ans: Removes the first occurrence of the specified element from this list,  if it is present (optional operation).  If this list does not contain the element, it is unchanged.  More formally, removes the element with the lowest index  if this list contained the specified element (or equivalently, if this list changed  as a result of the call).
     
This method throws ClassCastException if the type of the specified element is incompatible with this list (optional)

This method throws NullPointerException if the specified element is null and this list does not permit null elements
This method throws UnsupportedOperationException if the operation   is not supported by this list

Is it possible to get some number of elements sequence from the List ?
Ans: Yes it is possible using the ListIterator<E> listIterator(int index) method.
This method will return all the elements from the list from the specified index position to the size of the list. 

Also you can get some specifi range of elements from list using the 
List<E> subList(int fromIndex, int toIndex) method. here the elements at the fromIdex will be inclusive and toIndex is exclusive. If both of the specified index values are same then the returned list will be empty.
And any non structural changes made into the returned list will be reflected into the original list. (Structural modifications are those that changes the size of the this list)

How can you remove five elements in one shot from the list without using the remove(int index) method ?
Ans: using the subList(int fromIndex, int toIndex) method you can remove multiple elements simultaneously from 'this' list. 
exmple : subList(4,6).clear();
Here the 4th and 5th element will be removed from the list.





No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...