and pdfThursday, June 3, 2021 5:19:39 AM4

Collection Framework In Java Interview Questions And Answers Pdf

collection framework in java interview questions and answers pdf

File Name: collection framework in java interview questions and answers .zip
Size: 22240Kb
Published: 03.06.2021

Java Programming - Objects and Collections

Here I am listing some important java collections interview questions and answers to help you in the interview. 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. Java Collections have come through a long way with the 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;. Java 1. 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. I would highly recommend to go through Java Generic Tutorial to understand generics in a better way. Collection is the root of the collection hierarchy.

A collection represents a group of objects known as its elements. 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.

List is an ordered collection and can contain duplicate elements. You can access any element from its index. The list is more like an array with dynamic length. 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. Collection interface specifies group of Objects known as elements.

How the elements are maintained is left up to the concrete implementations of Collection. A lot of the Collection implementations have a public clone method. 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 less flexible and more restrictive. The specific implementation should decide as to whether it can be cloned or serialized. Although Map interface and its implementations are part of the Collections Framework, Map is not collections and collections are not Map.

If Map extends Collection interface, then where are the elements? The 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. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern. Enumeration is twice as fast as Iterator and uses very little memory. Enumeration is very basic and fits basic needs. But the 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.

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 its functionality clear. 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.

Using iterator is more thread-safe because it makes sure that if underlying list elements are modified, it will throw ConcurrentModificationException. 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. By design, all the collection classes in java. Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.

Check this post for ConcurrentHashMap Example. Iterator interface declare methods for iterating a collection but its implementation is responsibility of the Collection implementation classes. Every collection class that returns an iterator for traversing has its own Iterator implementation nested class. This allows collection classes to chose whether iterator is fail-fast or fail-safe.

UnsupportedOperationException is the exception used to indicate that the operation is not supported. UnmodifiableCollection throws this exception for all add and remove operations. HashMap stores key-value pair in Map. Entry static nested class implementation. HashMap works on hashing algorithm and uses hashCode and equals method in put and get methods. When we call put method by passing key-value pair, HashMap uses Key hashCode with hashing to find out the index to store the key-value pair.

The Entry is stored in the LinkedList, so if there is an already existing entry, it uses equals method to check if the passed key already exists, if yes it overwrites the value else it creates a new entry and stores this key-value Entry. When we call get method by passing Key, again it uses the hashCode to find the index in the array and then use equals method to find the correct Entry and return its value. The below image will explain these detail clearly. The other important things to know about HashMap are capacity, load factor, threshold resizing.

HashMap initial default capacity is 16 and load factor is 0. The threshold is capacity multiplied by load factor and whenever we try to add an entry if map size is greater than the threshold, HashMap rehashes the contents of the map into a new array with a larger capacity. HashMap uses the Key object hashCode and equals method to determine the index to put the key-value pair.

These methods are also used when we try to get value from HashMap. The implementation of equals and hashCode should follow these rules. We can use any class as Map Key, however following points should be considered before using them. HashMap and Hashtable both implements Map interface and looks similar, however, there is the following difference between HashMap and Hashtable.

For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

Arrays can contain primitive or Objects whereas ArrayList can contain only Objects. Arrays are fixed-size whereas ArrayList size is dynamic. Although ArrayList is the obvious choice when we work on the list, there are a few times when an array is good to use.

ArrayList and LinkedList both implement List interface but there are some differences between them. Download java collections pdf for more information. EnumSet is Set implementation to use with enum types. All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

EnumSet is not synchronized and null elements are not allowed. Check this post for java enum tutorial. Vector, Hashtable, Properties and Stack are synchronized classes, so they are thread-safe and can be used in multi-threaded environment. By design Iterator implementation in java. But Iterator implementation in java. BlockingQueue is a Queue that supports operations that wait for the queue to become non-empty when retrieving and removing an element, and wait for space to become available in the queue when adding an element.

Check this post for use of BlockingQueue for producer-consumer problem. Both Queue and Stack are used to store data before processing them.

Queue is an interface whose implementation classes are present in java concurrent package. There is also Deque interface that allows elements to be retrieved from both end of the queue.

Stack is a class that extends Vector whereas Queue is an interface. Collections is a utility class consists exclusively of static methods that operate on or return collections. This class contains methods for collection framework algorithms, such as binary search, sorting, shuffling, reverse, etc.

Java provides a Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods.

The comparable interface has a compareTo T obj method which is used by sorting methods. But, in most real-life scenarios, we want sorting based on different parameters.

This is the situation where we need to use Comparator interface because Comparable. Comparator interface compare Object o1, Object o2 method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if the first argument is less than the second one and returns zero if they are equal and positive int if the first argument is greater than the second one.

Check this post for use of Comparable and Comparator interface to sort objects. Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic.

Comparator interface is used to provide different algorithms for sorting and we can choose the comparator we want to use to sort the given collection of objects. If we need to sort an array of Objects, we can use Arrays.

Java collections Interview Questions

In Java, collection interview questions are most asked by the interviewers. Here is the list of the most asked collections interview questions with answers. Collection Framework is a combination of classes and interface, which is used to store and manipulate the data in the form of objects. Array and Collection are somewhat similar regarding storing the references of objects and manipulating the data, but they differ in many ways. The main differences between the array and Collection are defined below:. Collection framework implements various interfaces, Collection interface and Map interface java. Map are the mainly used interfaces of Java Collection Framework.

To browse Academia. Skip to main content. By using our site, you agree to our collection of information through the use of cookies. To learn more, view our Privacy Policy. Log In Sign Up.

For more java articles ,Click here to Subscribe JavaHungry. Java Hungry. Java developers tutorials and coding. We have already shared the most frequently asked java interview questions for experienced candidates. I also shared the tricky coding interview questions in our previous posts.

Java Collections Interview Questions

Java Collections is the type of the set of classes that help to implement the common reusable data. Java Collections framework is one of the most important parts of the Java programming language. Java Collections is the type of containers that help you group all the types of multiple items in the single units.

Without argument, java collections is one of the most important area where you will be tested in any position whether junior or senior. The scope is so much wide, that its almost impossible to cover all the questions. Yet based on my previous interviews, I am attempting to put as many as possible GOOD java collection interview questions you must know.

These interview questions seems to be too common and appear in almost many interviews and that's the reason I never asked so called frequently asked or popular interview question, instead I ask something which is not so common like: 1 What is CopyOnWriteArrayList, how it is different than ArrayList and Vector? Generics, dynamic growing 7 What is BlockingQueue, how it is different than other collection classes flow control 8 How do you iterator over Synchronized HashMap, do you need to lock iteration and why? If anyone wants to answer this question , they must required a very good understanding of Java Collection framework which is whole purpose of these interview questions.

40 Java Collections Interview Questions and Answers

java interview questions and answers

Here are Java Collections Interview Questions for fresher as well as experienced candidates to get their dream job. A framework is a popular and readymade architecture that contains a set of classes and interfaces. Collection Framework is a grouping of classes and interfaces that is used to store and manage the objects. Java Collection framework can also be used for interfaces like Queue, Set, List, etc. Collections is a class consists of static methods that operate on collections. It contains polymorphic algorithms to operate on collections, "wrappers". This class contains methods for algorithms, like binary sorting, search, shuffling, etc.

Arrays are not dynamic. Once an array of a particular size is declared, the size cannot be modified. To add a new element to the array, a new array has to be created with bigger size and all the elements from the old array copied to new array. Collections are used in situations where data is dynamic. Collections allow adding an element, deleting an element and host of other operations. There are a number of Collections in Java allowing to choose the right Collection for the right context. Most important methods declared in the collection interface are the methods to add and remove an element.

 Если Танкадо перестанет быть фактором? - вслух размышлял Нуматака.  - Тогда мы с вами придем к соглашению. - Буду держать вас в курсе, - произнес голос, и вслед за этим в трубке раздались короткие гудки. ГЛАВА 14 Беккер впился глазами в труп. Даже через несколько часов после смерти лицо азиата отливало чуть розоватым загаром. Тело же его было бледно-желтого цвета - кроме крохотного красноватого кровоподтека прямо над сердцем.


Good Java Collection Interview Questions Answers. How does HashMap work in Java? (What is the difference between fail-fast and fail-safe Iterators? (What is the difference between Synchronized Collection and Concurrent Collection? (What is the difference between Iterator and Enumeration? .


Javatpoint Services

 Тридцать два, - уточнил Стратмор.  - У него был врожденный порок сердца. - Никогда об этом не слышала. - Так записано в его медицинской карточке. Он не очень-то об этом распространялся. Сьюзан трудно было поверить в такое удачное совпадение.

4 Comments

  1. Julie H.

    06.06.2021 at 02:38
    Reply

    1) What is framework in Java? A framework is a popular and readymade architecture that contains a set of classes and interfaces. 2) What is the.

  2. Marian S.

    07.06.2021 at 09:50
    Reply

    Solved examples with detailed answer description, explanation are given and it would be easy to understand.

  3. Kipa C.

    09.06.2021 at 22:49
    Reply

    Java Collections interview questions and answers for experienced/beginner programmers. A must Java Collections Framework is one of the core APIs of java programming language. Download java collections pdf for more information.

  4. Jeanette D.

    11.06.2021 at 07:14
    Reply

    Here I am listing some important java collections interview questions and answers to help you in the interview.

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