Ans: Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack,Hashtable, Array. But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms. Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations. It also includes blocking interfaces and their implementations in java concurrent package. Some of the benefits of collections framework are:
Ans:
Ans: Java 1.5 came with Generics and all collection interfaces and implementations use it heavily. Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error. This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator. It also adds up to runtime benefit because the bytecode instructions that do type checking are not generated.
Ans: Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.
Ans: Since we know that collection cannot store primitive types, only references. Before the introduction of autoboxing/unboxing in JDK5, if you wanted to strore primitive value like int in a collection, it had to be wrapped in an Integer class manually. While retrieving the value it had to be cast manually into its primitive type.
Collection still store only references but autoboxing/unboxing facilitate it to happen automatically, with no need to wrap it manually.
List<Integer> tempList = new ArrayList<Integer>();
// Storing in collection using autoboxing
tempList.add(1);
// wrapping primitive int 2 to Integer manually, with out autoboxing
tempList.add(new Integer(2));
Ans:
Ans: Both Hashtable and HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below
Ans: Another feature which was added to Collection with JDK 5 is for-each style loop. Any collection which wants to be the target of the "for-each loop" statement has to implement iterable interface.
Using for-each loop is easier than constructing the iterator to iterate over the collection and can be used in most of the cases rather than using the iterator loop.
If you have a list of Strings, that can be iterated using for-each loop like this.
for(String city : cityList){ System.out.println("Name " + city);}
Ans: Collection interface specifies group of Objects known as elements. How the elements are maintained is left up to the concrete implementations of Collection. For example, some Collection implementations like List allow duplicate elements whereas other implementations like Set don’t. A lot of the Collection implementations have a public clone method. However, it does’t really make sense to include it in all implementations of Collection. This is because Collection is an abstract representation. What matters is the implementation.
The semantics and the implications of either cloning or serializing come into play when dealing with the actual implementation; so concrete implementation should decide how it should be cloned or serialized, or even if it can be cloned or serialized.
So mandating cloning and serialization in all implementations is actually less flexible and more restrictive. The specific implementation should make the decision as to whether it can be cloned or serialized.
Ans: Diamond operator let the compiler infer the type arguments for the generic classes. It is added in Java 7.
As Example - Before JDK7 if we had to define a Map using String as both Key and Value we had to write it like this -
Map<String, String> cityMap = new HashMap<String, String>();
In Java SE 7, you can substitute the parameterized type of the constructor with an empty set of type parameters (<>) known as diamond operator
Map<String, String> cityMap = new HashMap<>();
Ans: Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the “group of elements” paradigm.
Q12. What are the changes in Collections framework in Java 8?
There are several changes in Collections Framework in Java 8 mostly influenced by the inclusion of Lambda expression in Java 8 -
Ans: At high level - Fail-fast is a property of a system or software with respect to
its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are
usually designed to stop normal operation rather than attempt to continue a possibly-flawed process.
When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production.
In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown.
It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
Ans: Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration.
Ans: Java 8 has added a functional style lopping to the Collections. Real advantage of this loop is when it is used on a stream with the chain of functional methods. If you have a Map<String, String> then it can be looped using ForEach statement like this -
Set<Map.Entry<String, String>> valueSet = cityMap.entrySet();
valueSet.forEach((a)->System.out.println("Key is " + a.getKey() + " Value is " + a.getValue()));
Ans: Enumeration is twice as fast as Iterator and uses very less memory. Enumeration is very basic and fits to basic needs. But Iterator is much safer as compared to Enumeration because it always denies other threads to modify the collection object which is being iterated by it.
Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection that is not possible with Enumeration. Iterator method names have been improved to make it’s functionality clear.
Ans: RandomAccess interface is a marker interface used by List implementations to indicate that they support fast (generally constant time) random access.
Note that using it with a sequential access list like LinkedList will result in taking more time to access a particular element.
Ans: The semantics are unclear, given that the contract for Iterator makes no guarantees about the order of iteration. Note, however, that ListIterator does provide an add operation, as it does guarantee the order of the iteration.
Ans: In Java.util package the classes that implement random access interface are - ArrayList, CopyOnWriteArrayList, Stack, Vector.
Ans: HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
Ans: It can be implemented on top of current Iterator interface but since it’s use will be rare, it doesn’t make sense to include it in the interface that everyone has to implement.
Ans: Collection is an interface which is the root of the Collections framework, as you can see in question#2, List, Set and Queue are the interfaces that extend the Collection interface.
Collections is a utility class with static methods that operate on or return Collections. It provides several methods like sort, reverse, synchronizedCollection, binarySearch etc.
Ans:We can use Iterator to traverse Set and List collections whereas ListIterator can be used with Lists only. Iterator can traverse in forward direction only whereas ListIterator can be used to traverse in both the directions.
ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
Ans: In the initial Collection classes like Vector, HashTable and Stack all the methods were synchronized to make these classes thread safe.
Later implementations starting from Java 1.2 were not synchronized.
Classes in java.util.concurrent package like ConcurrentHashMap, CopyOnWriteArrayList also provides thread safety but with a different implementation that doesn't require making all the methods synchronized.
Ans: We can iterate over a list in two different ways – using iterator and using for-each loop.
List<String> strList = new ArrayList<>();
//using for-each loop
for(String obj : strList){
System.out.println(obj);
}
//using iterator
Iterator<String> it = strList.iterator();
while(it.hasNext()){
String obj = it.next();
System.out.println(obj);
}
Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException.
Ans: Collections class has several static methods that return synchronized collections. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method.
public static <T> Collection<T> synchronizedCollection(Collection<T> c);
public static <T> Set<T> synchronizedSet(Set<T> s);
public static <T> List<T> synchronizedList(List<T> list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static <T> SortedSet<T> synchronizedSortedSet(SortedSet<T> s);
public static <K,V> SortedMap<K,V> synchronizedSortedMap(SortedMap<K,V> m);
Each of these methods returns a synchronized (thread-safe) Collection backed up by the specified collection.
Ans: The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
Ans: Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element. If there are any modifications found, it throws ConcurrentModificationException. All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
Ans: Collections class provides static method to make a Collection unmodifiable. Each of the six core collection interfaces -Collection, Set, List, Map, SortedSet, and SortedMap - has one static factory method.
public static <T> Collection<T> unmodifiableCollection(Collection<? extends T> c);public static <T> Set<T> unmodifiableSet(Set<? extends T> s);public static <T> List<T> unmodifiableList(List<? extends T> list);public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);public static <T> SortedSet<T> unmodifiableSortedSet(SortedSet<? extends T> s);public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);
Ans: Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection. By design, all the collection classes in package are fail-fast whereas collection classes in are fail-safe. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
Ans: Basic data structure used by ArrayList to store objects is an array of Object class, which is defined like -
transient Object[] elementData;
When we add an element to an ArrayList it first verifies whether it has that much capacity in the array to store new element or not, in case there is not then the new capacity is calculated which is 50% more than the old capacity and the array is increased by that much capacity (Actually uses Arrays.copyOf which returns the original array increased to the new length)
Ans: We can use concurrent collection classes to avoid while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.Check this post for ConcurrentHashMap Example.
Ans:
Ans: Iterator interface declare methods for iterating a collection but it’s implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has it’s own Iterator implementation nested class.
This allows collection classes to chose whether iterator is fail-fast or fail-safe. For example ArrayList iterator is fail-fast whereas CopyOnWriteArrayList iterator is fail-safe.
Ans: Yes. List allows duplicate elements to be added.
Ans: Unsupported Operation Exception is the exception used to indicate that the operation is not supported. It’s used extensively in JDK classes, in collections framework throws this exception for all and operations.
Ans: In ArrayList any number of nulls can be added.
Ans: Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have 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 and vice versa which is an additional step while sorting.
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. So clearly it should be used when you have a array available with you and you want to sort it.
Related Interview Questions...
Core Java Interview Questions And Answers
Core Java Programming Interview Questions and Answers
Multithreading in Java Interview Questions and Answers
Javascript Interview Questions
Java/J2EE Apps Integration Questions and Answers.
Java Interview Questions and Answers
Interview Questions For Selenium with Java
Java Web Services Interview Questions and Answers
Tricky Java Interview Questions and Answers