Está en la página 1de 19

Random Collection ArrayList LinkedList HashSet TreeSet HashMap TreeMap Vector Hashtable Properties Stack CopyOnWriteArrayList ConcurrentHashMap CopyOnWriteArraySet

Ordering Yes Yes No Yes No Yes Yes No No Yes Yes No No Access Yes No No No Yes Yes Yes Yes Yes No Yes Yes No

KeyValue No No No No Yes Yes No Yes Yes No No Yes No

Duplicate Elements Yes Yes No No No No Yes No No Yes Yes No No

Null Element Yes Yes Yes No Yes No Yes No No Yes Yes Yes Yes

Thread Safety No No No No No No Yes Yes Yes Yes Yes Yes Yes

What is java Collection Framework


Collection is an interface in the Java API. It provide a set of interface (Set, List, Queue, Map) and Classes(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc) that support operation on collections of objects. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.

Eg:- Say you have 5 balls, and you want to move them around easily. You get a bag and place
the 5 balls inside of it. The bag acts as a container. You can now move this bag around, and so quite easily the 5 balls move with it.

Benefits of Collections framework


Reduced development effort by using core collection classes rather than implementing our own collection classes. Code quality is enhanced with the use of well tested collections framework classes. Reduced effort for code maintenance by using collection classes shipped with JDK. Reusability and Interoperability

Why we use Set interface


Set is a unordered Collection that cannot contain duplicate. There are three general-purpose Set implementations: HashSet, TreeSet , LinkedHashSet

HashSet
This class implements the class interface, stores elements in the hash table. It makes no guarantees as to the iteration order of the set, in particular, it does not guarantee that the order will remain same over time. This permits the null element. HashSet is not synchronized. To Synchronize the HashSet SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

Example: public class ArrayListExample {

public static void main(String[] args) { Set<String> q = new HashSet<String>();

q.add("Rajesh"); q.add("Ajay");

q.add("Suresh"); q.add("Mohan"); q.add("Arun");

Iterator<String> itr = q.iterator(); while(itr.hasNext()) { System.out.println(itr.next()); } } }

Output: Suresh, Arun, Mohan, Ajay, Rajesh

TreeSet
TreeSet is a sorted set. All the elements are ordered by natural order. The elements must implement Comparable to be inserted into a TreeSet or alternatively the TreeSet must be created using a Comparator. TreeSet is not synchronized and the iterator returned by it is fail-fast. TreeSet is not synchronized

SortedSet s = Collections.synchronizedSortedSet(new TreeSet(...));

LinkedHashSet
LinkedHashSet extends HashSet. LinkedHashSet maintains the order of insertion and allows inserting null into it. LinkedHashSet is not synchronized and the iterator returned by it is failfast.

Collections.synchronizedSet(new LinkedHashSet(...));

HashSet vs TreeSet
Similarity Both HashSet and TreeSet implements java.util.Set interface which means they follow contract of Set interface and doesn't allow any duplicates. Both HashSet and TreeSet are not thread-safe and not synchronized. Though you can make them synchronized by usingCollections.synchronizedSet() method. Third similarity between TreeSet and HashSet is that, Iterator of both classes are fail-fast in nature. They will throwConcurrentModificationException if Iterator is modified once Iterator is created. this is not guaranteed and application code should not rely on this code but Java makes best effort to fail as soon as it detects structural change in underlying Set.

Difference First major difference between HashSet and TreeSet is performance. HashSet is faster than TreeSet and should be preferred choice if sorting of element is not required. Second difference between HashSet and TreeSet is that HashSet allows null object but TreeSet doesn't allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException Another significant difference between HashSet and TreeSet is that, HashSet is backed by HashMap while TreeSet is backed by TreeMap in Java. One more difference between HashSet and TreeSet which is worth remembering is that HashSet uses equals() method to compare two object in Set and for detecting duplicates while TreeSet uses compareTo() method for same purpose. if equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet Now most important difference between HashSet and TreeSet is ordering. HashSet doesn't guaranteed any order whileTreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java.

