Summary of Java Collection Class fundamentals

Source: Internet
Author: User
Tags comparable serialization

1. What are the basic interfaces of the Java Collection Class framework?

Reference answer

The collection class interface specifies a set of objects called elements. Each specific implementation class of the collection class interface can optionally save and sort the elements in its own way. Some collection classes allow duplicate keys, some are not allowed.
The Java Collection class provides a set of well-designed interfaces and classes that support the manipulation of a set of objects. The most basic interfaces within the Java Collection class are:
Collection: Represents a set of objects, each of which is its child element.
Set: A collection that does not contain duplicate elements.
List: A sequence of collection, and can contain repeating elements.
Map: You can map a key (key) to an object with a value, and the key cannot be duplicated.

2. Why does the collection class not implement cloneable and serializable interfaces?

Reference answer

The semantics and meanings of cloning (cloning) or serialization (serialization) are related to specific implementations. Therefore, the specific implementation of the collection class should determine how to be cloned or serialized.

3. What is an iterator (Iterator)?

Reference answer

The iterator interface provides many ways to iterate over a collection element. Each collection class contains an instance of the iterator that can be returned
Iterative methods. Iterators can delete elements of the underlying collection during the iteration, but they cannot call the collection's remove (Object Obj) directly, and can be removed through the Remove () method of the iterator.

4. What is the difference between iterator and listiterator?

Reference answer

Their differences are listed below:
The iterator can be used to traverse the set and list collection, but Listiterator can only traverse the list.
Iterator to a collection can only be forward traversal, listiterator can be either forward or back.
Listiterator implements the iterator interface and includes other functions such as adding elements, replacing elements, getting the index of the previous and subsequent elements, and so on.

5. What is the difference between a fast failure (fail-fast) and a security failure (fail-safe)?

Reference answer

Iterator's security failure is based on a copy of the underlying collection, so it is not affected by modifications on the source collection. All of the collection classes below the Java.util package are fast failures, and all classes under the Java.util.concurrent package fail safely. A fast-failing iterator throws an concurrentmodificationexception exception, and a security-failed iterator never throws such an exception.

6. How does the HashMap in Java work?

Reference answer

HashMap in Java is a key-value pair (Key-value) that stores elements. HashMap requires a hash function that uses the hashcode () and Equals () methods to add and retrieve elements to the collection/collection. When the put () method is called, HashMap calculates the hash value of the key and stores the key-value pair on the appropriate index in the collection. If the key already exists, value is updated to the new value. Some of the important features of HashMap are its capacity (capacity), load factor (payload factor) and expansion limit (threshold resizing).

7. Where is the importance of the hashcode () and Equals () methods?

Reference answer

HashMap in Java uses the hashcode () and Equals () methods to determine the index of key-value pairs, which are used when the values are obtained by key. If these two methods are not implemented correctly, two different keys may have the same hash value, and therefore may be considered equal by the collection. Moreover, these two methods are also used to discover duplicate elements. So the realization of these two methods is very important to the accuracy and correctness of hashmap.

8. What is the difference between HashMap and Hashtable?

Reference answer

HashMap and Hashtable both implement the map interface, so many features are very similar. However, they have the following different points:
HashMap allows keys and values to be null, while Hashtable does not allow keys or values to be null.
The Hashtable is synchronous, while HashMap is not. Therefore, HashMap is more suitable for single-threaded environments, while Hashtable is suitable for multithreaded environments.
HashMap provides a collection of keys that can be used for iteration, so HashMap is a quick failure. On the other hand, Hashtable provides an enumeration of keys (enumeration).
Hashtable is generally considered to be a legacy class.

Application Scenario Analysis:

HashMap and Hashtable:hashmap removed the Hashtable contains method, but added the Containsvalue () and ContainsKey () methods. Hashtable synchronous, and HashMap is not synchronous, the efficiency is higher than Hashtable. HashMap allows null key values, while Hashtable is not allowed.

HashMap: Applies to inserting, deleting, and locating elements in map.

Treemap: For traversing keys (key) in natural order or in a custom order.

9. What is the difference between an array and a list (ArrayList)? When should I use array instead of ArrayList?

Reference answer

The different points of the array and ArrayList are listed below:
An array can contain primitive types and object types, and ArrayList can only contain object types.
The array size is fixed, and the size of the ArrayList is dynamically changing.
ArrayList provides more methods and features, such as AddAll (), RemoveAll (), iterator (), and so on.
For basic type data, the collection uses automatic boxing to reduce the coding effort. However, this approach is relatively slow when dealing with fixed-size base data types.

10. What is the difference between ArrayList and LinkedList?

Reference answer

ArrayList and LinkedList all implement the list interface, they have the following different points:
ArrayList is an index-based data interface, and its underlying is an array. It can randomly access elements with an O (1) time complexity. In contrast, LinkedList stores its data as a list of elements, with each element linked to its previous and subsequent elements, in which case the time complexity of finding an element is O (n).
It is faster to insert, add, and delete than Arraylist,linkedlist, because when an element is added anywhere in the collection, it is not necessary to recalculate the size as an array or to update the index.
LinkedList accounts for more memory than ArrayList because LinkedList stores two references for each node, one to the previous element, and one to the next.
You can also refer to ArrayList vs. LinkedList.

Application Scenario Analysis:

When ArrayList is required for this access to the data, LinkedList is used when multiple additions to the data are needed to delete the modifications.

11. What are the comparable and comparator interfaces? List the differences between them.

Reference answer

Java provides a comparable interface that contains only one CompareTo () method. This method can be used to sort two objects in a single order. Specifically, it returns a negative number, 0, a positive number to indicate that an existing object is less than, equal to, greater than the input object.
Java provides a comparator interface that contains two methods of compare () and Equals (). The Compare () method is used to sort two input parameters, return a negative number, 0, and a positive number indicates that the first parameter is less than, equal to, greater than the second argument. The Equals () method requires an object as a parameter that determines whether the input parameters are equal to comparator. This method returns true only if the input parameter is also a comparator and the input parameter is the same as the current comparator's ordering result.

12. What is the Java priority queue?

Reference answer

Priorityqueue is an unbounded queue based on a priority heap whose elements are sorted in natural order (natural orders). At the time of creation, we can provide it with a comparator that is responsible for ordering the elements. Priorityqueue do not allow null values because they do not have a natural order, or they do not have any associated comparators. Finally, Priorityqueue is not thread-safe, and the time complexity of the queue and the queue is O (log (n)).

13. Do you know the big O symbol (big-o notation)? Can you give examples of different data structures?

Reference answer

The large o symbol describes the size of the algorithm or an incremental upper bound when the elements in the data structure increase.
The large o symbol can also be used to describe other behaviors, such as memory consumption. Because the collection class is actually a data structure, we generally use the large O notation to choose the best implementation based on time, memory, and performance. The large o symbol provides a good indication of the performance of a large amount of data.

14. How do I weigh an unordered array or an ordered array?

Reference answer

The greatest benefit of an ordered array is that the time complexity of the lookup is O (log n), and the unordered array is O (n). The disadvantage of an ordered array is that the time complexity of the insert operation is O (n), because elements with large values need to be moved backward to make the new element space. Instead, the insertion time complexity of an unordered array is constant O (1).

15. What are the best practices for the Java Collection Class framework?

Reference answer

It is important for performance to correctly select the type of collection to use according to the needs of the application, such as: if the number of elements is fixed and can be known beforehand, 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 elements stored, we can set the initial capacity to avoid recalculation of hash values or expansion.
For type safety, the reason for readability and robustness is always to use generics. Also, using generics avoids classcastexception at run time.
Using the invariant Class (immutable Class) provided by the JDK as the key to the map avoids implementing the hashcode () and Equals () methods for our own classes.
The interface is better than the implementation when programming.
The underlying collection is actually empty, the return length is a collection of 0 or an array, do not return null.

16. What are the differences between enumeration interface and iterator interface?

Reference answer

The enumeration is twice times faster than iterator and consumes less memory at the same time. However, iterator is far more secure than enumeration because other threads are not able to modify objects in the collection that is being traversed by iterator. At the same time, iterator allows the caller to delete elements from the underlying collection, which is not possible for enumeration.

17. What is the difference between HashSet and TreeSet?

Reference answer

1.TreeSet is a two-fork tree (tree of red and black tree according to the structure), the data in the TreeSet is automatically sequenced, not allowed to put null values.

2.HashSet is a hash table implementation, the data in HashSet is unordered, can be put into null, but only a null, the values in both cannot be duplicated, such as the unique constraints in the database.

3.HashSet required to put the object must implement the Hashcode () method, put the object, is the Hashcode code as the identity, but with the same content of the string object, Hashcode is the same, so the contents cannot be duplicated. However, objects of the same class can be placed in different instances.

HashSet is implemented by a hash table, so its elements are unordered. The time complexity of the add (), remove (), contains () method is O (1).
On the other hand, TreeSet is implemented by a tree-shaped structure in which the elements are ordered. Therefore, the time complexity of the add (), remove (), contains () method is O (Logn).

Application Scenario Analysis:

HashSet is based on the hash algorithm, and its performance is usually better than treeset. For a set that is designed for quick lookups, we should usually use hashset, and we use treeset when we need to sort the functions.

18, the set frame, list,map,set have what specific implementation class, what is the difference?

Reference answer

1.List,set are inherited from the collection interface, map is not;

2.list features: elements are placed in order, elements can be repeated;

set Features: elements are not in order, elements are not repeatable, repeating elements will be overwritten, (note: Although the element is not placed in order, but the position of the element in the set is determined by the hashcode of the element, its position is actually fixed, add set Object must define the Equals () method;

In addition, the list supports a for loop, that is, through the subscript to traverse, you can also use an iterator, but set can only use iteration, because he is unordered, can not use subscript to get the desired value.

Comparison of 3.Set and list:

Set: The retrieval element is inefficient, the deletion and insertion efficiency is high, and insertions and deletions do not cause the element position to change.

List: And arrays, lists can grow dynamically, find elements efficiently, and insert deleted elements inefficiently because they cause other elements to change position.

4.map is suitable for storing data for key-value pairs.

5. Thread-Safe collection classes and non-thread-safe collection classes

LinkedList, ArrayList, hashset are non-thread-safe, vector is thread-safe;

HashMap is non-thread-safe, Hashtable is thread-safe;

StringBuilder is non-thread-safe and StringBuffer is thread-safe.

19. The difference between ArrayList and vector and the applicable scene

Reference Answer

The ArrayList has three methods of construction:

 Public ArrayList (int initialcapacity)// constructs an empty list with the specified initial capacity.      Public ArrayList ()// constructs an empty list with an initial capacity of 10.      Public extends e> c)// construct a list   of elements that contain the specified collection

Vector has four methods of construction:

 Public // constructs an empty vector using the specified initial capacity and the capacity increment equal to zero.      Public Vector (int//  constructs an empty vector, making its internal data array size, whose standard capacity increment is zero.      Public extends e> c)//  constructs a vector    that contains the elements in the specified collection (int  initialcapacity,int capacityincrement)// constructs an empty vector with the specified initial capacity and capacity increment

ArrayList and vectors are all implemented using arrays, and there are three differences:

1). Vector is multithreaded security, thread safety means that multithreaded access to the same code, will not produce an indeterminate result. And ArrayList is not, this can be seen from the source code, the method of the vector class has synchronized to decorate, so that the vector in efficiency can not be compared with ArrayList;

2). Two are all linear continuous spatial storage elements, but when space is low, two classes are incremented differently.

3). Vectors can set growth factors, and ArrayList cannot.

4). Vector is an old dynamic array that is thread-synchronized and inefficient, and is generally not in favor of use.

Applicable scenarios:

1.Vector is thread-synchronized, so it is thread-safe, and ArrayList is thread-asynchronous and insecure. If the thread security factors are not taken into account, the ArrayList efficiency is generally higher.

2. If the number of elements in the collection is greater than the length of the current collection array, it is advantageous to use a vector with a larger amount of data in the collection.

Summary of Java Collection Class fundamentals

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.