Java By Kiran
Java Training Institute in Pune
Java Training Institute in Pune
Fail-safe iterators are just opposite to fail-fast.
They never fail if you modify the underlying collection on which they are iterating, because they work on
clone of Collection instead of original collection and that’s why they are called as fail-safe iterator.
Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException..
We can use any class as Map Key, however following points should be considered before using them.
If the class overrides equals() method, it should also override hashCode() method. The class should follow the rules associated with equals() and hashCode() for all instances.
If a class field is not used in equals(), you should not use it in hashCode() method. Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance.
Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability.
let’s say I have a class MyKey that I am using for HashMap key. //MyKey name argument passed is used for equals() and hashCode()This is the reason why String and Integer are mostly used as HashMap keys.
MyKey key = new MyKey("Pankaj"); //assume hashCode=1234
// Below code will change the key hashCode() and equals()
// but it's location is not changed.
key.setName("Amit"); //assume new hashCode=7890
//below will return null, because HashMap will try to look for key
//in the same index as it was stored but since key is mutated,
//there will be no match and it will return null.
A collection designed for holding elements prior to processing.
Besides basic Collection operations, queues provide additional insertion, extraction, and inspection operations.
Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.
Stack is also a form of Queue but one difference, it is LIFO (last-in-first-out).
Whatever the ordering used, the head of the queue is that element which would be removed by a call to remove() or poll(). Also note that Stack and Vector are both synchronized.
Use a queue if you want to process a stream of incoming items in the order that they are received.Good for work lists and handling requests.
Use a stack if you want to push and pop from the top of the stack only. Good for recursive algorithms.
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements.
IdentityHashMap class is not a widely used Map implementation.
While this class implements the Map interface, it intentionally violates Map’s general contract, which
NavigableMap Map was added in Java 1.6, it adds navigation capability to Map data structure.
It provides methods like lowerKey() to get keys which is less than specified key, floorKey() to return keys which is less than or equal to specified key, ceilingKey() to get keys which is greater than or equal to specified key and higherKey() to return keys which is greater specified key from a Map.
It also provide similar methods to get entries e.g. lowerEntry(), floorEntry(), ceilingEntry() and higherEntry().
Apart from navigation methods, it also provides utilities to create sub-Map e.g. creating a Map from entries of an exsiting Map like tailMap, headMap and subMap. headMap() method returns a NavigableMap whose keys are less than specified, tailMap() returns a NavigableMap whose keys are greater than the specified and subMap() gives a NavigableMap between a range, specified by toKey to fromKey.
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.
Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface.
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.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room. A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.
In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. Read How HashMap works in Java for detailed explanation on how equals and hashcode method is used to put and get object from HashMap.
Use following methods:
These methods takes collection parameter and return a new read-only collection with same elements as in original collection.
A Queue that additionally supports operations that wait for the queue to become non-empty when
retrieving an element, and wait for space to become available in the queue when storing an element.
BlockingQueue methods come in four forms: one throws an exception, the second returns a special value
(either null or false, depending on the operation), the third blocks the current thread indefinitely until the
operation can succeed, and the fourth blocks for only a given maximum time limit before giving up.
This is another advanced level collection interview questions in Java which normally asked to check whether interviewer is familiar with optimization done on ConcurrentHashMap or not. ConcurrentHashMap is better suited for situation where you have multiple readers and one Writer or fewer writers since Map gets locked only during write operation. If you have equal number of reader and writer than ConcurrentHashMap will perform in line of Hashtable or synchronized HashMap.
We have three implementation of List : 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
ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it’s elements.
This tricky Java questions is part of How HashMap works in Java, which is also a popular topic to create confusing and tricky question in Java. well if you put the same key again than it will replace the old mapping because HashMap doesn't allow duplicate keys.
You will not be able to recover your object from hash Map if that is used as key in HashMap.
javac compiler for Java 5 generates unchecked warnings if you use combine raw types and generics types. You can be suppress those warnings by using @SuppressWarnings("unchecked") annotation.
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.