Collections in Java – 13 Things You MUST Know

Filed Under: Java
Java Collections

Java Collections Framework is one of the core parts of the Java programming language. Collections are used in almost every programming language. Most of the programming languages support various type of collections such as List, Set, Queue, Stack, etc.

Collections in Java

1. What is Java Collections Framework?

Collections are like containers that group multiple items in a single unit. For example, a jar of chocolates, list of names, etc.

Collections are used in every programming language and when Java arrived, it also came with few Collection classes – Vector, Stack, Hashtable, Array.

Java 1.2 provided Collections Framework that is the architecture to represent and manipulate Collections in java in a standard way. Java Collections Framework consists of the following parts:

  • Interfaces: Java Collections Framework interfaces provides the abstract data type to represent collection. java.util.Collection is the root interface of Collections Framework. It is on the top of Collections framework hierarchy. It contains some important methods such as size(), iterator(), add(), remove(), clear() that every Collection class must implement.

    Some other important interfaces are java.util.List, java.util.Set, java.util.Queue and java.util.Map.

    The Map is the only interface that doesn’t inherit from Collection interface but it’s part of the Collections framework. All the collections framework interfaces are present in java.util package.

  • Implementation Classes: Java Collections framework provides core implementation classes for collections. We can use them to create different types of collections in java program.

    Some important collection classes are ArrayList, LinkedList, HashMap, TreeMap, HashSet, TreeSet.

    These classes solve most of our programming needs but if we need some special collection class, we can extend them to create our custom collection class.

    Java 1.5 came up with thread-safe collection classes that allowed to modify Collections while iterating over it. Some of them are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

    These classes are in java.util.concurrent package. All the collection classes are present in java.util and java.util.concurrent package.

  • Algorithms: Algorithms are useful methods to provide some common functionalities, for example searching, sorting and shuffling.

Below class diagram shows Collections Framework hierarchy. For simplicity, I have included only commonly used interfaces and classes.

Collections in Java, java Collections Framework

2. Benefits of Java Collections Framework

Java Collections framework have following benefits:

  • Reduced Development Effort – It comes with almost all common types of collections and useful methods to iterate and manipulate the data. So we can concentrate more on business logic rather than designing our collection APIs.
  • Increased Quality – Using core collection classes that are well tested increases our program quality rather than using any home developed data structure.
  • Reusability and Interoperability
  • Reduce effort – to learn any new API if we use core collection API classes.

3. Java Collections Interfaces

Java collection interfaces are the foundation of the Java Collections Framework. Note that all the core collection interfaces are generic; for example public interface Collection<E>. The <E> syntax is for Generics and when we declare Collection, we should use it to specify the type of Object it can contain. It helps in reducing run-time errors by type-checking the Objects at compile-time.

To keep the number of core collection interfaces manageable, the Java platform doesn’t provide separate interfaces for each variant of each collection type. If an unsupported operation is invoked, a collection implementation throws an UnsupportedOperationException.

3.1) Collection Interface

This is the root of the collection hierarchy. A collection represents a group of objects known as its elements. The Java platform doesn’t provide any direct implementations of this interface.

The interface has methods to tell you how many elements are in the collection (size, isEmpty), to check whether a given object is in the collection (contains), to add and remove an element from the collection (add, remove), and to provide an iterator over the collection (iterator).

Collection interface also provides bulk operations methods that work on entire collection – containsAll, addAll, removeAll, retainAll, clear.

The toArray methods are provided as a bridge between collections and older APIs that expect arrays on input.

3.2) Iterator Interface

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. Iterators in collection classes implement Iterator Design Pattern.

3.3) Set Interface

Set is a collection that cannot contain duplicate elements. This interface models the mathematical set abstraction and is used to represent sets, such as the deck of cards.

The Java platform contains three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet. Set interface doesn’t allow random-access to an element in the Collection. You can use iterator or foreach loop to traverse the elements of a Set.

3.4) List Interface

List is an ordered collection and can contain duplicate elements. You can access any element from its index. List is more like array with dynamic length. List is one of the most used Collection type. ArrayList and LinkedList are implementation classes of List interface.

List interface provides useful methods to add an element at a specific index, remove/replace element based on the index and to get a sub-list using the index.


List strList = new ArrayList<>();

//add at last
strList.add(0, "0");

//add at specified index
strList.add(1, "1");

//replace
strList.set(1, "2");

//remove
strList.remove("1");