HashSet vs LinkedHashSet
The only difference is LinkedHashSet maintains the order of the item added to the set. It does It by maintaining double LinkedList Containing hash and original order of the items

LinkedHashSet vs TreeSet
TreeSet maintain natural order LinkedHashSet maintain the order inserted. TreeSet does not allow null, LinkedHashSet allow null.

Why we use List interface


List is a Ordered Collection that can contain duplicate. The main class implementing List interfaces are: ArrayList, LinkedList, Vector.

ArrayList
ArrayList implements the List interface. ArrayList maintains the order of insertion and allows inserting null into it. ArrayList is faster with random Access, Additional and removal is slower than LinkedList. . ArrayList is not synchronized.
Collections.synchronizedList(new ArrayList(...));

LinkedList
Linked list is an ordered collection where each element contains the data and the link to the next element. In Java LinkedList is implemented as doubly linked list. It contains the link to the next element as well as the link to the previous element. LinkedList implements List interface and it is not synchronized. LinkedList is not synchronized.

Collections.synchronizedList(new ArrayList(...));

ArrayList vs LinkedList
ArrayList is an index based data structure backed by Array, so it provides random access to its elements with performance as O(1) but LinkedList stores data as list of nodes where every node is linked to its previous and next node. So even though there is a method to get

the element using index, internally it traverse from start to reach at the index node and then return the element, so performance is O(n) that is slower than ArrayList. Insertion, addition or removal of an element is faster in LinkedList compared to ArrayList because there is no concept of resizing array or updating index when element is added in middle. LinkedList consumes more memory than ArrayList because every node in LinkedList stores reference of previous and next elements.

ArrayList vs Vector
Similarity
Both are index based and backed up by an array internally. Both maintains the order of insertion and we can get the elements in the order of insertion. The iterator implementations of ArrayList and Vector both are fail-fast by design. ArrayList and Vector both allows null values and random access to element using index number.

Difference
Vector is synchronized whereas ArrayList is not synchronized. However if you are looking for modification of list while iterating, you should use CopyOnWriteArrayList. ArrayList is faster than Vector because it doesnt have any overhead because of synchronization. ArrayList is more versatile because we can get synchronized list or read-only list from it easily using Collections utility class. By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

Set vs List
Set is unordered collection where List is ordered collection based on zero based index. List allow duplicate elements but Set does not allow duplicates. List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

Why we use Queue interface


The java.util.Queue interface is a subtype of the java.util.Collection interface. It represents an ordered list of objects just like a List, but its intended use is slightly different. A queue is designed to have elements inserted at the end of the queue, and elements removed from the beginning of the queue. Just like a queue in a supermarket. The main class implementing List interfaces are: LinkedList and PriorityQueue.

LinkedList
Same as LinkedList in list

PriorityQueue

Why we use Deque interface


The java.util.Deque interface is a subtype of the java.util.Queue interface. It represents a queue where you can insert and remove elements from both ends of the queue. Thus, "Deque" is short for "Double Ended Queue". The Deque interface is a richer abstract data type than both Stack and Queue because it implements both stacks and queues at the same time. The Dequeinterface, defines methods to access the elements at both ends of the Deque instance. Predefined classes like ArrayDeque and LinkedList implement the Deque interface. Deque interface can be used both as last-in-first-out stacks and first-in-first-out queues. The methods given in the Deque interface are divided into three parts:

Type of Operation Insert

First Element (Beginning of the Dequeinstance)


addFirst(e) offerFirst(e)

Last Element (End of the Dequeinstance)


addLast(e) offerLast(e)

removeFirst()

removeLast() pollLast() getLast() peekLast()

Remove

pollFirst() getFirst()

Examine

peekFirst()

ArrayDeque
Array deques have no capacity restrictions; they grow as necessary to support usage. They are not thread-safe; in the absence of external synchronization, they do not support concurrent access by multiple threads. Null elements are prohibited. This class is likely to be faster than Stack when used as a stack, and faster than LinkedList when used as a queue.

Why we use Map interface


