- 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
Questions about the differences between different collections
-
What are the differences between
Set
andList
?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 elementsnull
, while a set can contain only one. -
What are the differences between
List
andMap
?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.
-
What are the differences between
HashMap
andHashTable
?There are several differences between
HashMap
andHashTable
in Java:HashTable
thread safeHashMap
notHashTable
cannot contain elementsnull
, whileHashMap
it can contain one keynull
and any number of valuesnull
- The third key difference between them is that the iterator y
HashMap
, unlike the enumeratorHashTable
, works according to the principlefail-fast
(throws an exception for any data inconsistency)
-
What are the differences between
Vector
andArrayList
?Let's note some differences:
- All methods
Vector
are thread-safe, but yArrayList
is not. Vector
this is a deprecated class added in the first release of the JDK.ArrayList
appeared in JDK 1.2, along with the rest of the framework classesCollection
- By default,
Vector
it doubles its size when the memory allocated for the elements runs out.ArrayList
increases its size by only half
- All methods
-
What are the differences between
Iterator
andEnumeration
?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 classIterator
does 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()
matchesIterator.hasNext()
andEnumeration.nextElement()
matchesIterator.next()
, etc.
- There are iterators that allow you to remove elements from your collection during iteration, using the
-
What are the differences between
HashMap
andHashSet
?HashMap
is a collection of key/value pairs, whileHashSet
it is an ordered collection of unique elements. And that's it, no more explanation needed. -
What are the differences between
Iterator
andListIterator
?There are three differences:
Iterator
can be used to iterate over elements ofSet
,List
and Map . In contrast,ListIterator
it can only be used to iterate over the elements of a collection.List
Iterator
allows you to iterate over elements in only one direction, using thenext()
. WhereasListIterator
it allows you to iterate over the list in both directions, using the methodsnext()
andprevious()
- With ,
ListIterator
you can modify the list by adding/removing elements using theadd()
and methodsremove()
.Iterator
does not support this functionality
-
What are the differences between TreeSet and SortedSet?
SortedSet
is an interface implemented by the classTreeSet
. That's all! - What are the differences between
ArrayList
andLinkedList
?LinkedList
stores elements in a doubly linked list, whileArrayList
storing them in an array that can dynamically change in sizeLinkedList
supports 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.ArrayList
on 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.LinkedList
requires 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 theArrayList
elements simply go in order
And more questions
-
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.
-
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.
-
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 methodadd()
must be arranged differently. -
What are the ways to iterate over the elements of a list?
There are 4 ways:
- Loop with iterator
- Cycle
for
- Extended for loop
- Cycle
while
-
How do you understand the iterator property to work
fail-fast
?An iterator
fail-fast
throws 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. -
What's the difference between
fail-fast
andfail-safe
?In contrast
fail-fast
, iteratorsfail-safe
don'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
CopyOnWriteArrayList
view iterator are examples of iterators .keySet
ConcurrentHashMap
fail-safe
-
How to avoid
ConcurrentModificationException
while 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 usingList
, you can takeListIterator
. 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
ConcurrentHashMap
andCopyOnWriteArrayList
. 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 block
synchronized
Please note that the last two options will have a negative impact on performance.
- If you are using JDK 1.5 or later, the
-
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()
-
Which collection classes allow access to any element?
Classes
ArrayList
,HashMap
,TreeMap
,Hashtable
allow access to any element. -
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 (
null
orfalse
, 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 .
-
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
Regardless of the order of addition/removal, the head of the queue is the element that will be removed when theCollection
, 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.remove()
or methods are calledpoll()
. Also note thatStack
bothVector
are 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.
-
What are interfaces
Comparable
andComparator
?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
,TreeMap
etc. In order to sort elements, a class must implement interfacesComparator
orComparable
. That is why wrapper classes likeInteger
,Double
andString
implement theComparable
. The interfaceComparable
helps keep the sorting natural, whileComparator
allowing 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
Comparator
describes a methodint 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 interfaceComparator
, the whole point of which is that it can compare these class objectsT
, it is no longer needed for anything.An interface
Comparable
describes a methodint 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. - What are classes
Collections
andArrays
?Classes
Collections
areArrays
special 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. - 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.
GO TO FULL VERSION