Three sets of Java basic knowledge points

1. Collections in Java

        The hierarchy of the Collection framework. The java.util package contains all the classes and interfaces of the Collection framework. Core elements of the Java collections framework - interfaces, implementations, aggregation operations, and algorithms.

        Java's collection class is defined in the java.utilpackage, supports generics, and mainly provides three kinds of collection classes, including List, Setand Map. Java collections use uniform Iteratortraversal and try not to use legacy interfaces.

Collection Hierarchy in Java

1、List

        List is the most basic kind of collection: it is an ordered list. In practical applications, we need to add and delete an ordered list of elements, and we use it most ArrayList.

2、Map

        Map, a data structure of a key-value mapping table, is used to efficiently find values ​​(elements) through keys.

3、Set

        If we only need to store unique keys and do not need to store mapped values, then we can use Set.

4、Queue

        queue( Queue) is a frequently used collection. QueueIn fact, it implements a first-in, first-out (FIFO: First In First Out) ordered list.

5、Iterator

        This pattern of traversing a collection through an Iterator object is called an iterator. The benefit of using iterators is that the caller always traverses the various collection types in a uniform manner, without having to concern themselves with their internal storage structures.

        If we write a collection class ourselves and want to use the for each loop, we only need to meet the following conditions:

        (1) The collection class implements the Iterable interface, which requires an Iterator object to be returned;
        (2) Iterates the internal data of the collection with the Iterator object.

6、Properties

        It's very simple to Propertiesread the config file with. The default Java configuration file is .propertiesthe extension, each line is key=valuerepresented by , and the #beginning of the class is a comment. The following is a typical configuration file:

# setting.properties

last_open_file=/data/hello.txt
auto_save_interval=60

        Inside Properties is essentially a Hashtable. 

        Can be read from a file or from an ar package.

7、Collections

        CollectionsIt is a tool class provided by JDK, which is also located in the java.utilpackage. It provides a series of static methods that make it easier to manipulate various collections.

        create empty collection;

        Create a single-element collection;

        create immutable collections;

        Sort/Shuffle etc.

        Turn a thread-unsafe collection into a thread-safe collection

8. Examples

1. Q: Do you know those legacy classes and interfaces?

Answer:  Legacy classes: Hashtable, Vector, Stack; should not continue to be used.

        Legacy interface: Enumeration<E>: Superseded by Iterator<E>.

2. Q: What is the difference between Set and Map?

Answer:  Set contains only values, while Map contains keys and values.
        Sets contain unique values, while Maps can contain unique keys with duplicate values.
        A Set contains a single null value, while a Map can contain a single null key and n null values.


3. Question: Do List, Set, Map inherit from Collection interface?

Answer:  List, Set is, Map is not

4. Q: What is the main difference between an array and a collection?

Answer: (1) Arrays are always of fixed size, that is, users cannot increase or decrease the length of the array according to their own needs or at runtime, but in Collections, the size can be dynamically changed as needed.
        (2) Arrays can only store objects of the same or similar types, but heterogeneous objects can be stored in Collections.
        (3) Array does not provide ready-made methods such as sorting and searching, but Collection includes ready-made methods.

5. Q: What is the difference between Iterator and ListIterator?

Answer: Iterator traverses elements forward only, while ListIterator traverses elements forward and backward.

6. Q: What is the difference between ConcurrentHashMap, HashMap and HashTable?

Answer: (1) The packages are different java.util.HashMap; java.util.concurrent.ConcurrentHashMap;

        (2) ConcurrentHashMap implements ConcurrentMap and Serializable interface. This class is a thread-safe HashMap. 

        (3) Hashtable inherits from Dictionary class, the underlying array + linked list implementation, neither key nor value can be null, thread-safe, the way to achieve thread-safety is to lock the entire HashTable when modifying data, which is inefficient, and ConcurrentHashMap has done related optimizations .

7. Q: The elements in the Set cannot be repeated, how to ensure that they are not repeated?

Answer: The elements in the Set cannot be repeated. When putting, the hash and the value will be compared. If the hash does not exist, it is allowed to be stored. If the hash code value is the same and the equals judgment is equal, it means that the element already exists, but it does not exist; if the hash code value is the same, and the equals judgment is not equal, it means that the element does not exist and exists;

8. Q: What is the difference between ArrayList and LinkedList?

Answer: (1) ArrayList uses dynamic array; LinkedList uses doubly linked list.

       (2) ArrayList is more suitable for storage and faster to read; LinkedList is faster to operate.

        (3) ArrayList provides random access; LinkedList does not provide random access.

9. Q: What is the difference between HashMap and TreeMap?

Answer: HashMap remains unordered while TreeMap remains ascending.
        HashMap is implemented by hash table, and TreeMap is implemented by Tree structure.
        HashMap can be sorted by Key or value, and TreeMap can be sorted by Key.
        HashMap may contain null keys with multiple null values, while TreeMap cannot contain null keys but can have multiple null values.

10. Q: How to synchronize ArrayList?

答:(1)Collections.synchronizedList

        (2) Using CopyOnWriteArrayList, CopyOnWriteArrayList is a thread-safe version of ArrayList.

import java.util.*;  
public class SyncronizeArrayList {  
    public static void main(String args[]) {  
        // Non Synchronized ArrayList   
        List<String> fruitList = new ArrayList<String>();  
  
        fruitList.add("Mango");  
        fruitList.add("Banana");  
        fruitList.add("Apple");  
        fruitList.add("Strawberry");  
        fruitList.add("Pineapple");  
  
        // 同步 ArrayList 
        furitList = Collections.synchronizedList(fruitList);  
  
        // 使用同步块来避免非确定性行为  
        synchronized (fruitList) {  
            Iterator<String> itr = fruitList.iterator();  
            while (itr.hasNext()) {  
                System.out.println(itr.next());  
            }  
        }  
    }  
}  

11. Q: How to make Java ArrayList read-only? 

​Answer : Get java ArrayList Read-only by calling Collections.unmodifiableCollection() method. When we define an ArrayList as read-only, we cannot make any modifications to the collection through the add(), remove() or set() methods.

12. Question: Which of the following statements is incorrect? 

    (A) java.util.List can be used to store a set of ordered elements stored by index position.
    (B) Java objects and basic types of data are allowed to be stored in the java.util.Set collection.
    (C) When a thread executes the sleep() method of the Thread class to start sleeping, the occupied object lock will not be released.
    (D) When the Java virtual machine initializes a class, if its parent class has not been initialized, its parent class will be initialized first.

Answer: B; Only Java objects are allowed to be stored in the java.util.Set collection, and data of Java basic types is not allowed.

Guess you like

Origin blog.csdn.net/bashendixie5/article/details/123598818
Recommended