Questions in this article:
General issues- What are collections in Java? List their advantages
- Tell us about the collection hierarchy
- Why don't collections inherit interfaces
Cloneable
andSerializable
? - Why
Map
doesn't the interface inherit the interfaceCollection
?
- Why do we use lists? What main classes implement the interface
List
? - How to convert an array of strings to
ArrayList
? - How to sort a list in reverse order?
- Why do we use sets? What main classes implement the interface
Set
? - How are elements stored in
HashSet
? - Can an element
null
be added toTreeSet
orHashSet
?
- Why do we use dictionaries? What main classes implement the interface
Map
? - What is
IdentityHashMap
andWeakHashMap
? - Explain what this is
ConcurrentHashMap
? How does it work? - How do dictionaries work?
- How to create a good dictionary key?
- What content views does the interface provide
Map
? - When should you use it
HashMap
and when should you use itTreeMap
?
- What are the differences between
Set
andList
? - What are the differences between
List
andMap
? - Name the differences between
HashMap
andHashTable?
- What are the differences between
Vector
andArrayList
? - What are the differences between
Iterator
andEnumeration
? - What are the differences between
HashMap
andHashSet
? - What are the differences between
Iterator
andListIterator
? - What are the differences between
TreeSet
andSortedSet
? - What are the differences between
ArrayList
andLinkedList
?
- How to make a collection read-only?
- How to make a thread-safe collection?
- Why isn't there a method
Iterator.add()
to add elements to a collection? - What ways are there to iterate over the elements of a list?
- How do you understand the iterator property to work
fail-fast
? - What's the difference between
fail-fast
andfail-safe
? - How to avoid
ConcurrentModificationException
while iterating through a collection? - What's happened
UnsupportedOperationException
? - Which collection classes give access to any element?
- What's happened
BlockingQueue
? - What is a queue and a stack, list the differences between them?
- What are interfaces
Comparable
andComparator
? - What are classes
Collections
andArrays
? - List of used literature
General issues
-
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
Vector
andHashTable
, but there was no frameworkCollection
. 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
-
Tell us about the hierarchy of collections?
As shown in the picture, the collections framework contains one top-level interface -
Collection
, from whichSet
,List
and are inheritedQueue
. Below we will look at many more classes contained in these three branches. Remember the interface titleCollection
, 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 inheritCollection
in the fourth question. -
Why don't collections inherit interfaces
Cloneable
andSerializable
?Well, the simplest answer is “because it’s not necessary.” The functionality is provided by interfaces
Cloneable
andSerializable
is simply not needed for collections.Another reason is that a subclass is not always needed
Cloneable
because 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.
-
Why
Map
doesn't the interface inherit the interfaceCollection
?A good answer to this question is “because they are incompatible.” The interface
Collection
describes the methodadd(Object o)
.Dictionaries cannot contain this method because they work with key/value pairs. Also, dictionaries have representations
keySet
thatvalueSet,
are not in collections.Due to these differences, an interface
Map
cannot inherit an interfaceCollection
, and is a separate branch of the hierarchy.
Questions about lists
-
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
List
areStack
,Vector
,ArrayList
andLinkedList
. For more detailed information on them, please refer to the documentation. -
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 -Collections
andArrays
.The class
Collections
provides static methods for operations on collections. Accordingly,Arrays
it 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);
-
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
-
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. -
Как хранятся элементы в
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
вопросы. -
Может ли элемент
null
быть добавлен вTreeSet
orHashSet
?Как видно из предыдущего ответа, в методе
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
.
Вопросы про словари
-
Почему мы используем словари (
Map
)? Какие основные классы реализуют интерфейсMap
?Словари — специальный тип коллекции, которая используется для хранения пар ключ/meaning. По этой причине он не является наследником интерфейса
Collection
. Словарь предоставляет методы для добавления пар ключ/meaning, удаления, поиска и перебора по предоставляемым словарем представлениям данных.Основные классы реализующие интерфейс
Map
:HashMap
,Hashtable
,EnumMap
,IdentityHashMap
,LinkedHashMap
иProperties
. -
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 элемент будет удален сборщиком мусора, он уже не может быть восстановлен, и к большому удивлению программиста найти его в словаре больше не получится. -
Объясните что такое
ConcurrentHashMap
? Как оно работает?Взято с официальной documentации:
Реализация словаря fully поддерживающая многопоточное добавление/удаление/поиск элементов. Данный класс следует тем же спецификациям что иHashtable
, и содержит методы соответствующие методамHashtable
. Однако, хотя все операции являются потокобезопасными, операция по выборке элементов не блокирует таблицу, и вообще нет возможности запретить весь доступ к таблице. Этот класс совместим сHashtable
во всем кроме вопросов многопоточной синхронизации. -
Как работает
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у ключа. Больше информации можете получить по ссылке в начале ответа.
-
Как создать хороший ключ для словаря?
Следующий хороший вопрос, который обычно задают следом за вопросом о функционировании
HashMap
. Итак, главное ограничение — ключ должен быть таким, чтобы потом по нему можно было получить из словаря meaning. Иначе в его использовании просто нет смысла. Если вы понимаете How функционируетhashmap
, вы знаете что его работа сильно зависит от методовhashCode()
иequals()
an objectов-ключей.As follows from the above, a good key should give the same one
hashCode
over and over again, no matter how many times it is requested. And also, identical keysequals()
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 .
-
What content views does the interface provide
Map
?The interface
Map
provides three views of the stored data:- set of all keys
- set of all values
- a set of objects
Entry
containing both a key and a value
You can navigate through them using iterators.
-
When should you use it
HashMap
and when should you use itTreeMap
?HashMap
this 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.TreeMap
this is a special varietyHashMap
. The difference is that the keysTreeMap
are stored in an orderly manner. The default is "natural sorting". You can override sorting by providing an instance of the classComparator
, the methodcompare
of 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 callClassCastException
for anyk1
andk2
stored 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 typeInteger
), the methodput(Object key, Object value)
should callClassCastException
.
GO TO FULL VERSION