Collections class provide some useful algorithm for List – sort, shuffle, reverse, binarySearch etc.

3.5) Queue Interface

Queue is a collection used to hold multiple elements prior to processing. Besides basic Collection operations, a Queue provides additional insertion, extraction, and inspection operations.

Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner. Among the exceptions are priority queues, which order elements according to a supplied comparator or the elements’ natural ordering. Whatever the ordering used, the head of the queue is the element that would be removed by a call to remove or poll. In a FIFO queue, all new elements are inserted at the tail of the queue.

3.6) Dequeue Interface

A linear collection that supports element insertion and removal at both ends. The name deque is short for “double-ended queue” and is usually pronounced “deck”. Most Deque implementations place no fixed limits on the number of elements they may contain, but this interface supports capacity-restricted deques as well as those with no fixed size limit.

This interface defines methods to access the elements at both ends of the deque. Methods are provided to insert, remove, and examine the element.

3.7) Map Interface

Java Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

The Java platform contains three general-purpose Map implementations: HashMap, TreeMap, and LinkedHashMap.

The basic operations of Map are put, get, containsKey, containsValue, size, and isEmpty.

3.8) ListIterator Interface

An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator’s current position in the list.

Java 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().

3.9) SortedSet Interface

SortedSet is a Set that maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. Sorted sets are used for naturally ordered sets, such as word lists and membership rolls.

3.10) SortedMap Interface

Map that maintains its mappings in ascending key order. This is the Map analog of SortedSet. Sorted maps are used for naturally ordered collections of key/value pairs, such as dictionaries and telephone directories.

4. Java Collections Classes

Java Collections framework comes with many implementation classes for the interfaces. Most common implementations are ArrayList, HashMap and HashSet. Java 1.5 included Concurrent implementations; for example ConcurrentHashMap and CopyOnWriteArrayList. Usually Collection classes are not thread-safe and their iterator is fail-fast. In this section, we will learn about commonly used collection classes.

4.1) HashSet Class

Java HashSet is the basic implementation the Set interface that is backed by a HashMap. It makes no guarantees for iteration order of the set and permits the null element.

This class offers constant time performance for basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. We can set the initial capacity and load factor for this collection. The load factor is a measure of how full the hash map is allowed to get before its capacity is automatically increased.

4.2) TreeSet Class

A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.

Refer: Java Comparable Comparator

This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).

Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal.

4.3) ArrayList Class

Java ArrayList is the resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

The size, isEmpty, get, set, iterator, and list iterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

Further reading: Java ArrayList and Iterator

4.4) LinkedList Class

Doubly-linked list implementation of the List and Deque interfaces. Implements all optional list operations, and permits all elements (including null).

All of the operations perform as expected for a doubly-linked list. Operations that index into the list will traverse the list from the start or the end, whichever is closer to the specified index.

4.5) HashMap Class

Hash table based implementation of the Map interface. This implementation provides all of the optional map operations and permits null values and the null key. HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits null. This class makes no guarantees for the order of the map.

This implementation provides constant-time performance for the basic operations (get and put). It provides constructors to set initial capacity and load factor for the collection.

Further Read: HashMap vs ConcurrentHashMap

4.6) TreeMap Class

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

This implementation provides guaranteed log(n) time cost for the containsKey, get, put and remove operations. Algorithms are adaptations of those in Cormen, Leiserson, and Rivest’s Introduction to Algorithms.

Note that the ordering maintained by a TreeMap, like any sorted map, and whether or not an explicit comparator is provided, must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a sorted map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

4.7) PriorityQueue Class

Queue processes its elements in FIFO order but sometimes we want elements to be processed based on their priority. We can use PriorityQueue in this case and we need to provide a Comparator implementation while instantiation the PriorityQueue. PriorityQueue doesn’t allow null values and it’s unbounded. For more details about this, please head over to Java Priority Queue where you can check its usage with a sample program.

5. Collections class

Java Collections class consists exclusively of static methods that operate on or return collections. It contains polymorphic algorithms that operate on collections, “wrappers”, which return a new collection backed by a specified collection, and a few other odds and ends.

This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse etc.

6. Synchronized Wrappers

The synchronization wrappers add automatic synchronization (thread-safety) to an arbitrary collection. Each of the six core collection interfaces — Collection, Set, List, Map, SortedSet, and SortedMap — has one static factory method.


