IQ-Collections


  • What is Java Collections Framework? what are benefits of Collections framework ?

             Collections are used in every programming language and initial java release contained few classes for collections: Vector, Stack, Hashtable, Array.
            But looking at the larger scope and usage, Java 1.2 came up with Collections Framework that group all the collections interfaces, implementations and algorithms.
           Java Collections have come through a long way with usage of Generics and Concurrent Collection classes for thread-safe operations.
           It also includes blocking interfaces and their implementations in java concurrent package.

Some of the benefits of collections framework are;

      - 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
      - Improves program quality and speed
---------------------------


  • What is the difference between Collection and Collections ?

               Collection is  an interface while Collections is a java class , both are present in java.util package and  part of java collections framework.
---------------------------


  • Which collection classes are synchronized or thread-safe ?

             Stack, Properties , Vector and Hashtable can be used in multi threaded environment because they are synchronized classes (or thread-safe).
---------------------------


  • What are the basic interfaces of Java Collections Framework ?

               Collection 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.

              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 it’s index. List is more like array with dynamic length.

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

             Some other interfaces are Queue, Dequeue, Iterator, SortedSet, SortedMap and ListIterator.
---------------------------


  • What is the benefit of Generics in Collections Framework ?

              Java 1.5 came with Generics and all collection interfaces and implementations use it heavily.
Generics allow us to provide the type of Object that a collection can contain, so if you try to add any element of other type it throws compile time error.
             This avoids ClassCastException at Runtime because you will get the error at compilation. Also Generics make code clean since we don’t need to use casting and instanceof operator.
---------------------------


  • What are the classes implementing List and Set interface ?

                    Class implementing List interface : ArrayList,Vector,LinkedList

                    Class implementing Set interface : HashSet,TreeSet
---------------------------


  • What is the difference between ArrayList and Vector ?

                          1) ArrayList is not synchronized.
                                                Vector is synchronized.
                          2) ArrayList is not a legacy class.
                                                Vector is a legacy class.
                          3)ArrayList increases its size by 50% of the array size.
                                                Vector increases its size by doubling the array size.
---------------------------


  • What is the difference between ArrayList and LinkedList ?

                         1) ArrayList uses a dynamic array.
                                         LinkedList uses doubly linked list.
                         2) ArrayList is not efficient for manipulation because a lot of shifting is required.
                                         LinkedList is efficient for manipulation.
                         3) ArrayList is better to store and fetch data.
                                         LinkedList is better to manipulate data.
---------------------------


  • What is an Iterator ?

              Iterator interface provides methods to iterate over any Collection.
              You 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.
---------------------------


  • What is the difference between Iterator and ListIterator ?

             Iterator traverses the elements in forward direction only.
             ListIterator traverses the elements in backward and forward directions both.

            Iterator can be used in List, Set and Queue.
            ListIterator can be used in List only.

            ListIterator inherits from Iterator interface and comes with extra functionalities like adding an element, replacing an element, getting index position for previous and next elements.
---------------------------


  • What is the difference between Iterator and Enumeration ?

                 Iterator can traverse legacy and non-legacy elements.
                 Enumeration can traverse only legacy elements.

                         Iterator is fail-fast.
                         Enumeration is not fail-fast.

                        Iterator is slower than Enumeration.
                        Enumeration is twice faster than Iterator.
---------------------------


  • What do you understand by iterator fail-fast property ?

              Iterator fail-fast property checks for any modification in the structure of the underlying collection everytime we try to get the next element.
              If there are any modifications found, it throws ConcurrentModificationException.
              All the implementations of Iterator in Collection classes are fail-fast by design except the concurrent collection classes like ConcurrentHashMap and CopyOnWriteArrayList.
---------------------------


  • What is difference between fail-fast and fail-safe ?

               Iterator fail-safe property work with the clone of underlying collection, hence it’s not affected by any modification in the collection.
               By design, all the collection classes in java.util package are fail-fast whereas collection classes in java.util.concurrent are fail-safe.
              Fail-fast iterators throw ConcurrentModificationException whereas fail-safe iterator never throws ConcurrentModificationException.
---------------------------


  • Why Map interface doesn’t extend Collection interface ?

            Although Map interface and it’s implementations are part of Collections Framework, Map are not collections and collections are not Map. Hence it doesn’t make sense for Map to extend Collection or vice versa.
           If Map extends Collection interface, then where are the elements? Map contains key-value pairs and it provides methods to retrieve list of Keys or values as Collection but it doesn’t fit into the group of elements paradigm.
