Prev Next

Java / Collections

1. How do you initialize an ArrayList? 2. How to reverse the List using Collections? 3. What is Java Collections Framework? 4. How do I parse an URL String into Name-Value Collection? 5. Explain get(keyObj) method of HashMap/Hashtable. 6. How get() method will handle if two keys have the same hashcode? 7. What get() method return if the key does not exist at HashMap? 8. Advantages of using Collections Framework. 9. Root interface in collection hierarchy. 10. Where does the Java Collection framework packaged? 11. How do I synchronize a ArrayList In Java? 12. Does HashMap get() method work with value object's hashcode? 13. What is Entry? 14. Difference between poll() and remove() method of Queue interface. 15. Difference between fail-fast and fail-safe Iterators. 16. Which collection classes are synchronized or thread-safe ? 17. What are the core Collection interfaces? 18. What is the difference between List and Set ? 19. What is the difference between Map and Set ? 20. What are the classes that implements List and Set interface ? 21. What is an iterator? 22. What is the difference between Iterator and Enumeration ? 23. Which design pattern implemented by Iterator? 24. What are the methods to be overridden to use an object type as key in HashMap ? 25. What is the difference between Queue and Stack? 26. Convert the array of strings into a list. 27. What is the difference between HashMap and Hashtable? 28. What is the difference between peek(),poll() and remove() method of the Queue interface? 29. What is the difference between Iterator and ListIterator? 30. What is the difference between Array and ArrayList in Java? 31. Does HashSet ignore String case when contains() method is invoked in Java? 32. How do you swap two elements in a list using Collections class API? 33. What is IdentityHashmap in Java? 34. What are the similarities between HashSet, LinkedHashSet and TreeSet In Java? 35. List the differences between LinkedList and ArrayList in Java. 36. List out the similarities between ArrayList and LinkedList in Java. 37. Java: Which algorithm does Collections.sort() use? 38. Why Collection does not extend Cloneable and Serializable interfaces ? 39. Difference between Comparable and Comparator interface. 40. Difference between Synchronized Collection and Concurrent Collection. 41. What is BlockingQueue in Java collections? 42. Difference between the add and offer methods in a Queue in Java. 43. How do you filter a Java Collection? 44. How to avoid ConcurrentModificationException when removing while Iterating through a Collection? 45. What is the difference between Streams and Collections in Java 8? 46. What is predicate in Java 8? 47. Advantages of using Lambda expression. 48. Difference between Predicate and function in Java 8. 49. Difference between IntStream.rangeClosed() and range() in Java 8. 50. What is the main objective of streaming and lambda in Java8? 51. How are the parallel streams implemented in Java8? 52. Explain Supplier interface in Java8. 53. What is BooleanSupplier interface in Java8? 54. Why do we need to use Java 8 Stream API? 55. The default capacity of Collection Elements: ArrayList, Vector, HashSet, Hashtable, and HashMap. 56. How Fail Fast Iterator works internally?

1. How do you initialize an ArrayList?

In three ways, Using add(Object obj) method, ArrayList list = new ArrayList(); list.add("Apple"); list.add("Banana"); list.add("Cherry"); Using Double brace initialization, (an anonymous inner class with an instance initializer. ArrayList alphabets = new ArrayList(...

Read full answer

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);

Read full answer

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.

Read full answer

4. How do I parse an URL String into Name-Value Collection?

public static Map splitQuery(String urlquery) throws UnsupportedEncodingException { Map query_pairs = new LinkedHashMap(); String[] partStr= urlquery.split("\\?"); if (partStr.length >1 && partStr[1] != null) { String[] pairs = partStr[1].split("&")...

Read full answer

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.

Read full answer

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

Read full answer

7. What get() method return if the key does not exist at HashMap?

returns null.

Read full answer

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.

Read full answer

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.

Read full answer

10. Where does the Java Collection framework packaged?

Under java.util package.

Read full answer

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.

Read full answer

12. Does HashMap get() method work with value object's hashcode?

13. What is Entry?

Entry is an inner class of HashMap that stores key-value pair.

Read full answer

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.

Read full answer

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

Read full answer

16. Which collection classes are synchronized or thread-safe ?

Stack, Properties , Vector and Hashtable are synchronized classes (or thread-safe).

Read full answer

17. What are the core Collection interfaces?

The core collection interfaces are : Collection , Set , Queue , List , Map

Read full answer

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.

Read full answer

19. What is the difference between Map and Set ?

Map object has unique keys each containing some value, while Set contain only unique values.

Read full answer

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

Read full answer

21. What is an iterator?

Iterator is an interface that provides specification for methods to iterate over any Collection.

Read full answer

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.

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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);

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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

Read full answer

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

Read full answer

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

Read full answer

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

Read full answer

37. Java: Which algorithm does Collections.sort() use?

Collections.sort implementation uses merge sort or tim sort.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

43. How do you filter a Java Collection?

Java 8 uses streams and lambdas to perform filtering in one line of code. List highlyPaidEmployees= employees.stream() .filter(p -> p.getSalary() > 1500000).collect(Collectors.toList());

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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.

Read full answer

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 .

Read full answer

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.

Read full answer

50. What is the main objective of streaming and lambda in Java8?

Parallelism.

Read full answer

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.

Read full answer

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

Read full answer

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.

Read full answer

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

Read full answer

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

Read full answer

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

Read full answer

«
»

Comments & Discussions