Home >Java >JavaInterview questions >Java high-frequency basic interview questions - collection framework part

Java high-frequency basic interview questions - collection framework part

王林
王林forward
2020-08-28 15:49:291850browse

Java high-frequency basic interview questions - collection framework part

1. The difference between ArrayList and Vector

(Recommendations for more interview questions: java interview questions and answers)

Both classes implement the List interface (the List interface inherits the Collection interface). They are both ordered collections, that is, the positions of the elements stored in these two collections are in order, which is equivalent to a dynamic array. , we can retrieve an element according to the position index number in the future, and the data in it is allowed to be repeated. This is the biggest difference from collections such as HashSet. Collections such as HashSet cannot retrieve elements by index number. , and no duplicate elements are allowed.

The difference between ArrayList and Vector mainly includes two aspects:

(1) Synchronicity:

Vector is thread-safe, that is to say, between its methods It is thread synchronized, while ArrayList is not thread safe, and its methods are thread asynchronous. If only one thread will access the collection, it is best to use ArrayList, because it does not consider thread safety and will be more efficient; if multiple threads will access the collection, it is best to use Vector, because we do not need to do it ourselves Think about and write thread-safe code again.

(2) Data growth:

ArrayList and Vector both have an initial capacity. When the number of elements stored in them exceeds the capacity, ArrayList and Vector need to be increased. Each time you want to increase the storage space, you don’t just add one storage unit, but add multiple storage units. The number of storage units added each time must achieve a certain balance between memory space utilization and program efficiency. .

Vector grows by twice its original size by default, while ArrayList’s growth strategy is not clearly specified in the document (from the source code, it is seen that it grows by 1.5 times its original size). Both ArrayList and Vector can set the initial space size, and Vector can also set the growth space size, while ArrayList does not provide a method for setting the growth space.

Summary: Vector increases by twice its original size, and ArrayList increases by 0.5 times its original size.

2. The difference between HashMap and Hashtable

HashMap is a lightweight implementation of Hashtable (non-thread-safe implementation). They both complete the Map interface. The main difference is that HashMap allows empty (null) ) Key value (key), due to non-thread safety, the efficiency is higher than Hashtable when only one thread accesses it.

HashMap allows null to be used as the key or value of an entry, but Hashtable does not.

HashMap has removed the contains method of Hashtable and changed it to containsvalue and containsKey. Because the contains method is easily misleading.

Hashtable inherits from the Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2.

The biggest difference is that Hashtable's method is Synchronized, but HashMap is not. When multiple threads access Hashtable, you do not need to synchronize its methods yourself, while HashMap must provide synchronization for it.

Regarding HashMap and HashTable, there are mainly three aspects.

(1) Historical reasons: Hashtable is based on the old Dictionary class, and HashMap is an implementation of the Map interface introduced in Java 1.2

(2) Synchronicity: Hashtable is thread-safe. That is to say, it is synchronous, and HashMap is an unsafe online program and is not synchronous

(3) Value: Only HashMap allows you to use a null value as the key or value of a table entry

(Learning video recommendation: java course)

3. The difference between List and Map?

One is a collection that stores single column data, and the other is a collection of keys and For a collection of double-column data such as values, the data stored in the List is in order and is allowed to be repeated; the data stored in the Map is not in order, its keys cannot be repeated, and its values ​​can be repeated.

4. Are List, Set, and Map inherited from the Collection interface?

List, Set are, but Map is not.

5. List, Map, and Set interfaces exist. What are the characteristics of each element when taking them?

(This kind of question compares the level of examination in two aspects: one is to truly understand the content, and the other is to have strong summary and presentation skills.)

First, List Similar to Set, they are both collections of single-column elements, so they have a common parent interface called Collection. Duplicate elements are not allowed in Set, that is, there cannot be two equal (note, not just the same) objects. That is, suppose there is an A object in the Set collection, and now I want to save a B object to the Set collection. But if the B object is equal to the A object, the B object will not be stored.

So, the add method of the Set collection has a boolean return value. When there is no element in the set, and the add method can successfully add the element, it will return true. When the set contains an element When equals equals elements, the add method cannot add the element at this time, and the return result is false. When Set takes elements, you cannot specify which number to take. You can only get all the elements through the Iterator interface, and then iterate through each element one by one.

List represents a collection in sequence. Note that it is not sorted by age, size, price, etc. When we call the add(Obje) method multiple times, the objects added each time are sorted in the order of first come, first served, just like the queue order for buying tickets at a train station. Sometimes, you can also jump in the queue, that is, call the add(intindex,Obj e) method to specify the storage location of the current object in the collection.

An object can be stored repeatedly in the 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 in the collection. An index variable is used to point to this object. When this object is added multiple times, it is equivalent to multiple indexes in the collection pointing to this object, as shown in Figure x. In addition to using the Iterator interface to obtain all elements of List and then iterating through each element one by one, you can also call get(index i) to clearly indicate which number to retrieve.

Map is different from List and Set. It is a double-column collection, which has a put method, which is defined as follows: put(obj key, obj value). Each time it is stored, a pair of key/value must be stored. Duplicate keys cannot be stored. The duplication rule is also based on equals comparison. The corresponding value can be obtained 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, the combination of all values, and the collection of Map.Entry objects composed of key and value.

List holds elements in a specific order and may have duplicate elements. Set cannot have duplicate elements and is sorted internally. Map saves key-value values, and value can have multiple values.

6. Tell us about the storage performance and characteristics of ArrayList, Vector, and LinkedList.

Both ArrayList and Vector use arrays to store data. The number of elements in this array is larger than the actual stored data to facilitate addition and insertion. Elements, they all allow indexing elements directly by serial number, but inserting elements involves memory operations such as array element movement, so indexing data is fast but inserting data is slow. Vector usually has worse performance than ArrayList due to its use of the synchronized method (thread safety). LinkedList uses a doubly linked list for storage. Indexing data by serial number requires forward or backward traversal, and the index becomes slower. However, when inserting data, you only need to record the items before and after this item, so the insertion speed is faster.

LinkedList is also thread-unsafe. LinkedList provides some methods so that LinkedList can be used as a stack and queue.

7. Remove duplicate elements from a Vector set

Vector newVector = new Vector();
For (int i=0;i<vector.size();i++)
{
Object obj = vector.get(i);
       if(!newVector.contains(obj);
             newVector.add(obj);
}

There is also a simple way to use Set that does not allow duplicate elements:

HashSetset = new HashSet(vector );

8. The difference between Collection and Collections.

Collection is the superior interface of the collection class. The interfaces that inherit it mainly include Set and List.

Collections is a helper class for the collection class. It provides a series of static methods to implement various Collection search, sorting, thread safety and other operations.

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

In Set The elements cannot be repeated. Whether the elements are repeated or not is determined using the equals() method. The difference between

== and equal is also a question that has failed in the exam. Let’s talk about it here: The

== operator is specially used to compare whether the values ​​​​of two variables are equal, that is, it is used to compare variables. Whether the values ​​stored in the corresponding memory are the same, to compare whether two basic types of data or two reference variables are equal, you can only use the == operator.

The equals method is used to compare whether the contents of two independent objects are the same, just like comparing whether the appearance of two people is the same. The two objects it compares are independent.

For example: two new statements create two objects, and then use the two variables a/b to point to one of the objects respectively. These are two different objects, and their first addresses are Different, that is, the values ​​stored in a and b are different, so the expression a==b will return false, and the contents of the two objects are the same, so the expression a.equals(b) will return true.

(Recommended related tutorials: java introductory tutorial)

10. What collection classes do you know? Main method?

The most commonly used collection classes are List and Map. Specific implementations of List include ArrayList and Vector, which are variable-sized lists and are more suitable for constructing, storing, and manipulating element lists of any type of object. List is suitable for accessing elements by numerical index.

Map provides a more general element storage method. The Map collection class is used to store pairs of elements (called "keys" and "values"), where each key maps to a value.

They all have methods of adding, deleting, modifying and checking.

For set, the general methods are add, remove, contains, etc.

For map, the general methods are put, remove, contains, etc.

The List class will have a method like get(int index) because it can take elements in order, but there is no method like get(int index) in the set class. Both List and set can iterate out all elements. When iterating, you must first obtain an iterator object. Therefore, both the set and list classes have an iterator method for returning the iterator object. Map can return three collections, one returns a collection of all keys, the other returns a collection of all values, and the third returns a collection of EntrySet objects composed of keys and values. Map also has a get method, and the parameter is key. The return value is the value corresponding to the key. This is free to play, and it is not the ability to test the method. There will be prompts during the programming process. Just talk about the usage based on the differences between the three.

The above is the detailed content of Java high-frequency basic interview questions - collection framework part. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete