JavaRush/Java Blog/Random EN/Java Class Collection Interview Frequently Asked Question...
theGrass
Level 24

Java Class Collection Interview Frequently Asked Questions (Part 1)

Published in the Random EN group
members
Without a doubt, collections in Java are a very important area, and questions about collections will be asked in interviews for both novice and experienced programmers. The topic is so vast that it is almost impossible to cover it entirely. And yet, based on my previous interviews, I will try to list as many GOOD questions as possible that you should be prepared for. Java Class Collections Interview Frequently Asked Questions (Part 1) - 1The questions will be both difficult and simple, so if the question seems too primitive for you - do not forget that it is perfect for a less experienced programmer.

Questions in this article:

General issues
  1. What are collections in Java? List their benefits
  2. Tell us about the hierarchy of collections
  3. Why don't collections inherit interfaces Cloneableand Serializable?
  4. Why Mapdoesn't an interface inherit interface Collection?
Questions about lists
  1. Why do we use lists? What are the main classes that implement the interface List?
  2. How to convert an array of strings to ArrayList?
  3. How to sort a list in reverse order?
Questions about sets
  1. Why do we use sets? What are the main classes that implement the interface Set?
  2. How are elements stored in HashSet?
  3. Can an element nullbe added to TreeSetor HashSet?
Questions about dictionaries
  1. Why do we use dictionaries? What are the main classes that implement the interface Map?
  2. What is IdentityHashMapand WeakHashMap?
  3. Explain what is ConcurrentHashMap? How does it work?
  4. How do dictionaries work?
  5. How to create a good dictionary key?
  6. What kind of content representations does the interface provide Map?
  7. When to use HashMapand when TreeMap?
Questions 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

General issues

  1. What are collections in Java? List their benefits?

    By definition, a collection is an object representing a group of objects. As in set theory, a set is a group of objects. Simple, right? Prior to JDK 1.2, there were classes like Vectorand HashTable, but there was no Collection. Then it was decided to add support for reusable data structures. This framework was developed primarily by Joshua Bloch, and first appeared in JDK 1.2.

    As the main advantages, we can list:

    • Reduced time spent writing code
    • Improved performance through the use of highly efficient algorithms and data structures
    • Collections are a versatile way to store and pass data, making it easy for different parts of your code to interact.
    • Easy to learn because only the topmost interfaces and supported operations need to be learned
  2. Tell us about the hierarchy of collections?

    Java Class Collection Interview Frequently Asked Questions (Part 1) - 2

    As shown in the picture, the collections framework contains one top-level interface - Collection, from which Set, Listand are inherited Queue. Below we will look at many more classes contained in these three branches. Remember the interface title Collection, it will help you with many questions.

    public interface Collection extends Iterable {
    //описание методов
    }

    The framework also contains the Map interface , which is not a descendant of the Collection. The reason why he does not inherit Collection, we will analyze in the fourth question.

  3. Why don't collections inherit interfaces Cloneableand Serializable?

    Well, the simplest answer is "because you don't have to." The functionality provided by interfaces Cloneableis Serializablesimply not needed for collections.

    Another reason is that a subclass is not always needed, Cloneablebecause each clone operation consumes a lot of memory, and inexperienced programmers can spend it themselves without understanding the consequences.

    And the last reason - cloning and serialization are very highly specific operations, and they should be implemented only when necessary. Many collection classes implement these interfaces, but there is absolutely no need to implement them for all collections at all. If you need cloning and serialization - just use those classes where it is, if not - the rest of the classes.

  4. Why Mapdoesn't an interface inherit interface Collection?

    A good answer to this question is "because they are incompatible". The interface Collectiondescribes the method add(Object o).

    Dictionaries cannot contain this method because they operate on key/value pairs. Also, dictionaries have representations keySetthat valueSet,don't exist in collections.

    Due to these differences, an interface Mapcannot inherit an interface Collectionand is a separate branch of the hierarchy.

Questions about lists

  1. Why do we use lists? What are the main classes that implement the interface List?

    Lists in Java are an ordered collection of elements. Each element has an index starting from zero. All indexes are unique. In addition to the methods described in the interface Collection, lists have their own methods, mainly for working with elements of collections by their index. These methods can be divided into 3 groups - searching for an element, getting a specific element, iterating over a collection, and selecting a subgroup. All these operations can be performed by element index.

    The main classes that implement the interface Listare Stack, Vector, ArrayListand LinkedList. For more information on them, refer to the documentation.

  2. How to convert an array of strings to ArrayList?

    This question is somewhat deeper than just programming, as it is seen by beginners. Its purpose is to test the candidate's knowledge of the utility classes of the framework Collection. Consider two such classes, the most popular in interviews - Collectionsand Arrays.

    The class Collectionsprovides static methods for operations on collections. Accordingly, Arraysit provides static methods for operations on arrays.

    String[] words = {"аз", "буки", "веди", "глагол", "добро"};
    //Как вы можете обратить внимание, у нас есть массив строк String[] words.
    //В котором у нас лежат 5 строк.
    List wordList = Arrays.asList(words);
    //легким движением руки, а точнее вызовом Arrays.asList() мы превратor наш
    //массив строк в список List wordList.

    I would also like to note that this method is capable of processing not only strings, it will create a list of elements of any type that an array was.

    Integer[] nums = {1, 2, 3, 4};
    List numList = Arrays.asList(nums);
  3. How to sort a list in reverse order?

    Like the previous one, this question tests your knowledge of utility classes.Collection

    List reversedList = Collections.reverse(list);

Questions about sets

  1. Why do we use sets? What are the main classes that implement the interface Set?

    It models a mathematical set, from set theory. The interface Setis similar to List, but has some differences. The first is not an ordered collection. Therefore, adding/removing elements does not require them to be sorted. The main feature of sets is the uniqueness of elements, that is, the same element cannot be contained in the set twice.

    equals()The and methods are very important for the functioning of sets hashCode(); they allow you to compare sets of different classes. Two sets are identical only if they contain the same elements.

    As you can see from the above, sets do not support element-index-based operations like lists do. Sets have only those methods that are described in the interfaceCollection

    The main classes that implement the interface Setare EnumSet, HashSet, LinkedHashSetand TreeSet. If you want to learn more, read the relevant sections of the Java documentation.

  2. How are elements stored in HashSet?

    As you already know, HashMapstores key/value pairs, and the keys must be unique. HashSetuses this feature HashMapto ensure the uniqueness of its elements. In the class HashSet, the dictionary is described as follows:

    private transient HashMap<E, Object> map;
    private static final Object PRESENT = new Object();

    So, when you store an element in a set, it puts that element as the key in the dictionary, and the value is the PRESENT object, as described below:

    public boolean add(E e) {
      return map.put(e, PRESENT) == null;
    }

    I strongly recommend that you read this article , it will help you answer all related HashMapquestions with ease.

  3. Can an element nullbe added to TreeSetor HashSet?

    As you can see from the previous answer, add()there is no check for null. Also, HashMapallows one key null, hence one element nullcan be added to HashSet.

    TreeSetworks on the same principle as HashSet, but uses NavigableMapto store elements

    private transient NavigableMap<E,Object> m;
    private static final Object PRESENT = new Object();

    NavigableMapit is a derived class SortedMapand SortedMapdoes not allow the use of keys null. Therefore, and TreeMapdoes not support storing elements of type null. If you try to add null в TreeSet, you will get an exception NullPointerException.

Questions about dictionaries

  1. Why do we use dictionaries ( Map)? What are the main classes that implement the interface Map?

    Dictionaries are a special type of collection that is used to store key/value pairs. For this reason, it does not inherit from the interface Collection. The dictionary provides methods for adding key/value pairs, deleting, searching, and iterating over the data representations provided by the dictionary.

    The main classes that implement the interface Mapare: HashMap, Hashtable, EnumMap, IdentityHashMap, LinkedHashMapand Properties.

  2. What is IdentityHashMapand WeakHashMap?

    IdentityHashMapsimilar to HashMapwith one exception - to compare objects, a comparison of pointers to objects is used, if the pointers are not equal (point to objects located at different addresses), then the objects are considered different.

    IdentityHashMapis quite rarely used. Although it implements an interface Map, it violates one of the device's fundamental principles Map, which requires the use of a method equals()to compare objects.

    IdentityHashMapis used only when it is required to compare objects by their addresses.

    WeakHashMapis an implementation of an interface Mapthat contains weak references to elements. WeakHashMapThat is, if there is not a single reference to its element left outside , this element is removed by the garbage collector. The class is intended to be used with objects whose method equals()checks the object's identity using the ==. Once an element is removed by the garbage collector, it can no longer be recovered, and much to the surprise of the programmer, it will no longer be possible to find it in the dictionary.

  3. Explain what is ConcurrentHashMap? How does it work?

    Taken from the official documentation:
    A dictionary implementation that fully supports multi-threaded adding/removing/search of elements. This class follows the same specifications as Hashtable, and contains methods corresponding to those of Hashtable. However, while all operations are thread-safe, the fetch operation does not lock the table, and there is no way to deny all access to the table at all. This class is compatible with Hashtableeverything except multi-threaded synchronization issues.

  4. How does it work hashmap?

    The most important question most likely to be asked in an interview for a programmer of any level. You should be well versed in this topic, and not only because it is the most asked question, but also because understanding the device hashmapallows you to more easily understand other features of how collections work.

    The answer to this question is very extensive, and you can read it in full in this article - how hashmap works . For now, just remember what HashMapworks based on hashing. A dictionary, by definition, is an object that associates keys and values. To store such structures, it uses the inner class Entry.

    static class Entry implements Map.Entry
    {
    final K key;
    V value;
    Entry next;
    final int hash;
    ...//Еще много codeа тут
    }

    Variables keyand valueare used to store the key and value. And the objects themselves Entryare in an array.

    /**
    * Размер таблицы меняется по необходимости,
    * и обязательно должен быть equals степени двойки
    */
    transient Entry[] table;

    The index of the desired element in the array is calculated from the hash code of the key. More information can be found at the link at the beginning of the answer.

  5. How to create a good dictionary key?

    The next good question, which is usually asked next to the function question HashMap. So, the main limitation is that the key must be such that later it can be used to get a value from the dictionary. Otherwise, there is simply no point in using it. If you understand how it functions hashmap, you know that its operation is heavily dependent on methods hashCode()and equals()key objects.

    As follows from the above, a good key should give the same one hashCodeover and over again, no matter how many times it is requested. And also, the same keys, when calling the method, equals()should return true, and different keys should return false.

    From which it follows that the best candidates for the role of the key are immutable classes.

    You can read more at .

  6. What kind of content representations does the interface provide Map?

    The interface Mapprovides three views of the stored data:

    • set of all keys
    • set of all values
    • a set of objects Entrycontaining both a key and a value

    You can navigate through them using iterators.

  7. When to use HashMapand when TreeMap?

    HashMapit's a very widely used class and you know it. So, I will limit myself to saying that it stores key / value pairs and it allows you to perform many operations on them.

    TreeMapthis is a special variety HashMap. The difference is that the keys TreeMapare stored in an orderly fashion. The default is "natural sort". You can override sorting by providing an instance of the class Comparator, the method compareof which will be used to sort the keys.

    Please note that all keys added to the dictionary must implement the interface Comparable(this is necessary for sorting). Moreover, all keys must be mutually compatible: k1.compareTo(k2)must not call ClassCastExceptionfor any k1and k2stored in a dictionary. If the user tries to put a key into the dictionary that violates this condition (for example, a string key into a dictionary where all keys are of type Integer), the method put(Object key, Object value)should call ClassCastException.

Original article
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet