Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
Null Element Yes Yes Yes No Yes No Yes No No Yes Yes Yes Yes
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.
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(...));
q.add("Rajesh"); q.add("Ajay");
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
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.
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.
LinkedList
Same as LinkedList in list
PriorityQueue
removeFirst()
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.
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 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.
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.
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.
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.
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.
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.
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.
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.
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.
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.