JavaRush /Java Blog /Random EN /Java Class Collection Interview Frequently Asked Question...
theGrass
Level 24
Саратов

Java Class Collection Interview Frequently Asked Questions (Part 2)

Published in the Random EN group
Java Class Collections Interview Frequently Asked Questions (Part 2) - 1Questions about the differences between different collections
  1. What are the differences between Setand List?
  2. What are the differences between Listand Map?
  3. List the differences between HashMapandHashTable?
  4. What are the differences between Vectorand ArrayList?
  5. What are the differences between Iteratorand Enumeration?
  6. What are the differences between HashMapand HashSet?
  7. What are the differences between Iteratorand ListIterator?
  8. What are the differences between TreeSetand SortedSet?
  9. What are the differences between ArrayListand LinkedList?
And more questions
  1. How to make a collection read-only?
  2. How to make a collection thread-safe?
  3. Why isn't there a method Iterator.add()to add elements to a collection?
  4. What are the ways to iterate over the elements of a list?
  5. How do you understand the iterator property to work fail-fast?
  6. What's the difference between fail-fastand fail-safe?
  7. How to avoid ConcurrentModificationExceptionwhile iterating over a collection?
  8. What is UnsupportedOperationException?
  9. Which collection classes give access to any element?
  10. What is BlockingQueue?
  11. What is a queue and a stack, list the differences between them?
  12. What are interfaces Comparableand Comparator?
  13. What are classes Collectionsand Arrays?
  14. List of used literature
Without wasting time, let's get down to the explanations

Questions about the differences between different collections

  1. What are the differences between Setand List?

    List of Key Differences:
    Sets are unordered collections while lists are ordered, where each element has a zero-based index. Lists can contain two or more identical elements, but sets cannot. A list can contain any number of elements null, while a set can contain only one.

  2. What are the differences between Listand Map?

    The easiest question. A list is a collection of elements, and a dictionary is a collection of key/value pairs. There are many more changes, but they are all a consequence of this one. They have a different top-level interface, a different set of methods, and different data representations. In most cases, only the first answer is sufficient.

  3. What are the differences between HashMapand HashTable?

    There are several differences between HashMapand HashTablein Java:

    • HashTablethread safe HashMapnot
    • HashTablecannot contain elements null, while HashMapit can contain one key nulland any number of valuesnull
    • The third key difference between them is that the iterator y HashMap, unlike the enumerator HashTable, works according to the principle fail-fast(throws an exception for any data inconsistency)

  4. What are the differences between Vectorand ArrayList?

    Let's note some differences:

    • All methods Vectorare thread-safe, but y ArrayListis not.
    • Vectorthis is a deprecated class added in the first release of the JDK. ArrayListappeared in JDK 1.2, along with the rest of the framework classesCollection
    • By default, Vectorit doubles its size when the memory allocated for the elements runs out. ArrayListincreases its size by only half

  5. What are the differences between Iteratorand Enumeration?

    Iterators differ from enumerators in three ways:

    • There are iterators that allow you to remove elements from your collection during iteration, using the remove(). The class Iteratordoes not support this functionality. You can't add/remove elements using an enumerator
    • Enumerators are present in legacy classes such as Vector/Stack, while iterators are present in all modern collection classes.
    • Another slight difference is that iterators and enumerators have different method names, that is, Enumeration.hasMoreElements()matches Iterator.hasNext()and Enumeration.nextElement()matches Iterator.next(), etc.

  6. What are the differences between HashMapand HashSet?

    HashMapis a collection of key/value pairs, while HashSetit is an ordered collection of unique elements. And that's it, no more explanation needed.

  7. What are the differences between Iteratorand ListIterator?

    There are three differences:

    • Iteratorcan be used to iterate over elements of Set, Listand Map . In contrast, ListIteratorit can only be used to iterate over the elements of a collection.List
    • Iteratorallows you to iterate over elements in only one direction, using the next(). Whereas ListIteratorit allows you to iterate over the list in both directions, using the methods next()andprevious()
    • With , ListIteratoryou can modify the list by adding/removing elements using the add()and methods remove(). Iteratordoes not support this functionality

  8. What are the differences between TreeSet and SortedSet?

    SortedSetis an interface implemented by the class TreeSet. That's all!

  9. What are the differences between ArrayListand LinkedList?
    • LinkedListstores elements in a doubly linked list, while ArrayListstoring them in an array that can dynamically change in size
    • LinkedListsupports adding/removing elements in a fixed time, but only sequential access to elements. That is, you can loop through the list from beginning to end and from end to beginning, but getting an element in the middle of the list will take time proportional to the size of the list. ArrayListon the other hand, it allows you to get any element by its index in a fixed time. But adding/removing elements there takes time proportional to the size, because you need to move all the elements from the place of insertion/deletion to the end of the list, either to make room for the one being inserted or to remove the gap at the place of the deleted one.
    • LinkedListrequires more memory to store the same number of elements, because in addition to the element itself, pointers to the next and previous elements of the list are also stored, while the ArrayListelements simply go in order