A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Map interface includes methods for basic operations (such as put, get, remove, containsKey, containsValue, size, and empty) bulk operations (such as putAll and clear), and collection views (such as keySet, entrySet, and values). The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.

public class ArrayListExample { public static void main(String[] args) { Map<Integer, String> q = new HashMap<Integer, String>(); q.put(1, "Rajesh"); q.put(2, "Ajay"); q.put(3, "Suresh"); q.put(4, "Mohan"); q.put(null, null); q.put(null, null); q.put(5, "Arun");

Iterator<Integer> itr = q.keySet().iterator(); while(itr.hasNext()) { Integer key = itr.next(); System.out.println("Key: " + key + " value: " + q.get(key)); } } }

Why we use SortedSet interface


A SortedSet is a Set that maintains its elements in ascending order, sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet.

Why we use SortedMap interface


A SortedMap is a Map that maintains its entries in ascending order, sorted according to the keys' natural ordering, or according to a Comparator provided at the time of the SortedMap creation.

Why Collection interface does not extend Cloneable and Serializable interface?
Well, simplest answer is there is no need to do it. Extending an interface simply means that you are creating a subtype of interface, in other words a more specialized behavior and Collection interface is not expected to do what Cloneable and Serializable interfaces do. Another reason is that not everybody will have a reason to have Cloneable collection because if it has very large data, then every unnecessary clone operation will consume a big memory. Beginners might use it without knowing the consequences. Another reason is that Cloneable and Serializable are very specialized behavior and so should be implemented only when required. For example, many concrete classes in collection implement these interfaces. So if you want this feature. use these collection classes otherwise use their alternative classes.

Why Map interface does not extend Collection interface?


A good answer to this interview question is because they are incompatible. Collection has a method add(Object o). Map can not have such method because it need key-value pair. There are

other reasons also such as Map supports keySet, valueSet etc. Collection classes does not have such views. Due to such big differences, Collection interface was not used in Map interface, and it was build in separate hierarchy.

How to convert an array of String to arraylist


1. public class StringArrayTest 2. { 3. public static void main(String[] args) 4. { 5. String[] words = {"ace", "boom", "crew", "dog", "eon"}; 6. 7. List<String> wordList = Arrays.asList(words); 8. 9. for (String e : wordList) 10. { 11. System.out.println(e); 12. } 13. } 14. }

How to sort list in reverse order?


List reversedList = Collections.reverse(list);

Can a null element added to a TreeSet or HashSet?


HashSet allow Null Key. Since it belong set interface it allow only one null key. TreeSet does not allow Null key. Since it use NavigableMap for sorting the elements. NavigableMap is a subtype of sortedMap which does not allow null key. So TreeSet does not allow null key. It will throw NullPointerException if we try to insert null key.

ConcurrentHashMap
ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package. Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, than, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you

have better choice; because, not only it can be safely used in concurrent multi-threaded environment but also provides better performance over Hashtable and synchronizedMap. ConcurrentHashMap performs better than earlier two because it only locks a portion of Map, instead of whole Map, which is the case with Hashtable and synchronized Map. CHM allows concurred read operations and same time, maintains integrity by synchronizing write operations.

How ConcurrentHashMap is implemented in Java


ConcurrentHashMap is introduced as an alternative of Hashtable and provided all functions supported by Hashtable with additional feature called "concurrency level", which allows ConcurrentHashMap to partition Map. ConcurrentHashMap allows multiple readers to read concurrently without any blocking. This is achieved by partitioning Map into different parts based on concurrency level and locking only a portion of Map during updates. Default concurrency level is 16, and accordingly Map is divided into 16 part and each part is governed with different lock. This means, 16 thread can operate on Map simultaneously, until they are operating on different part of Map. This makes ConcurrentHashMap high performance despite keeping thread-safety intact. Though, it comes with caveat. Since update operations like put(), remove(), putAll() or clear() is not synchronized, concurrent retrieval may not reflect most recent change on Map. In case of putAll() or clear(), which operates on whole Map, concurrent read may reflect insertion and removal of only some entries. Another important point to remember is iteration over CHM, Iterator returned by keySet of ConcurrentHashMap are weekly consistent and they only reflect state of ConcurrentHashMap and certain point and may not reflect any recent change. Iterator of ConcurrentHashMap's keySet area also fail-safe and doesnt throw ConcurrentModificationExceptoin.. Default concurrency level is 16 and can be changed, by providing a number which make sense and work for you while creating ConcurrentHashMap. Since concurrency level is used for internal sizing and indicate number of concurrent update without contention, so, if you just have few writers or thread to update Map keeping it low is much better. ConcurrentHashMap also uses Reentrant Lock to internally lock its segments.

