Java / Collections
1. How do you initialize an ArrayList?
In three ways, Using add(Object obj) method, ArrayList
2. How to reverse the List using Collections?
Collections class has its own static method reverse(List list) that could reverse any type of list. Collections.reverse(myListObject);
3. What is Java Collections Framework?
Java collections API is the implementation of data structures; Java collection is nothing but a java object that point to a group of objects.
4. How do I parse an URL String into Name-Value Collection?
public static Map
5. Explain get(keyObj) method of HashMap/Hashtable.
hashcode() method of the Key object being passed as an argument to the get method finds the unique bucket location in backing array and the value from the entry(Key, value) is returned. one hashcode() (one entry) corresponds to one bucket location.
6. How get() method will handle if two keys have the same hashcode?
When put() method stores the key at the same bucket location collision would have occurred, so the bucket location upgrades itself to store multiple entries by forming a linked data structure, and once key.hashcode() find the bucket location, all the entries are traversed to find the correct key ...
7. What get() method return if the key does not exist at HashMap?
8. Advantages of using Collections Framework.
improves re-usability and interoperability. Less programming/development effort. Improved code quality and well structured. Utility functions to perform processing/manipulation over the collection data e.g.sort, search. enhances code readability.
9. Root interface in collection hierarchy.
Collection interface is the root interface and it is part of java.util package. Although Collection extends java.lang.Iterable, Iterable is not part of collection hierarchy.
10. Where does the Java Collection framework packaged?
Under java.util package.
11. How do I synchronize a ArrayList In Java?
Collections.synchronizedList() can be used to synchronize arraylist. This method returns synchronized list backed by the specified list.
12. Does HashMap get() method work with value object's hashcode?
No.
13. What is Entry?
Entry is an inner class of HashMap that stores key-value pair.
14. Difference between poll() and remove() method of Queue interface.
poll() and remove() method from Queue is used to remove the object and returns the head of the queue. However If Queue is empty() then a call to remove() method will throw Exception, whereas a call to poll() method returns null.
15. Difference between fail-fast and fail-safe Iterators.
Fail-fast Iterators throws ConcurrentModificationException when one thread is iterating over the collection object and other thread structurally modify the Collection either by adding, removing or modifying objects on underlying collection. They are called fail-fast because it immediately throws ...
16. Which collection classes are synchronized or thread-safe ?
Stack, Properties , Vector and Hashtable are synchronized classes (or thread-safe).
17. What are the core Collection interfaces?
The core collection interfaces are : Collection , Set , Queue , List , Map
18. What is the difference between List and Set ?
Set can hold only unique elements where as List can contain duplicate elements. Set is unordered while List is ordered; List maintains the order of object insertion.
19. What is the difference between Map and Set ?
Map object has unique keys each containing some value, while Set contain only unique values.
20. What are the classes that implements List and Set interface ?
Class implementing List interface are ArrayList, Vector, LinkedList Class implementing Set interface : HashSet, TreeSet
21. What is an iterator?
Iterator is an interface that provides specification for methods to iterate over any Collection.
22. What is the difference between Iterator and Enumeration ?
Iterator has remove() method while Enumeration doesn't. Hence, using Iterator we can modify the collection by adding and removing the objects. Enumeration acts as a read only interface, only traverse through the objects.
23. Which design pattern implemented by Iterator?
It uses iterator design pattern. Iterator design pattern allows us to navigate through the collection of objects by using a common interface irrespective on type of collection. Enumeration is also an example of Iterator design pattern.
24. What are the methods to be overridden to use an object type as key in HashMap ?
equals() and hashCode() method has to be overriden by the object and provide its own implementation.
25. What is the difference between Queue and Stack?
Queue is a data structure which is based on FIFO (first in first out). e.g. in the real world, who gets into the ticket counter queue gets the ticket and leave the queue. Stack is a data structure which is based on LIFO (last in first out). e.g. stacked plates, where we need to remove the top pla...
26. Convert the array of strings into a list.
Arrays class of java.util package contains the method asList() which accepts the array as parameter. So, String[] fruits = {"Apple" , "Orange" , "Banana"}; List fruitsList = Arrays.asList(fruits);
27. What is the difference between HashMap and Hashtable?
HashMap allows one null key and any number of null values while Hashtable does not allow null as either keys or values. HashMap is not synchronized or thread-safe whereas Hashtable is synchronized or thread-safe.
28. 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 ...
29. What is the difference between Iterator and ListIterator?
Using Iterator we can traverse the list of objects only in forward direction . But ListIterator can traverse the collection in both directions that is forward as well as backward. ListIterator has .add() method whereas Iterator does not have.
30. What is the difference between Array and ArrayList in Java?
Array is static in size while ArrayList is dynamic in size. Array can contain primitive data types or Objects while ArrayList can only hold Objects and can not contain primitive data types.
31. Does HashSet ignore String case when contains() method is invoked in Java?
HashSet's contains() method is case sensitive and does not allow the use of comparators. We could use TreeSet instead of HashSet which allow Comparator thus facilitating case-insensitive search and comparison. Using the comparator String.CASE_INSENSITIVE_ORDER we could perform case ignored search...
32. How do you swap two elements in a list using Collections class API?
Using Collections.swap. It swaps the elements at the specified positions in a specified list. swap(List listElement, int i, int k) This static method of Collections class swap the element between the position i and k at the listElement. import java.util.ArrayList ; import java.util.Arrays ; impor...
33. What is IdentityHashmap in Java?
Java.util.IdentityHashMap implements Map interface and it does not make use of equals() and hashcode() methods to compare objects insteadIdentityHashMap uses equality operator "==" to compare the key and value objects. The use of the equality operator makes IdentityHashMap perform faster compared...
34. What are the similarities between HashSet, LinkedHashSet and TreeSet In Java?
Although these implementations had considerable difference, there share similarities with each other. None of them allow duplicate elements. None of them are synchronized. All are Cloneable and Serializable. Iterator returned by these implementations are fail-fast i.e We will encounter Concurrent...
35. List the differences between LinkedList and ArrayList in Java.
LinkedList is the doubly linked list implementation of List interface whereas ArrayList is the resizable array implementation of List interface. Retrieval (get (int index)) and search operations are faster in ArrayList compared to LinkedList in terms of performance as ArrayList internally uses ar...
36. List out the similarities between ArrayList and LinkedList in Java.
Both ArrayList and LinkedList implements List interface and their API are identical. Both allows null as an element and even multiple null is possible as well since List allows duplicates. Both ArrayList and LinkedList are not synchronized and we could render as synchronized using Collections.syn...
37. Java: Which algorithm does Collections.sort() use?
Collections.sort implementation uses merge sort or tim sort.
38. Why Collection does not extend Cloneable and Serializable interfaces ?
The Collection interface specifies groups of objects known as elements. Each concrete implementation of a Collection can choose its own way of how to maintain and order its elements. The semantics and the implications of either cloning or serialization come into play when dealing with actual impl...
39. Difference between Comparable and Comparator interface.
Comparable. Comparator. Class whose objects to be sorted must implement this interface and to implement compareTo(Object) method. Class whose objects to be sorted do not need to implement this interface. Instead a third class can implement this interface to sort and implement compare method. Sort...
40. Difference between Synchronized Collection and Concurrent Collection.
Concurrent Collections has better performance than synchronized Collection because they lock only a portion of Map to achieve concurrency and Synchronization.
41. What is BlockingQueue in Java collections?
BlockingQueue implements java.util.Queue interface. BlockingQueue 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 does not accept null elements and it's impleme...
42. Difference between the add and offer methods in a Queue in Java.
When an element cannot be added to collection the add method throws an exception while offer method doesn't.
43. How do you filter a Java Collection?
Java 8 uses streams and lambdas to perform filtering in one line of code. List
44. How to avoid ConcurrentModificationException when removing while Iterating through a Collection?
Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
45. What is the difference between Streams and Collections in Java 8?
Collection is used for storing data in different data structures while Stream API is used for computation of data on a large set of Objects. Collection API we can store a finite number of elements in a data structure. With Stream API, we can handle streams of data that can contain infinite number...
46. What is predicate in Java 8?
In Java 8, Predicate a functional interface used as the assignment target for a lambda expression or method reference. You may use them anywhere where you need to evaluate a condition on group/collection of similar objects such that evaluation can result either in true or false. public static voi...
47. Advantages of using Lambda expression.
Lambda expression enable functional programming in Java. Passing a lambda expression as an object to a method eliminates the overhead involved in passing an anonymous class. We can also pass a method as parameter to another method using lambda expressions.
48. Difference between Predicate and function in Java 8.
Both helps in evaluating lambda expressions. The difference is a predicate takes one argument and returns a boolean value while a function takes one argument and returns an object .
49. Difference between IntStream.rangeClosed() and range() in Java 8.
Both generates incremental number by one from start to end point in java 8. The difference is range does not include last number while rangeClosed does. For example IntStream.range(1,6) produces value from 1 through 5 while rangeClosed generates 1 to 6.
50. What is the main objective of streaming and lambda in Java8?
Parallelism.
51. How are the parallel streams implemented in Java8?
Parallelization can be achieved just by calling parallel() and it is implemented using fork and join thread pool framework.
52. Explain Supplier interface in Java8.
The Supplier is a functional nterface that represents an operation that takes no argument and returns an object. It declares the functional method Object get().
53. What is BooleanSupplier interface in Java8?
java.util.function.BooleanSupplier is a functional interface whose functional method is boolean getAsBoolean(). This method returns a boolean result.
54. Why do we need to use Java 8 Stream API?
Java 8 Stream API provides the following capabilities. To perform Database like Operations such as group by, order by operations. Enables Parallel Operations there by improving performance. Enables Functional Style programming so we will focus on what to do rather than how to do. Enables operatio...
55. The default capacity of Collection Elements: ArrayList, Vector, HashSet, Hashtable, and HashMap.
.tg {border-collapse:collapse;border-spacing:0;} .tg td{font-family:Arial, sans-serif;font-size:14px;padding:10px 5px;border-style:solid;border-width:1px;overflow:hidden;word-break:normal;border-color:black;} .tg th{font-family:Arial, sans-serif;font-size:14px;font-weight:normal;padding:10px 5px;...
56. How Fail Fast Iterator works internally?
To identify the structural modification in the collection, fail-fast iterators use an internal flag called modCount which is updated each time a collection is modified. Fail-fast iterators check this flag while calling next() method to retrieve next value and if it finds that modCount changed aft...