And more questions

  1. How to make a collection read-only?

    Use the following methods:

    • Collections.unmodifiableList(list);
    • Collections.unmodifiableSet(set);
    • Collections.unmodifiableMap(map);

    They all take a collection as a parameter, and return a read-only collection with the same elements inside.

  2. How to make a collection thread-safe?

    Use the following methods:

    • Collections.synchronizedList(list);
    • Collections.synchronizedSet(set);
    • Collections.synchronizedMap(map);

    They all take a collection as a parameter, and return a thread-safe collection with the same elements inside.

  3. Why isn't there a method Iterator.add()to add elements to a collection?

    The only job of an iterator is to iterate over a collection. Each collection has a method add()that you can use. It makes no sense to add this method to an iterator, because collections can be ordered and unordered, and the method add()must be arranged differently.

  4. What are the ways to iterate over the elements of a list?

    There are 4 ways:

    • Loop with iterator
    • Cyclefor
    • Extended for loop
    • Cyclewhile
    Read the article .

  5. How do you understand the iterator property to work fail-fast?

    An iterator fail-fastthrows an exception as soon as it detects that the structure of the collection has changed since iteration began. By changing the structure, we mean adding/removing/changing an element of a collection while another thread is iterating over this collection.

  6. What's the difference between fail-fastand fail-safe?

    In contrast fail-fast, iterators fail-safedon't throw any exceptions when the structure changes, because they operate on a clone of the collection instead of the original.

    The collection iterator and the collection CopyOnWriteArrayListview iterator are examples of iterators .keySetConcurrentHashMapfail-safe

  7. How to avoid ConcurrentModificationExceptionwhile iterating over a collection?

    First of all, you can choose another iterator that works according to the principle fail-safe. For example, if you are using List, you can take ListIterator. If you need an obsolete collection, then use enumerators.

    If the above doesn't work for you, you have three options:

    • If you are using JDK 1.5 or later, the ConcurrentHashMapand CopyOnWriteArrayList. This is the best option
    • You can convert the list to an array and iterate over the array
    • You can block changes to the list for the duration of the iteration using the blocksynchronized

    Please note that the last two options will have a negative impact on performance.

  8. What is UnsupportedOperationException?

    This exception is thrown when calling a method that is not supported by this collection. For example, if you create a read-only list with and then call the or Collections.unmodifiableList(list)method on it , you will definitely get this exception.add()remove()

  9. Which collection classes allow access to any element?

    Classes ArrayList, HashMap, TreeMap, Hashtableallow access to any element.

  10. What is BlockingQueue?

    This is a queue that allows you to handle situations when they try to get an element from an empty queue, or when they try to add an element to the queue, and the place in it has run out. The blocking queue methods can be of four types: the first throw an exception, the second return special values ​​( nullor false, depending on the operation), the third block the current thread until the operation can be completed, and the fourth block the thread only for a certain amount of time.

    Examples can be found in this article .

  11. What is queue and stack, list the difference between them?

    Collections created to store items for further processing. In addition to the basic interface operations Collection, queues support additional operations for adding, removing, and checking the state of an element. Usually, but not necessarily, queues operate on a first-in, first-out basis. The stack is almost like a queue, but works on the LIFO principle - last in, first out.

    Regardless of the order of addition/removal, the head of the queue is the element that will be removed when the remove()or methods are called poll(). Also note that Stackboth Vectorare thread safe.

    Usage: Use a queue if you want to process a stream of elements in the same order that they arrive. Good for todo list and request handling. Use a stack if you only want to add and remove elements from the top of the stack, which is useful in recursive algorithms.

    (Now let's digress and explain everything a little differently. So, imagine a clip of a machine gun. You insert cartridges there one at a time, only from one end. And from the same end, one at a time, the bolt mechanism will take them when firing. This is a stack, put an element you can only go to its top, remove it from there and nowhere else.The last placed element will be removed first.

    The queue is like a tube into which you can roll balls and pick them up from the other end. The queue allows you to put elements only in your tail, and pick up only from the head. The element that was placed first will be the first to be taken.

    What a queue and a stack have in common is that they both have a fixed place to put an element and a fixed place to pick it up from - all other elements are inaccessible.

  12. What are interfaces Comparableand Comparator?

    In Java, all collections that support automatic sorting use comparison methods to properly sort the elements. As an example of such classes, we can indicate TreeSet, TreeMapetc. In order to sort elements, a class must implement interfaces Comparatoror Comparable. That is why wrapper classes like Integer, Doubleand Stringimplement the Comparable. The interface Comparablehelps keep the sorting natural, while Comparatorallowing you to sort items according to different custom patterns. The comparator instance is usually passed to the collection's constructor if the collection supports it.

    (Again, I explain differently. The interface Comparatordescribes a method int compare(T o1, T o2), that is, an object that implements this interface can be used to compare two other objects of the same class. If this method returns 0, the objects are equal, +1 and -1 indicate that the first object is "greater" second or vice versa. What meaning you put in the concept of "greater than" and "less than" in relation to your objects is entirely up to you. That is, you describe a class that implements an interfaceСomparator, and in this method you define how you want to compare your objects. Then you pass an object of this class to the collection constructor, which stores the objects compared by this method, and the collection can sort them in ascending / descending order. I repeat - you have a collection in which objects of class T are stored, and there is another object, of another class that implements the interface Comparator, the whole point of which is that it can compare these class objects T, it is no longer needed for anything.

    An interface Comparabledescribes a method int compareTo(T o), that is, it is called not to compare two other objects, but to compare itself with someone else. That is, you do not need a separate comparer object, you lay the comparison mechanism in the element itself stored in the collection. What is more convenient and in what situation is up to you.

  13. What are classes Collectionsand Arrays?

    Classes Collectionsare Arraysspecial utility classes for working with collection classes. They allow you to transform collections, make them write-protected or thread-safe, sort them in different ways, and so on.

  14. List of used literature

    Well, that's not an interview question. Purely for fun. (But to achieve nirvana, you must read as many articles as possible, your hair will become silky and curly and karma will be cleared.

I hope these questions will help you in your next interview. In the future, I advise you to read something additional. The more you know, the better for you! Good study! Original article
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION