Questions in this article:
General issues- What are collections in Java? List their benefits
- Tell us about the hierarchy of collections
- Why don't collections inherit interfaces
Cloneable
andSerializable
? - Why
Map
doesn't an interface inherit interfaceCollection
?
- Why do we use lists? What are the main classes that 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 are the main classes that implement the interface
Set
? - How are elements stored in
HashSet
? - Can an element
null
be added toTreeSet
orHashSet
?
- Why do we use dictionaries? What are the main classes that implement the interface
Map
? - What is
IdentityHashMap
andWeakHashMap
? - Explain what is
ConcurrentHashMap
? How does it work? - How do dictionaries work?
- How to create a good dictionary key?
- What kind of content representations does the interface provide
Map
? - When to use
HashMap
and whenTreeMap
?
- What are the differences between
Set
andList
? - What are the differences between
List
andMap
? - List 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 collection thread-safe?
- Why isn't there a method
Iterator.add()
to add elements to a collection? - What are the ways 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 over a collection? - What is
UnsupportedOperationException
? - Which collection classes give access to any element?
- What is
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 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
Vector
andHashTable
, but there was noCollection
. 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
-
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
. The reason why he does not inheritCollection
, we will analyze in the fourth question. -
Why don't collections inherit interfaces
Cloneable
andSerializable
?Well, the simplest answer is "because you don't have to." The functionality provided by interfaces
Cloneable
isSerializable
simply not needed for collections.Another reason is that a subclass is not always needed,
Cloneable
because 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.
-
Why
Map
doesn't an interface inherit 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 operate on key/value pairs. Also, dictionaries have representations
keySet
thatvalueSet,
don't exist 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 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
List
areStack
,Vector
,ArrayList
andLinkedList
. For more information on them, refer to the documentation. -
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 -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 an 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 are the main classes that implement the interface
Set
?It models a mathematical set, from set theory. The interface
Set
is similar toList
, 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 setshashCode()
; 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 interface
Collection
The main classes that implement the interface
Set
areEnumSet
,HashSet
,LinkedHashSet
andTreeSet
. If you want to learn more, read the relevant sections of the Java documentation. -
How are elements stored in
HashSet
?As you already know,
HashMap
stores key/value pairs, and the keys must be unique.HashSet
uses this featureHashMap
to ensure the uniqueness of its elements. In the classHashSet
, 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
HashMap
questions with ease. -
Can an element
null
be added toTreeSet
orHashSet
?As you can see from the previous answer,
add()
there is no check fornull
. Also,HashMap
allows one keynull
, hence one elementnull
can be added toHashSet
.TreeSet
works on the same principle asHashSet
, but usesNavigableMap
to store elementsprivate transient NavigableMap<E,Object> m; private static final Object PRESENT = new Object();
NavigableMap
it is a derived classSortedMap
andSortedMap
does not allow the use of keysnull
. Therefore, andTreeMap
does not support storing elements of typenull
. If you try to addnull в TreeSet
, you will get an exceptionNullPointerException
.
Questions about dictionaries
-
Why do we use dictionaries (
Map
)? What are the main classes that implement the interfaceMap
?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
Map
are:HashMap
,Hashtable
,EnumMap
,IdentityHashMap
,LinkedHashMap
andProperties
. -
What is
IdentityHashMap
andWeakHashMap
?IdentityHashMap
similar toHashMap
with 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.IdentityHashMap
is quite rarely used. Although it implements an interfaceMap
, it violates one of the device's fundamental principlesMap
, which requires the use of a methodequals()
to compare objects.IdentityHashMap
is used only when it is required to compare objects by their addresses.WeakHashMap
is an implementation of an interfaceMap
that contains weak references to elements.WeakHashMap
That 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 methodequals()
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. -
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 asHashtable
, and contains methods corresponding to those ofHashtable
. 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 withHashtable
everything except multi-threaded synchronization issues. -
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
hashmap
allows 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
HashMap
works based on hashing. A dictionary, by definition, is an object that associates keys and values. To store such structures, it uses the inner classEntry
.static class Entry implements Map.Entry { final K key; V value; Entry next; final int hash; ...//Еще много codeа тут }
Variables
key
andvalue
are used to store the key and value. And the objects themselvesEntry
are 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.
-
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 functionshashmap
, you know that its operation is heavily dependent on methodshashCode()
andequals()
key objects.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, 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 .
-
What kind of content representations 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 to use
HashMap
and whenTreeMap
?HashMap
it'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.TreeMap
this is a special varietyHashMap
. The difference is that the keysTreeMap
are stored in an orderly fashion. The default is "natural sort". 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)
must not callClassCastException
for anyk1
andk2
stored 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 typeInteger
), the methodput(Object key, Object value)
should callClassCastException
.
GO TO FULL VERSION