public static  Collection synchronizedCollection(Collection c);
public static  Set synchronizedSet(Set s);
public static  List synchronizedList(List list);
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> m);
public static  SortedSet synchronizedSortedSet(SortedSet 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.

7. Unmodifiable wrappers

Unmodifiable wrappers take away the ability to modify the collection by intercepting all the operations that would modify the collection and throwing an UnsupportedOperationException. Its main usage are;

  • To make a collection immutable once it has been built. In this case, it’s good practice not to maintain a reference to the backing collection. This absolutely guarantees immutability.
  • To allow certain clients read-only access to your data structures. You keep a reference to the backing collection but hand out a reference to the wrapper. In this way, clients can look but not modify, while you maintain full access.

These methods are;


public static  Collection unmodifiableCollection(Collection<? extends T> c);
public static  Set unmodifiableSet(Set<? extends T> s);
public static  List unmodifiableList(List<? extends T> list);
public static <K,V> Map<K, V> unmodifiableMap(Map<? extends K, ? extends V> m);
public static  SortedSet unmodifiableSortedSet(SortedSet<? extends T> s);
public static <K,V> SortedMap<K, V> unmodifiableSortedMap(SortedMap<K, ? extends V> m);

8. Thread Safe Collections

Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design iterator is fail-fast and throws ConcurrentModificationException. Some of these classes are CopyOnWriteArrayList, ConcurrentHashMap, CopyOnWriteArraySet.

Read these posts to learn about them in more detail.

9. Collections API Algorithms

Java Collections Framework provides algorithm implementations that are commonly used such as sorting and searching. Collections class contain these method implementations. Most of these algorithms work on List but some of them are applicable for all kinds of collections.

9.1) Sorting

The sort algorithm reorders a List so that its elements are in ascending order according to an ordering relationship. Two forms of the operation are provided. The simple form takes a List and sorts it according to its elements’ natural ordering. The second form of the sort takes a Comparator in addition to a List and sorts the elements with the Comparator.

9.2) Shuffling

The shuffle algorithm destroys any trace of order that may have been present in a List. That is, this algorithm reorders the List based on input from a source of randomness such that all possible permutations occur with equal likelihood, assuming a fair source of randomness. This algorithm is useful in implementing games of chance.

9.3) Searching

The binarySearch algorithm searches for a specified element in a sorted list. This algorithm has two forms. The first takes a List and an element to search for (the “search key”).

This form assumes that the list is sorted in ascending order according to the natural ordering of its elements.

The second form takes a Comparator in addition to the List and the search key and assumes that the list is sorted into ascending order according to the specified Comparator.

The sort algorithm can be used to sort the List prior to calling binarySearch.

9.4) Composition

The frequency and disjoint algorithms test some aspect of the composition of one or more Collections.

  • frequency: counts the number of times the specified element occurs in the specified collection
  • disjoint: determines whether two Collections are disjoint; that is, whether they contain no elements in common

9.5) Min and Max values

The min and the max algorithms return, respectively, the minimum and maximum element contained in a specified Collection. Both of these operations come in two forms. The simple form takes only a Collection and returns the minimum (or maximum) element according to the elements’ natural ordering.
The second form takes a Comparator in addition to the Collection and returns the minimum (or maximum) element according to the specified Comparator.

10. Java 8 Collections API Features

Java 8 biggest changes are related to Collection APIs. Some of the important changes and improvements are:

  1. Introduction of Stream API for sequential as well as parallel processing, you should read Java Stream API Tutorial for more details.
  2. Iterable interface has been extended with forEach() default method for iterating over a collection.
  3. Lambda Expression and Functional interfaces are mostly beneficial with Collection API classes.

11. Java 10 Collections API Changes

  1. List.copyOf, Set.copyOf, and Map.copyOf methods to create unmodifiable collections.
  2. Collectors class gets various methods for collecting unmodifiable collections (Set, List, Map). These method names are toUnmodifiableList, toUnmodifiableSet, and toUnmodifiableMap.

Let’s look at an example of these new Java 10 Collections API methods usage.


