The data structures behind the collections framework

The data structures behind the collections framework

1. What is the collection framework?

In java, there is a set of ready-made data structures, such as sequence list, linked list, queue, stack, priority queue, hash table, etc., which are encapsulated into corresponding interfaces/classes for programmers to use directly, only need to create related The object can be used without realizing its internal structure.
A collection is to place multiple elements in a unit for adding, deleting, modifying, querying, storing and managing these elements. For example, a deck of playing cards (a set of cards), an address book (a set of mapping relationships between names and phone numbers), and so on.

The picture below is very important! ! ! Its commonly used interfaces and classes need to be kept in mind! !
insert image description here
insert image description here

Because the map interface does not implement the Iterable interface, how to traverse the elements in it?

		Map<Integer,String> map = new HashMap();
        map.put(1,"jack");
        map.put(2,"tom");
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        // 使用迭代器进行遍历 ,增强 for同理
        Iterator<Map.Entry<Integer, String>> iterator = entries.iterator();
        while (iterator.hasNext()) {
    
    
            Map.Entry<Integer, String> entry =  iterator.next();
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

Taking HashMap as an example above, you can call its entrySet() method to encapsulate each <k,v> key-value pair in the map into a Map.Entry<Integer, String> object, because it is received by the Set interface, so You can use iterator or for-each() to traverse, and each entry object has getKey() and getValue() methods to get the key value and value value respectively.

Basic Relationships (Simple Version)
insert image description here

2. Collection interface

Generally, the interface or class that implements the Collection interface is used to accept the objects of the specific implementation class. As can be seen from the above figure, the Collection interface is a series of interfaces and the parent interface of the class. There are few internal implementation methods, so some cannot be called. Common methods that subclasses have.

(1) Specify the object type in the corresponding collection through generics (note: the type passed in here can only be a reference type, if it is a basic data type, it should be specified by its wrapper class)
		Collection<String> collection1 = new ArrayList();
        collection1.add("haha");
        collection1.add("world");
        Collection<Integer> collection2 = new ArrayList();
        collection2.add(1);
        collection2.add(2);
        //collection2.add("hh");// 这里会报错,不符合传入的指定类型Integer
(2), the use of common methods of Collection
method effect
void clear() remove all elements from a collection
boolean isEmpty() Determine if a set has no elements, commonly known as an empty set
boolean remove(Object e) If element e is present in the set, remove one of them
boolean add(E e) put element e into the set
int size() Returns the number of elements in the collection
Object[] toArray() Returns an array with all elements in the collection

Note: In the last Object[] toArray() method, an array of Object[] type is returned. The underlying method is to take out the elements in the collection one by one, convert them into Object objects, and store them to be returned. , and finally returns an array of type Object[]. If it is directly converted to an array of type String[], a type conversion exception will be thrown.
insert image description here
Because there is no guarantee that each element in the array is converted to String, but only the entirety is converted to an array of type String[], so if you have to convert, you need to traverse the returned results and convert them one by one to String type, and finally assign it to an array of String[] type. It is not recommended to convert the array type as a whole in java.

		Object[] objects = collection1.toArray();
        String[] strings = new String[objects.length];
        for (int i = 0; i < objects.length; i++) {
    
    
            strings[i] = (String)objects[i];// 一个一个转,但是没啥必要
        }

3. Map interface

Data is stored in the form of < k, v > key-value pairs, where the key value is unique, and each key value can correspond to its corresponding value value. Different key values ​​can correspond to the same value.
HashMap: When storing an element, according to its key value, call the internal hashCode function to find the location where the element should be placed, so the elements in the hash table are not stored in the order in which they are stored.

(1), the use of common methods of Map
method effect
V get(Object k) Find the corresponding v according to the specified k
V getOrDefault(Object k, V defaultValue) Find the corresponding v according to the specified k, if not found, return the default value
V put(K key, V value) Put the specified kv into the Map
boolean containsKey(Object key) Determine whether the key is included
boolean containsValue(Object value) Determine if it contains value
Set<Map.Entry<K, V>> entrySet() return all key-value pairs
boolean isEmpty() Determine if it is empty
int size() Returns the number of key-value pairs
		HashMap<Integer, String> map = new HashMap<>();

        // put()
        map.put(1,"张飞");// 这里的 key 值唯一
        map.put(1,"宋江");// 如果二次插入的 key 值之前有,则替换其 value值
        map.put(2,"Jack");
        System.out.println(map);

        // get()
        String s1 = map.get(1);// 返回 宋江
        String s3 = map.getOrDefault(3,"三团");// 未找到,返回 三团

        // entrySet()
        // 该方法返回一个 Set<Map.Entry<Integer, String>> 对象
        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        for (Map.Entry<Integer, String> entry : entries) {
    
    
            // 通过 entry.getKey() 和 entry.getValue() 获取每个entry对应的 k, v值
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

insert image description here

4, the specific implementation class

insert image description here
The above is the introductory knowledge of the collection~

Guess you like

Origin blog.csdn.net/qq_45792749/article/details/123664748