This java collection framework interview questions, let you easily get the interviewer!

Write catalog title here

Collection frame

1. The difference between ArrayList and Vector.

Both classes implement List interface (Collection List interface extends the interface), they are ordered set of
engagement, i.e., the position of these two elements is stored in the collection are sequential, corresponding to a dynamic array I
can later withdrawn position by an element index, and wherein the data is allowed to repeat, which is
the maximum at a different set of HashSet and the like, and the like can not be set HashSet index number to retrieve
the The element of, is also not allowed to have duplicate elements (the original question has nothing to do with hashset, but in order to
clarify the function of ArrayList and Vector, we use the contrast method, which is more conducive to explaining the problem). Then I will
talk about the difference between ArrayList and Vector, which mainly includes two aspects.
Synchronization :
Vector is thread-safe, which means that its methods are thread-synchronized, while ArrayList is not thread
-safe, and its methods are not thread-synchronized. If only one thread can access the collection, it is
best to use ArrayList, because it does not consider thread safety, and the efficiency will be higher; if there are multiple threads accessing
the collection, it is best to use Vector, because we do not need ourselves Then consider and write thread-safe
code.
Remarks: For Vector&ArrayList, Hashtable&HashMap, keep in mind the issue of thread safety.
Remember that Vector and Hashtable are old and provided by java. They are thread-safe
. ArrayList and HashMap are only provided when java2. It is not thread safe. So I
Let's talk about the old ones first.
Data growth :
ArrayList and Vector both have an initial capacity size. When the number of elements stored in them exceeds
the capacity, the storage space of ArrayList and Vector needs to be increased
. Add one storage unit, but add multiple storage units. The number of storage units added each time
must strike a balance between memory space utilization and program efficiency. The default growth of Vector is twice the original, and
the growth strategy of ArrayList is not clearly specified in the document (seeing from the source code is 1.5
times the original ). Both ArrayList and Vector can set the initial space size, Vector can also set the growth
space size, but ArrayList does not provide a method to set the growth space.
Summary: That is, Vector doubles the original size, and ArrayList doubles the original size.

2. Talk about the storage performance and characteristics of ArrayList, Vector, LinkedList.

Both ArrayList and Vector use arrays to store data. The number of elements in this array is greater than the actual data stored in
order to add and insert elements. Both of them allow direct indexing of elements by sequence number, but inserting elements involves
memory operations such as array element movement, so indexing Data is fast but slow to insert data. Vector uses the
synchronized method (thread safety).
ArrayList performance difference is usually more, and LinkedList implemented using a doubly linked list is stored, indexed by serial number, the number of
data need to be traversed forward or backward, but only before and after the record of this can insert the data item, it is inserted
into the faster .
ArrayList is fast when searching, and LinkedList has advantages when inserting and deleting.

3. What is the difference between fail-fast and fail-safe?

The safety failure of Iterator is based on copying the underlying collection, so it is not affected by the modification on the source collection.
All the collection classes in the java.util package fail fast, while
all the classes in the java.util.concurrent package fail safely. Iterators that fail fast will throw
ConcurrentModificationException, while iterators that fail safely will never throw such an
exception.

4. The data structure of hashmap.

In the Java programming language, there are two basic structures. One is an array and the other is an analog pointer
(reference). All data structures can be constructed using these two basic structures, and the hashmap is no
exception. Hashmap is actually a combination of an array and a linked list (in the data structure, it is generally called "linked
list hash")
enter image description here

5. What is the working principle of HashMap?

HashMap in Java stores elements in the form of key-value pairs. HashMap needs
a hash function, which uses hashCode() and equals() methods to add and retrieve
elements to/from the collection . When the put() method is called, HashMap will calculate the hash value of the key, and then
store the key- value pair in the appropriate index in the collection. If the key already exists, the value will be updated to the new value.
Some important characteristics of HashMap are its capacity, load factor and
threshold resizing.

6. When will Hashmap expand?

When the number of elements in the hashmap exceeds the array size loadFactor, the array will be expanded.
The default value of loadFactor is 0.75, that is, by default, the array size is 16, so when the
number of elements in the hashmap exceeds 160.75=12 when the size of the extended array is put 216 = 32,
i.e., doubled, and then re-calculates the position of each element in the array, which is a performance-consuming operation
for, so if we have predicted elements hashmap The number of preset elements can effectively
improve the performance of hashmap. For example, we have 1000 elements new HashMap(1000),
but theoretically new HashMap(1024) is more suitable, but annegu said above, even if it
is 1000, hashmap will automatically set it to 1024. But new HashMap(1024) is
not more suitable, because 0.75*1000 <1000, that is to say, in order to make 0.75 * size> 1000, we
must use new HashMap(2048) in this way to be the most suitable, considering the problem of & and Avoid the
problem of resizing .

7. What are the characteristics of the three interfaces of List, Map, and Set when accessing elements?

Such questions are free to play: These questions compare the test level, and have two levels: one is to truly understand
the content, and the other is to have a strong summarization and presentation ability. If you understand but the expression is not clear, it
is equivalent to not understanding to others .
First of all, List and Set have similarities. They are a collection of single-column elements. Therefore, they have a common
parent interface called Collection. Duplicate elements are not allowed in Set. The so-called duplication means that there cannot be two
objects that are equal (note that it is not just the same). That is, suppose there is an A object in the
Set collection . Now I want to store another in the Set collection. The B object, but the equals of the B object and the A object are equal, the B
object cannot be stored. Therefore, the add method of the Set collection has a boolean return value. When there is
no element in the collection , the add method can successfully join the If the element is an element, it returns true. When the set contains
an element equal to an element equals, the add method cannot add the element at this time, and the return result is false.
When taking elements in Set, there is no way to say which number to take. You can only obtain all the elements through the Iterator interface, and then traverse
each element one by one .
List represents a prioritized collection. Note that it is not sorted by age, size, or price.
When we call the add(Obj e) method multiple times, the objects added each time
are sorted in the order of first-come, first-come, just like the train station has a queue for buying tickets . Sometimes, you can also jump in the queue, that is, call the add(int index, Obj e)
method to specify the storage location of the current object in the collection. An object can be stored repeatedly in List,
Each time the add method is called, the object is inserted into the collection once. In fact, the object
itself is not stored in the collection, but an index variable is used to point to the object in the collection. When the object is added
multiple times When, it means that there are multiple indexes pointing to this object in the collection, as shown in Figure x. In addition
to getting all the elements of List through the Iterator interface, and then traversing each element one by one, you can also call
get(index i) to specify which number to take.
Map is different from List and Set. It is a collection of two columns. There is a put method, which is defined as follows:
put(obj key, obj value), each time a key/value pair is stored, duplicate
keys cannot be stored . This repeated rule also compares equals according to equals. Get the corresponding
value according to the key , that is, the return value of get(Object key) is the value corresponding to the key. In addition, you can also get
the combination of all keys, all the combinations of value, and
the collection of Map.Entry objects composed of key and value .
List holds elements in a specific order and can have duplicate elements. Set cannot have duplicate elements, internal sorting.
Map stores the key-value value, and the value can be multiple values.
HashSet is stored according to a certain calculation method of the hashcode value, rather than directly according to
the size of the hashCode value. For example, "abc" —> 78, "def" —> 62, "xyz" —> 65 in
The storage order in hashSet is not 62, 65, 78. Thanks to a previous student named Cui Jian who raised these questions.
Finally , I explained it clearly to him by viewing the source code. See how many of the trainees can understand the source code.
LinkedHashSet is stored in the order of insertion. What is the purpose of the hashcode method of the stored object
? Students think about it! The hashset set compares whether two objects are equal, first to see whether the hashcode method is
equal, and then to see whether the equals method is equal. Insert two new students into the HashSet, look at
the size of the HashSet, and look at the size after implementing the hashcode and equals methods.
The same object can be added multiple times in Vector. Adding elements to the collection is equivalent to
connecting the target object with a rope in the collection . It can't be added many times to HashSet.

8. The elements in the Set cannot be repeated, so what method is used to distinguish the repeated or not? Is it to use == or

equals()? What is the difference between them?
The elements in the Set cannot be repeated . Whether the elements are repeated or not is judged by the equals() method.
The equals() and == methods determine whether the reference value points to the same object equals() is overridden in the class, in order
to return the true value when the content and type of the two separate objects match.

9. Two objects have the same value (x.equals(y) == true), but they can have different hash codes. Is this sentence correct?

Correct. If objects are to be stored in HashSet or HashMap, and their equals are equal, then
their hashcode values ​​must be equal.
If it is not to be kept in HashSet or HashMap, it has nothing to do with the hashcode, and then
waiting hashcode range is possible, for example arrayList stored object hashcode do not realize, when
of course, we have no reason not to achieve, usually to achieve of.

10. What is the difference between heap and stack.

Java memory is divided into two categories, one is stack memory and the other is heap memory. Stack memory means that
when the program enters a method , a piece of private storage space is allocated for this method to store local variables inside the method.
When the method ends, the stack allocated to this method will be released. The variables will be released accordingly.
The heap is a different memory from the stack. It is generally used to store data that is not placed in the current method stack. For example,
objects created with new are placed in the heap, so it will not disappear with the end of the method. After the local
variables in the method are modified with final, they are placed in the heap instead of the stack.

11. What are the basic interfaces of the Java collection framework?

The collection interface specifies a set of objects called elements. Each specific implementation class of the collection class interface can
choose to store and sort the elements in its own way. Some collection classes allow duplicate keys, some do not.
Java collection classes provide a set of well-designed interfaces and classes that support operations on a set of objects. The
most basic interfaces in the Java collection class are:
Collection: Represents a group of objects, each of which is its child element.
Set: A Collection that does not contain repeated elements.
List: An ordered collection, and can contain repeated elements.
Map: An object that can map a key to a value, and the key cannot be repeated.

12. What is the difference between HashSet and TreeSet?

HashSet is implemented by a hash table, so its elements are unordered. add(),
remove(), contains()
TreeSet is implemented by a tree structure, the elements in it are ordered. Therefore,
the time complexity of add(), remove() and contains() methods is O(logn).

13. What is the underlying implementation of HashSet?

By looking at the source code, we know that the implementation of HashSet depends on HashMap, and the value of HashSet is stored
in HashMap. In the construction of HashSet, a HashMap object is initialized.
HashSet does not allow repeated values. Therefore, the value of HashSet is stored in the
HashMap as the key of the HashMap, and false is returned when the stored value already exists.

14. How does LinkedHashMap work?

LinkedHashMap is also implemented based on HashMap. The difference is that it defines an Entry
header. This header is not placed in the Table, it is additionally independent.
LinkedHashMap inherits Entry in hashMap and adds two attributes Entry
before, after, and header to form a doubly linked list to realize
sorting by insertion order or access order . LinkedHashMap defines the sorting mode accessOrder, which is a boolean variable
. For access order, it is true; for insertion order, it is false. In general, it is not necessary to specify the
sorting mode, and its iteration order is the insertion order by default.

15. Why does the collection class not implement the Cloneable and Serializable interfaces?

The semantics and meaning of cloning or serialization are related to the specific implementation.
Therefore, the specific implementation of the collection class should decide how to be cloned or serialized.

16. What is an Iterator?

The Iterator interface provides many methods for iterating over collection elements. Each collection class contains
iteration methods that can return an iterator instance. The iterator can delete the elements of the underlying collection during the iterative process, but it
can not directly call the remove(Object Obj) of the collection to delete it. It can be deleted through the remove() method of the iterator
.

17. What is the difference between Iterator and ListIterator?

The differences are listed below:
Iterator can be used to traverse Set and List collections, but ListIterator can only be used to traverse List.
Iterator can only traverse the collection forward, and ListIterator can both forward and backward.
ListIterator implements the Iterator interface and contains other functions, such as adding elements, replacing
elements, obtaining the index of the previous and next elements, and so on.

18. What is the difference between Array and ArrayList? When should you use Array instead of

ArrayList?
Array can contain basic types and object types, and ArrayList can only contain object types.
The size of Array is fixed, and the size of ArrayList changes dynamically.
When ArrayList deals with fixed-size basic data types, this method is relatively slow.

19. What are the best practices for the Java collection framework?

If the size of the elements is fixed and can be known in advance, we should use Array instead of ArrayList.
Some collection classes allow you to specify the initial capacity. Therefore, if we can estimate the number of stored elements, we can set the initial capacity to avoid recalculating the hash value or expanding the capacity. For type safety, generics are always used for readability and robustness reasons. At the same time, using generics can also avoid ClassCastException at runtime.  Using the immutable class provided by the JDK as the key of the Map can avoid implementing hashCode() and equals() methods for our own classes.
 Interface is better than implementation when programming.
 If the underlying collection is actually empty, return a collection or array with a length of 0 instead of null.

20. The elements in a set cannot be repeated, so what method is used to distinguish whether they are repeated or not? Should I use == or equals()? What is the difference between them?

The elements in the Set cannot be repeated, so use the iterator() method to distinguish repeated or not. equals() is to judge
whether two Sets are equal.
equals() and == methods determine whether the reference value points to the same object equals() is overridden in the class, so that
when the content and type of two separate objects match, Return true value
##21. What are the Comparable and Comparator interfaces? List their differences.
Java provides a Comparable interface that contains only a compareTo() method. This method can
sort two objects individually. Specifically, it returns negative numbers, 0, and positive numbers to indicate that the input object is less than, equal to, or greater than the
existing object.
Java provides a Compare() and equals() Comparator interface.
The compare() method is used to sort the two input parameters, returning a negative number, 0, and a positive number indicating that the first parameter is less
than, equal to, and greater than the second parameter. The equals() method requires an object as a parameter, which is used to determine whether the input
parameter is equal to the comparator.
This method returns true only when the input parameter is also a comparator and the input parameter is the same as the sort result of the current comparator.

22. The difference between Collection and Collections.

Collection is the superior interface of the collection class. The inheritance and its interfaces are mainly set and list.
The collections class is a helper class for the collection class. It provides a series of static methods for searching
, sorting, thread-safety and other operations on various collections .

Guess you like

Origin blog.csdn.net/Java_Yhua/article/details/110988646