---------------------------


  • What is the advantage of Properties file ?

               If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.
---------------------------


  • What does the hashCode() method ?

              The hashCode() method returns a hash code value (an integer number).

              The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same.

              But, it is possible that two hash code numbers can have different or same keys.
---------------------------


  • Why we override equals() method?

             The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property.

            For example, Employee is a class that has 3 data members: id, name and salary. But, we want to check the equality of employee object on the basis of salary. Then, we need to override the equals() method.
---------------------------


  • How to avoid ConcurrentModificationException while iterating a collection ?

                 We can use concurrent collection classes to avoid ConcurrentModificationException while iterating over a collection, for example CopyOnWriteArrayList instead of ArrayList.
---------------------------


  • Which collection classes provide random access of it’s elements ?

                    ArrayList
                    HashMap
                    TreeMap
                    Hashtable
              These classes provide random access to it’s elements.
---------------------------


  • What is EnumSet ?

              java.util.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. It also provides some useful methods like copyOf(Collection c), of(E first, E rest) and complementOf(EnumSet s).
---------------------------


  • What is the Dictionary class ?

                   The Dictionary class provides the capability to store key-value pairs.
---------------------------


  • What is BlockingQueue ?

               java.util.concurrent.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.

             BlockingQueue interface is part of java collections framework and it’s primarily used for implementing producer consumer problem.
            We don’t need to worry about waiting for the space to be available for producer or object to be available for consumer in BlockingQueue as it’s handled by implementation classes of BlockingQueue.
---------------------------


  • What is difference between Comparable and Comparator interface ?

             Comparable and Comparator interfaces are used to sort collection or array of 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 chose the comparator we want to use to sort the given collection of objects.
---------------------------


  • While passing a Collection as argument to a function, how can we make sure the function will not be able to modify it ?
                We can create a read-only collection using Collections.unmodifiableCollection(Collection c) method before passing it as argument, this will make sure that any operation to change the collection will throw UnsupportedOperationException.
---------------------------


  • What is Java Priority Queue ?

             PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation.
             PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering.
            Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueing and dequeing operations.
---------------------------


  • Why can’t we create generic array ?

             We are not allowed to create generic arrays because array carry type information of it’s elements at runtime.
             This information is used at runtime to throw ArrayStoreException if elements type doesn’t match to the defined type. Since generics type information gets erased at compile time by Type Erasure, the array store check would have been passed where it should have failed.
---------------------------


  • What is the difference between length of array and size() of ArrayList in Java ?

              size() method of ArrayList provides the number of objects available in the collection.

             Array has length property which provides the length or capacity of the Array. It is the total space allocated during the intialization of the array.
---------------------------


  • How to reverse the List in Collections ?

       There is a built in reverse method in Collections class . reverse(List list) accepts list as parameter.
---------------------------


  • How to convert the array of strings into the list ?

              Arrays class of java.util package contains the method Array.asList() which accepts the array as parameter.
---------------------------


  • How to remove element from an array ?
              By converting array to array-list & then converting back to array.
             
             Ex: List list = new ArrayList(Arrays.asList(array));
                    list.removeAll(Arrays.asList("a"));

                    array = list.toArray(array); |
---------------------------


  • What is the difference between peek(),poll() and remove() method of the Queue interface ?

               Both poll() and remove() method is used to remove head object of the Queue. The main difference lies when the Queue is empty().
               If Queue is empty then poll() method will return null . While in similar case , remove() method will throw NoSuchElementException .
               peek() method retrieves but does not remove the head of the Queue. If queue is empty then peek() method also returns null.
---------------------------


  • What is CopyOnWriteArrayList ?  How it is different from  ArrayList in Java ?

            CopyOnWriteArrayList is a thread safe variant of ArrayList in which all mutative operations like add , set are implemented by creating a fresh copy of the underlying array.
            It guaranteed not to throw ConcurrentModificationException.
            It permits all elements including null. It is introduced in jdk 1.5


2 comments:

  1. Short and to the point notes. thanks for this !
    For more in details you can refer Java Framework tutorialsl anytime for future blogs
    thanks in advance !!

    ReplyDelete

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...