Summary
ConcurrentHashMap allows concurrent read and thread-safe update operation. During update operation, ConcurrentHashMap only lock a portion of Map instead of whole Map. Concurrent update is achieved by internally dividing Map into small portion which is defined by concurrency level. Choose concurrency level carefully as a significant higher number can be waste of time and space and lower number may introduce thread contention in case writers over number concurrency level. All operations of ConcurrentHashMap are thread-safe. Since ConcurrentHashMap implementation doesn't lock whole Map, there is chance of read overlapping with update operations like put() and remove(). In that case result returned by get() method will reflect most recently completed operation from there start. Iterator returned by ConcurrentHashMap is weekly consistent, fail safe and never throw ConcurrentModificationException. In Java. ConcurrentHashMap doesn't allow null as key or value.

You can use ConcurrentHashMap in place of Hashtable but with caution as CHM doesn't lock whole Map.

Difference between HashMap and ConcurrentHashMap


ConcurrentHashMap is thread-safe, while the HashMap is not. ConcurrentHashMap does not allow null key, while HashMap allow null key. ConcurrentHashMap has Lock Mechanism, while HashMap does not have Lock Mechanism

Difference between HashMap and Collections.synchronizedMap


HashMap is non-synchronized, while Collections.synchronizedMap is synchronized

Difference between ConcurrentHashMap and Collections.synchronizedMap


Both are synchronized but differ with their core functionality

Collections.synchronizedMap is fully locked, that mean if multiple thread try to access the synchronizedMap at same time, they will be allowed to get/put key-value pairs one at a time in synchronized manner. ConcurrentHashMap is consist of internal segments which can be viewed as independent HashMaps, conceptually. All such segments can be locked by separate threads in high concurrent executions. In this way, multiple threads can get/put key-value pairs from ConcurrentHashMap without blocking/waiting for each other.

Difference between HashMap and HashTable


The major difference is that HashTable is synchronized and HashMap is not. If asked for other reasons, tell them, HashTable is legacy class (part of JDK 1.0) which was promoted into collections framework by implementing Map interface later. It still has some extra features like Enumerator with it, which HashMap lacks. Another minor reason can be: HashMap supports null key (mapped to zero bucket), HashTable does not support null keys and throws NullPointerException on such attempt.

Difference between Set and List?


Set is unordered collection where List is ordered collection based on zero based index. List allow duplicate elements but Set does not allow duplicates. List does not prevent inserting null elements (as many you like), but Set will allow only one null element.

Difference between List and Map?


List is collection of elements where as map is collection of key-value pairs

Difference between HashMap and HashTable?


Hashtable is synchronized, whereas HashMap is not. Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not.

Difference between Vector and ArrayList?

All the methods of Vector is synchronized. But, the methods of ArrayList is not synchronized. Vector is a Legacy class added in first release of JDK. ArrayList was part of JDK 1.2, when collection framework was introduced in java. By default, Vector doubles the size of its array when it is re-sized internally. But, ArrayList increases by half of its size when it is re-sized.

Difference between Iterator and Enumeration?


Iterators allow the caller to remove elements from the underlying collection during the iteration with its remove() method. You can not add/remove elements from a collection when using enumerator. Enumeration is available in legacy classes i.e Vector/Stack etc. whereas Iterator is available in all modern collection classes. Another minor difference is that Iterator has improved method names e.g. Enumeration.hasMoreElement() has become Iterator.hasNext(), Enumeration.nextElement() has become Iterator.next() etc.

Difference between HashMap and HashSet?


HashMap is collection of key-value pairs whereas HashSet is un-ordered collection of unique elements. Thats it. No need to describe further.

Difference between Iterator and ListIterator?


We can use Iterator to traverse Set and List and also Map type of Objects. But List Iterator can be used to traverse for List type Objects, but not for Set type of Objects. By using Iterator we can retrieve the elements from Collection Object in forward direction only whereas List Iterator, which allows you to traverse in either directions using hasPrevious() and previous() methods. ListIterator allows you modify the list using add() remove() methods. Using Iterator you can not add, only remove the elements.

Difference between TreeSet and SortedSet?


SortedSet is an interface which TreeSet implements. That it !!

Difference between ArrayList and LinkedList?


LinkedList store elements within a doubly-linked list data structure. ArrayList store elements within a dynamically resizing array. LinkedList allows for constant-time insertions or removals, but only sequential access of elements. In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list. ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap. LinkedList has more memory overhead than ArrayList because in ArrayList each index only holds actual object (data) but in case of LinkedList each node holds both data and address of next and previous node.

How to make a collection thread safe?


Collections.synchronizedList(list); Collections.synchronizedSet(set); Collections.synchronizedMap(map);

What do you understand by iterator fail-fast property?


Fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. Fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.

What is difference between fail-fast, fail-stolerant and fail-safe?


You have understood fail-fast in previous question. Fail-safe iterators are just opposite to failfast. 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 thats why they are called as fail-safe iterator.

Fail-tolerant property allows to system to continue in case failures rather than completely stopping the system. 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.

How to avoid ConcurrentModificationException while iterating a collection?


You should first try to find another alternative iterator which are fail-safe. For example if you are using List and you can use ListIterator. If it is legacy collection, you can use enumeration. If above options are not possible then you can use one of three changes: If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach. You can convert the list to an array and then iterate on the array. You can lock the list while iterating by putting it in a synchronized block.

What is UnsupportedOperationException?
This exception is thrown on invoked methods which are not supported by actual collection type. For example, if you make a read-only list list using Collections.unmodifiableList(list) and then call add() or remove() method, what should happen. It should clearly throw UnsupportedOperationException.

Which collection classes provide random access of it elements


ArrayList, HashMap, TreeMap, Hashtable classes provide random access to it elements.

What is BlockingQueue?
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.

What is Queue and Stack, list down their differences?


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. Usage: 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.

What is Comparable and Comparator interface?


Comparable defines the natural order of the objects but Comparator provides way to define multiple algorithms to order the objects. Comparable objects need to implement compareTo() method but Comparator classes need to implement compare() method. Implementing Comparable interface needs a code change of the existing class but Implementing Comparator does not need to change the existing code and instead a new class needs to create. Comparable is useful when only one short order is required for the legacy classes but Comparator is useful when one or many short orders are required for the third party classes.

What are Collections and Arrays classes?


Collections and Arrays classes are special utility classes to support collection framework core classes. They provide utility functions to get read-only/ synchronized collections, sort the collection on various ways etc.

Arrays also helps array of objects to convert in collection objects. Arrays also have some functions which helps in copying or working in part of array objects.

Which is a better choice in terms of Insertion and Iteration between List and Set?
In terms of Insertion List is faster than Set because List can directly add an element at the end but Set needs to perform a sequential check for a duplication before adding. This duplication checking makes Set slower than List. In terms of Iteration List is faster because it supports indexed access

Which is a better choice in terms of Insertion and Iteration between ArrayList and HashSet?
In terms of Insertion ArrayList is faster than HashSet because ArrayList can directly add an element at the end but HashSet needs to perform a sequential check inside the bucket for a duplication before adding. This duplication checking makes HashSet slower than ArrayList. In terms of Iteration ArrayList is faster because it implements RandomAccess (a marker interface) and supports direct index based access.

Which is a better choice in terms of Insertion and Iteration between ArrayList and TreeSet?
In terms of insertion and iteration ArrayList is a better choice over TreeSet.

More interview Question at


http://javaadmin.com/interview-questions/java-collections-frameworkinterview-questions/5/

También podría gustarte