package com.journaldev.collections;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class JDK10CollectionFunctions {

	public static void main(String[] args) {

		// 1. List, Set, Map copyOf(Collection) method
		List<String> actors = new ArrayList<>();

		actors.add("Jack Nicholson");
		actors.add("Marlon Brando");

		System.out.println(actors);
		// prints [Jack Nicholson, Marlon Brando]

		// New API added - Creates an UnModifiable List from a List.
		List<String> copyOfActors = List.copyOf(actors);

		System.out.println(copyOfActors);
		// prints [Jack Nicholson, Marlon Brando]

		// copyOfActors.add("Robert De Niro"); Will generate
		// UnsupportedOperationException

		actors.add("Robert De Niro");

		System.out.println(actors);
		// prints [Jack Nicholson, Marlon Brando, Robert De Niro]

		System.out.println(copyOfActors);
		// prints [Jack Nicholson, Marlon Brando]

		// 2. Collectors class toUnmodifiableList, toUnmodifiableSet, and
		// toUnmodifiableMap methods
		List<String> collect = actors.stream().collect(Collectors.toUnmodifiableList());
		System.out.println(collect);
	}

}

12. Java 11 Collections API Changes

A new default method toArray(IntFunction<T[]> generator) added in the Collection interface. This method returns an array containing all of the elements in this collection, using the provided generator function to allocate the returned array.


package com.journaldev.collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class JDK11CollectionFunctions {

	public static void main(String[] args) {

		/*
		 * JDK 11 New Method in Collection interface 
		 * default <T> T[] toArray(IntFunction<T[]> generator) {
		 * return toArray(generator.apply(0)); }
		 */

		List<String> strList = new ArrayList<>();
		strList.add("Java");
		strList.add("Python");
		strList.add("Android");

		String[] strArray = strList.toArray(size -> new String[size]);
		System.out.println(Arrays.toString(strArray));

		strArray = strList.toArray(size -> new String[size + 5]);
		System.out.println(Arrays.toString(strArray));

		strArray = strList.toArray(size -> new String[size * 3]);
		System.out.println(Arrays.toString(strArray));
	}

}

Output:


[Java, Python, Android]
[Java, Python, Android, null, null]
[Java, Python, Android]

13. Collection classes in a Nutshell

Below table provides basic details of commonly used collection classes.

Download URL: Java Collection Classes

Collection Ordering Random Access Key-Value Duplicate Elements Null Element Thread Safety
ArrayList
LinkedList
HashSet
TreeSet
HashMap
TreeMap
Vector
Hashtable
Properties
Stack
CopyOnWriteArrayList
ConcurrentHashMap
CopyOnWriteArraySet

I hope this tutorial explains most of the topics in java collections framework, please share your opinion with comments.

Reference: Oracle Documentation

Comments

  1. Ulrich says:

    Excellent, amazing, …… Many thanks

  2. Nikita Ramdas Alai says:

    I have made a video on collections in Java

    https://www.youtube.com/channel/UCftcGRuKOh-DmgK9jpgANzg

  3. Jitendra Bahadur Chand says:

    I subscribed but can’t see the ebook in my email box

  4. Tuğberk says:

    good job, very informative, deep knowledge, thanks.

  5. chetan sharma says:

    TreeMap doesnot implement Random Access

  6. Fantine says:

    I subscribed but can’t see the ebook in my email box

  7. Subhash says:

    LinkedHashMap is missing the collection table

  8. hooni says:

    thank you very much.
    this helped me a lot (learning java now).

    Thank you!! :))

  9. ilhom says:

    hi,

    I found a mistake on your DEsign Pattern book in example in Chain of Responsibility Pattern,
    can u please check that program there s smth wrong with it, it is printing Null Pointer Exception,

    thanks.

  10. sakshi says:

    Treemap contain null values.you have written wrong i think.

  11. zabir says:

    RendomAccess Interface implemented class is ArrayList, AttributeList, CopyOnWriteArrayList, RoleList, RoleUnresolvedList, Stack, Vector

    Source:: RandomAccess API Doc

  12. amol says:

    Hi Pankaj ! This is an amazing tutorial. I am a fan or your work. I have read this article in text mode. Just like any text read without fancy css and ads. Can you please give me that link.

    1. Pankaj says:

      I didn’t get what you meant.

    2. Rahul S Kumar says:

      Amol….. Reading mode is a feature of your browser. Firefox is having that feature. I don’t know if other browsers having that feature or not (Might be having).

  13. Anurag Singh says:

    Hello sir

    this is very well explained about java collection framework.
    keep posting like that
    thank you so much this useful post

  14. Chandra Babu says:

    Why CopyOnWriteArraylist is not random access?

    From the source code
    public class CopyOnWriteArrayList
    implements List, RandomAccess, Cloneable, java.io.Serializable {

    1. Chandra Babu says:

      Sorry Overlooked CopyonWriteArraySet

  15. Dev says:

    Hi Admin,

    I need little more information regarding object equals() and hashcode() method.
    In java equals() and hashcode() method are very important. I want to know the cases where these two method are call internally in java.
    For example :
    1. get() method in HashMap.
    2.Set
    3.contains() method in ArrayList calls equals method internally.

    Can anyone please tell me what is the other cases where equals() method (or hashcode()) calls internally to perform any operation (like above mention 3 cases).

    1. Pankaj says:

      I think they are used in String too.

  16. Keval Solanki says:

    It would be nice if you add here some programmes too….theory only is not at all sufficient..

  17. ch sreelekha says:

    can u please provide more programs that users can easily understand pratically also…….

  18. Arjun Sridhar says:

    Corrections:

    HashSet Internally uses HashMap not HashTable. Author can you please rectify we are all observing your site keenly..

    1. Pankaj says:

      Sorry for typo error and Thanks a lot for pointing it out. I have corrected the post.

      1. sivaaprasad says:

        But it is given in java docs that hashset uses hashtable to store elements.

        could u pls justify ur answer

  19. Satya Chandu says:

    Pretty good coverage. Good Job !!!

  20. kamlesh says:

    nice……………tutorials for helpful all Student

  21. aparna says:

    hi pankaj,

    can u please put all the data topic wise on this website in downlodable PDF format.

  22. Rajan Chauhan says:

    theoretically its very understandable………..but could it be presented with examples of each ?……classes implementing these interfaces.. that will be more understandable.

  23. Contra says:

    Wonderful post!, it was worth spending every sec reading your blog.

  24. Sekhar says:

    Hi,

    I faced one question in interview that is “Which collection frame work object is used in your project, I replied that I was using HashMap because of synchronisation”

    He asked is this only the main advantage of hashmap?. But i was in silent for that question.

    Please provide the proper solution for these type of questions>

    Thanks in Advance,
    Sekhar

    1. Pankaj says:

      You can’t read everything, some things come from experience. There are no limits on interview questions, that being said there is no way anyone can address all of them.

      1. manjunath says:

        I’m following your blog from past 5 months it’s was too much good , I have a doubt why all methods in Collections class are static methods , please provide your powerful answer. Thanks in advance

        1. Pankaj says:

          Collections is a utility class that provides useful methods, that’s why all the methods are made static. There is no point in making those methods non-static, that will result in create an object of it and then calling the method.

          1. manjunath says:

            Thank you very much sir,According to my analogy ” this “(operator) is a static reffereence which is created by JVM and supplies to each and every java program at run time and also internally “this” operator is following dynamic bynding(runtime polymorphism)
            static x this; ——this stmt is created by jvm inside the class
            x obj=new x(); —-programmer statement

            next duty of jvm: this=obj1; ,,,,,,,and so on in a class

    2. bhaskar says:

      Interviewer tricked you, as HashMap is not synchronized. If you are using HashMap and you want it to be thread safe, then you have to provide synchronization mechanism.

    3. Siva Narayana Reddy M says:

      Hi Sekhar,

      Whether you already know it or not, I just want to put forth some piece of information which I know.

      HashMap is a concrete implementation of Map interface.
      HashMap is NOT synchronized.
      HashTable is another concrete implementation of Map interface.
      HashTable is SYNCHRONIZED.

      Thanks
      Siva Narayana Reddy M

  25. Vaibhav says:

    hi pankaj,

    you explained it very impressively.. Start with list if topic then explanation of it.. its very easy to read n your explanations are easy to understand too..:-)
    just a request..plz give simple..small example for it..

    thanks..:-)

  26. Urmila says:

    Very Good Explanation but can u give small practical example on Collections Framework

  27. JJ_Jacob says:

    good article

  28. Partha says:

    Hi Pankaj,

    As you said Random access NO for LinkedList and YES for ArrayList. Could you elaborate more on this, what random access mean?
    Does it mean retrieving the object from a list/map? I can see there is a get() in both the ArrayList and LinkedList class. Using this method we can retrieve the object. Does it mean random access?

    Thanks
    Partha

    1. Pankaj says:

      LinkedList supports get(int index) operation but internally it traverses the list from start or end which ever is closer depending on the length. So it’s not efficient and not random.

      Random access means that whether you get the element at index 1 or at index 10000 of 50000 elements, it should take same time but for LinkedList it will take more time because it will have to skip first 9999 elements to get the desired element.

      ArrayList supports random access, means whether you are accessing index 1 or 10000 of 50000 elements, time to get the element will be same.

      If you look at the implementation of ArrayList and LinkedList, you will see that ArrayList implements RandomAccess interface whereas LinkedList does not.

      1. Partha says:

        As per my understanding, In ArrayList if an element is removed then the arrayList is resized. But Linked list works on the principle of Node. So if any element is removed in LinkedList it is not resized.

        Lets say in element 10 is removed so element 11 will take the place of 10 in ArrayList. But in Linked list element 10 place is blank. So we can’t access element 10 if we are using LinkedList.

        Is that the reason LinkedList doesn’t allow Random Access?

  29. jagjeet singh says:

    great Work…easily understand all things in collection framework.and how it work in java.

  30. shirisha says:

    Thanq Pankaj ,Perfectly explained .

  31. Nihar says:

    Amazing …. love to read ur blog.

  32. Abhay Singh says:

    Hi Pankaj..
    I think ConcurrentHashMap does not allow null values.. but you have mention YES in the table..

    The main reason that nulls aren’t allowed in ConcurrentMaps (ConcurrentHashMaps, ConcurrentSkipListMaps) is that ambiguities that may be just barely tolerable in non-concurrent maps can’t be accommodated. The main one is that if map.get(key) returns null, you can’t detect whether the key explicitly maps to null vs the key isn’t mapped. In a non-concurrent map, you can check this via map.contains(key), but in a concurrent one, the map might have changed between calls.

    1. Pankaj says:

      Hi Abhay,

      Thanks for pointing out the mistake and providing the explanation. I have corrected it.

      1. Abdul Rajak Shaik says:

        Please correct it on downloadable PDF file too

  33. dg says:

    Hey! I’m at work browsing your blog from my new apple iphone!

    Just wanted to say I love reading your blog and look forward to all your posts!
    Keep up the excellent work!

  34. Snehal Masne says:

    I think this is among the most significant articles I have seen.
    And I’m glad reading your article.

    Good job, cheers! 🙂

  35. Madiraju Krishna Chaitanya says:

    Hi Pankaj Sir,
    Wonderful Post.We got a Good Understanding of the Collections Framework from this writeup.Please keep up the Good Work and keep posting wonderful articles like this.May GOD Bless You.

  36. satish says:

    thks i learn some thing from here

  37. выкройки одежды для собaк журнaл says:

    Very good write-up. I definitely appreciate this site. Keep it up!

  38. anonymous says:

    It’s hard to find well-informed people about this topic, however, you sound like you know what you’re talking about!
    Thanks

  39. homepage says:

    Hello my friend! I want to say that this article is amazing,
    great written and include approximately all important infos.
    I would like to peer extra posts like this .

  40. kenneth copeland ministry says:

    Howdy fantastic website! Does running a blog similar to
    this require a lot of work? I’ve no understanding of programming but I was
    hoping to start my own blog soon. Anyways, should
    you have any suggestions or techniques for new blog owners please
    share. I know this is off topic but I simply needed to ask.

    Appreciate it!

  41. Emilio says:

    I think this is among the most significant information for me.
    And i’m glad reading your article. But wanna remark on some general
    things, The website style is great, the articles is really great : D.

    Good job, cheers

  42. Zella says:

    It’s very effortless to find out any matter on web as compared to books, as I found this post at
    this site.

  43. Sreenivas Reddy says:

    Great tutorial about Collections. We can easily understand about java collections by this tutorial. Keep post good posts like this .Thanks very much for this valuble info..

  44. Www.Linkedin.com says:

    I always spent my half an hour to read this web site’s articles all the time along with a cup of coffee.

  45. Prashant Kumar says:

    Perfectly explained Pankaj. Thanks a lot..

  46. Bhimaraya says:

    Thank you very much sir.
    you explained very nicely.

  47. Santosh says:

    Q>>why would you want to catch Exception, when you can catch Throwable?

    1. Pradeep says:

      You are absolutely right. you can catch Throwable object instead of Exception object BUT if you look at the hierarchy of exceptions then you will notice Throwable is the top class of ERROR & EXCEPTION classes…..& if you catch Throwable object then there is an assumption from the developer that your program may throw Error object which is not possible. Please read this article.

      So whichever exception(Runtime or CompileTime) is occurring in the program, will be able to Upcast to Exception object….so it is good practice to catch Exception object rather than Throwable object.

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages