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

Frequently Asked Interview Questions on Collection Classes in Java (Part 1)

Published in the Random EN group
Without a doubt, collections in Java are a very important area, and questions about collections will be asked in interviews for both new and experienced programmers. The topic is so vast that it is almost impossible to cover it entirely. Still, based on my previous interviews, I will try to list as many GOOD questions as possible that you should be prepared for. Frequently Asked Interview Questions on Collection Classes in Java (Part 1) - 1The questions will be both complex and simple, so if the question seems too primitive to 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 advantages
  2. Tell us about the collection hierarchy
  3. Why don't collections inherit interfaces Cloneableand Serializable?
  4. Why Mapdoesn't the interface inherit the interface Collection?
Questions about lists
  1. Why do we use lists? What main classes 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 main classes 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 main classes implement the interface Map?
  2. What is IdentityHashMapand WeakHashMap?
  3. Explain what this is ConcurrentHashMap? How does it work?
  4. How do dictionaries work?
  5. How to create a good dictionary key?
  6. What content views does the interface provide Map?
  7. When should you use it HashMapand when should you use it TreeMap?
Questions about differences between different collections
  1. What are the differences between Setand List?
  2. What are the differences between Listand Map?
  3. Name 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 thread-safe collection?
  3. Why isn't there a method Iterator.add()to add elements to a collection?
  4. What ways are there 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 through a collection?
  8. What's happened UnsupportedOperationException?
  9. Which collection classes give access to any element?
  10. What's happened 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 any time, let's get started with the explanations.

General issues

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

    By definition, a collection is an object that is a group of objects. As in set theory, a set is a group of objects. Simple, isn't it? Before JDK 1.2, there were classes such as Vectorand HashTable, but there was no framework 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.

    We can list the main advantages:

    • Reduces time spent writing code
    • Improves performance through the use of highly efficient algorithms and data structures
    • Collections are a universal way to store and transfer data, which simplifies the interaction of different parts of the code
    • Easy to learn because only the topmost interfaces and supported operations need to be learned
  2. Tell us about the hierarchy of collections?

    Frequently Asked Interview Questions on Collection Classes in Java (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. We will look at the reason why he does not inherit Collectionin the fourth question.

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

    Well, the simplest answer is “because it’s not necessary.” The functionality is provided by interfaces Cloneableand Serializableis simply not needed for collections.

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

    And the last reason is that 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 in general. If you need cloning and serialization, just use those classes where it is, if not, use the remaining classes.

  4. Why Mapdoesn't the interface inherit the 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 work with key/value pairs. Also, dictionaries have representations keySetthat valueSet,are not in collections.

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

Questions about lists

  1. Why do we use lists? What main classes 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 collection elements by their index. You can divide these methods into 3 groups - searching for an element, getting a specific element, iterating through 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 detailed information on them, please refer to the documentation.

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

    This question is somewhat deeper than just programming, as it seems to beginners. Its purpose is to test the candidate's knowledge of the framework's utility classes Collection. Let's consider two such classes that are most in demand during 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 the 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 main classes implement the interface Set?

    Он моделирует математическое множество, из теории множеств. Интерфейс Set похож на List, но имеет некоторые отличия. Первое — это не упорядоченная коллекция. Следовательно, добавление/удаление элементов не требует их сортировки. Главная особенность множеств - уникальность элементов, то есть один и тот же элемент не может содержаться в множестве дважды.

    Очень важными для функционирования множеств являются методы equals() и hashCode(), они позволяют сравнивать множества разных классов. Два множества являются идентичными только если они содержат одни и те же элементы.

    Как следует из вышеизложенного, множества не поддерживают операций основанных на индексе element, How списки. Множества имеют только те методы которые описаны в интерфейсе Collection

    Основными классами, реализующими интерфейс Set, являются EnumSet, HashSet, LinkedHashSet и TreeSet. Если хотите узнать больше — почитайте соответствующие разделы documentации Java.

  2. Как хранятся элементы в HashSet?

    Как вы уже в курсе, HashMap хранит пары ключ/meaning, и ключи должны быть уникальны. HashSet использует эту особенность HashMap для обеспечения уникальности своих элементов. В классе HashSet, словарь описан следующим образом:

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

    Итак, когда вы сохраняете элемент в множестве, оно кладет данный элемент в качестве ключа в словарь, а meaningм идет an object PRESENT, How это описано ниже:

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

    Я настоятельно рекомендую вам прочесть эту статью, это поможет вам с легкостью ответить на все связанные с HashMap вопросы.

  3. Может ли элемент null быть добавлен в TreeSet or HashSet?

    Как видно из предыдущего ответа, в методе add() нет проверки на null. Также, HashMap позволяет один ключ null, следовательно, один элемент null может быть добавлен в HashSet.

    TreeSet работает по тому же принципу что и HashSet, но использует NavigableMap для хранения элементов

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

    NavigableMap это класс-наследник SortedMap, а SortedMap не позволяет использование ключей null. Следовательно, и TreeMap не поддерживает хранение элементов типа null. Если вы попробуете добавить null в TreeSet, получите исключение NullPointerException.

Вопросы про словари

  1. Почему мы используем словари (Map)? Какие основные классы реализуют интерфейс Map?

    Словари — специальный тип коллекции, которая используется для хранения пар ключ/meaning. По этой причине он не является наследником интерфейса Collection. Словарь предоставляет методы для добавления пар ключ/meaning, удаления, поиска и перебора по предоставляемым словарем представлениям данных.

    Основные классы реализующие интерфейс Map: HashMap, Hashtable, EnumMap, IdentityHashMap, LinkedHashMap и Properties.

  2. What такое IdentityHashMap и WeakHashMap?

    IdentityHashMap похож на HashMap за одним исключением — для сравнения an objectов используется сравнение указателей на an objectы, если указатели не равны (указывают на an objectы лежащие по разным addressм), значит an objectы считаются различными.

    IdentityHashMap является довольно редко используемым. Хотя он реализует интерфейс Map, он нарушает один из основных принципов устройства Map, который требует использования метода equals() для сравнения an objectов.

    IdentityHashMap используется только в тех случаях, когда требуется сравнение an objectов по их addressм.

    WeakHashMap это реализация интерфейса Map, которая содержит слабые ссылки на элементы. То есть, если за пределами WeakHashMap не осталось ни одной ссылки на его элемент, этот элемент удаляется сборщиком мусора. Класс предназначен для использования с an objectми, у которых метод equals() проверяет идентичность an objectов с помощью оператора ==. После того How элемент будет удален сборщиком мусора, он уже не может быть восстановлен, и к большому удивлению программиста найти его в словаре больше не получится.

  3. Объясните что такое ConcurrentHashMap? Как оно работает?

    Взято с официальной documentации:
    Реализация словаря fully поддерживающая многопоточное добавление/удаление/поиск элементов. Данный класс следует тем же спецификациям что и Hashtable, и содержит методы соответствующие методам Hashtable. Однако, хотя все операции являются потокобезопасными, операция по выборке элементов не блокирует таблицу, и вообще нет возможности запретить весь доступ к таблице. Этот класс совместим с Hashtable во всем кроме вопросов многопоточной синхронизации.

  4. Как работает hashmap?

    Самый важный вопрос, который скорее всего будет задан на собеседовании программисту любого уровня. Вы должны хорошо разбираться в этой теме, и не только потому что это самый задаваемый вопрос, но и потому что понимание устройства hashmap позволяет вам легче разобраться в других особенностях работы коллекций.

    Ответ на этот вопрос очень обширный, и fully его можно прочесть в этой статье — How работает hashmap. А на данный момент просто запомните что HashMap работает на основе хэширования. Словарь, по определению, это an object который связывает ключи и значения. Для хранения таких структур, он использует внутренний класс Entry.

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

    Переменные key и value служат для хранения ключа и значения. А сами an objectы Entry лежат в массиве.

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

    Индекс нужного element в массиве вычисляется по хэш-codeу ключа. Больше информации можете получить по ссылке в начале ответа.

  5. Как создать хороший ключ для словаря?

    Следующий хороший вопрос, который обычно задают следом за вопросом о функционировании HashMap. Итак, главное ограничение — ключ должен быть таким, чтобы потом по нему можно было получить из словаря meaning. Иначе в его использовании просто нет смысла. Если вы понимаете How функционирует hashmap, вы знаете что его работа сильно зависит от методов hashCode() и equals() an objectов-ключей.

    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, identical keys equals()should return true when calling a method, and different ones should return false.

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

    You can read more at .

  6. What content views 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 should you use it HashMapand when should you use it TreeMap?

    HashMapthis is a very widely used class and you know it. So, I will limit myself to saying that it stores key/value pairs and 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 manner. The default is "natural sorting". 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)should not call ClassCastExceptionfor any k1and k2stored in the 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
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION