Java collection plus source code analysis

Introduce

  1. Collections and arrays are structures that can store multiple data, referred to as Java containers for short
  2. Features of array storage data:
    1. Once the array is initialized, the length of the array is determined
    2. Once the array is defined, the data type that can store the elements is determined
  3. Disadvantages of storing data in an array:
    1. Immutable length
    2. The methods provided in the array are limited, which is inconvenient for operations such as adding and deleting, and the efficiency is not high
    3. It is difficult to obtain the number of valid elements in the array
    4. Unable to meet disorderly and non-repetitive needs

One, Java collection framework

Collection interface: single-column collection, storing objects one by one

​ List interface: ordered, repeatable data (can be understood as a dynamic array)

​ ArrayList、LinkedHashSet、Vector

​ Set interface: Unordered, non-repeatable data (can be understood as a set in high school mathematics)

​ HashSet、LinkedHashSet、TreeSet

Map interface: two-column collection, storing a pair of (key-value) data (can be understood as a function)

​ HashMap、LinkedHashMap、TreeMap、HashTable、Properties

Two, Collection interface method

Looking at the Collection interface, we can see that there are 15 abstract methods for the implementation class to implement, 13 of them are explained in detail below


1 boolean add(E e)	向集合中添加元素,只能添加引用类型,不能添加基本类型
    
2 boolean addAll(Collection c)	将形参集合的元素添加到当前集合
    
3 void clear()	删除当前集合所有元素
    
4 boolean comtains(Object obj)	会调用obj对象所在类的equals方法,判断形参传入集合中的值是否在当前集合内
    
5 boolean contains(Collection coll)	判断形参coll的元素是否都在当前集合内
    
6 boolean equals(Object o)	判断当前集合和形参集合元素是否相等
    
7 int hashCode()	返回当前集合的hashCode值
    
8 boolean isEmpty()		判断当前集合是否为空
   
9 boolean remove(Object obj)		从当前集合删除obj元素
    
10 boolean removeAll(Collection coll)	从当前集合删除coll集合的所有元素
    
11 boolean retainAll(Collection coll) 	求两个集合的交集,并返回给当前集合
    
12 int size()		返回当前集合的长度
    
13 Object[] toArray() 		将当前集合转换为数组

Three, iterator interface

The Iterator object is called an iterator, which is mainly used to traverse the elements in the Collection collection, and it can also delete elements in the collection while traversing

Iterator only applies to collection traversal

The collection object will get a brand new iterator object every time the iterator() method is called, and the default cursor is before the first element of the collection

Collection coll = new ArrayList();
Iterator iterator = coll.iterator();

//遍历集合
while(iterator.hasNext()){
    
    
    iterator.next();
}

hasNext()   判断是否还有下一个元素
next()   指针下移、下移后将集合位置上的元素返回

Four, Collection sub-interface 1: List

List Commonly used implementation classes for interfaces are:ArrayList LinkedList Vector

Similarities and differences:

​ Same: All three classes implement the List interface

ArrayList As the main implementation class of List, thread is not safe, efficient, and the bottom layer uses Object[] storage
LinkedList The bottom layer uses a doubly linked list to store, frequently add, and delete efficiently
Vector As an ancient implementation class of List, thread safety, low efficiency, and Object[] storage at the bottom

Common methods of the List interface

void add(int index,Object ele)	在index位置插入ele元素

boolean addAll(int index,Collection eles)	从index位置开始将eles中的所有元素添加进来
    
Object get(int index)	获取index位置的元素
    
int indexOf(Object obj)		返回obj第一次出现的索引
    
int lastIndexOf(Object obj)		返回obj在当前集合最后一次出现的索引
    
Object remove(int index)	移除index位置的元素,并返回该元素
    
Object set(int index,Object obj)	设置index位置的元素为obj
    
list subList(int fromIndex,int toIndex)		返回从fromIndex到toIndex的子集合	

List traversal (three ways)

ArrayList list = new ArrayList();
list.add(123);
list.add("asd");

//方式一:Iterator方式
Iterator iterator = list.iterator();
while(iterator.hasNext()){
    
    
    iterator.next();
}
//方式二:增强for循环
for(Object obj : list){
    
    
    System.out.println(obj);
}
//方式三:普通for循环
for(int i = 0; i < list.size ; i++){
    
    
    System.out.println(list.get(i));
}

ArrayList source code analysis:

ArrayList arr = new ArrayList();	//底层创建长度为10的Object[]数组

arr.add(123);	//elementDate[0] = 123
...
arr.add(11);	
//如果此次添加元素导致底层elementDate数组容量不够,则扩容,默认情况下扩容为原来的1.5倍,同时将原数组的元素复制到新数组中
int newCapacity = oldCapacity + (oldCapacity >> 1);
elementData = Arrays.copyOf(elementData, newCapacity);

ArrayList arr = new ArrayList();//底层并没有创建长度为10的数组
arr.add(123);	//第一次调用add方法时,才创建长度为10的数组
后续和7之前一样
    
总结:
    7类似于饿汉式、8类似于懒汉式,节省内存

Five, Collection sub-interface 2: Set

The Set interface is a sub-interface of the Collection interface. It does not provide additional methods . All methods declared by Collection are used.

Set collections are not allowed to contain the same elements

1. Understanding of Set

1.1 Disorder

The stored elements are not added in the order of the array index at the bottom, but are determined according to the hash value of the array

1.2, non-repeatability

1.3, the process of adding elements to the set

Step 1: Add element a to the hashSet. First call the hashCode method of the class where a is located to calculate the hash value, and then use this hash value to calculate the index value of the element stored in the array through a certain algorithm.

Step 2: After obtaining the index value, judge whether there is an element at the position, if there is no element at this position, the addition is successful

​ If there is an element at this position, first compare a and the hash value of the element at this position

​ If the hash value is different, the element a is added successfully

Step 3: If the hash values ​​are the same, call the equals method of the class where a is, and pass other elements into the formal parameters of the equals method

​ If the method returns true, element a failed to add

​ If the method returns false, the addition is successful (stored in a linked list)

2、treeSet

1. The elements added to the treeSet must be objects of the same class (so that the size can be compared)

Two, two sorting methods

​ Natural sorting (implement Comparable interface)

​ The criterion for comparing two objects with the same is no longer equals, but the compareTo method returns 0

​ Custom sort

​ The criterion for comparing whether two objects are equal is not equals, but

Six, Map interface

1. Frame structure of Map interface

|------Map: Store the data of Key-value pairs

​ |------HashMap: As the main implementation class of Map; thread is not safe; high efficiency

| ------ LinkedHashMap

​ |------TreeMap: can be sorted (sorted by key)

​ |------Hashtable: as an ancient implementation class of Map; thread-safe; low efficiency

​ |------Properties: commonly used to process configuration files; key-value pairs are all String types

The underlying implementation principle of HashMap?

2. Understanding of key-value

① Key in Map: Unordered, non-repeatable (stored with set) The class where it is located must override the equals method and hashCode method (for HashMap)

② Value in Map: Unordered, repeatable (stored in Collection) The equals method of the class should be rewritten (for HashMap)

③ A key-value pair constitutes an Entry object (stored with set)

​ The key-value pair put in put is actually stored in the Entry object. Entry has two attributes, key and value

​ Entry is disordered and not repeatable

3. The underlying implementation principle of HashMap

以JDK7说明
    
HashMap map = new HashMap();	实例化以后,底层创建了长度为16的数组Entry[] table
map.put(key,value);		
首先调用key所在类的hashCode方法,计算key的哈希值,此哈希值经过某种算法计算后,得到key在Entry[]中的存放位置
如果此位置数据为空,则键值对添加成功
    如果此位置数据不为空(意味着此位置存放一个或多个数据(链表存储)),比较当前key和这些数据的哈希值,
    	如果key的哈希值与已经存在的数据局哈希值都不相同,则键值对添加成功
    	如果key的哈希值与已经存在的某个key的哈希值相同,则调用key所在类的equal方法
    		返回true,用value去替换已经存在key的value值
    		返回false,则键值对添加成功
默认扩容方式为原来的2倍,并且赋值过来
    
87的不同点
    1new时,底层并没有创建长度为16的数组
    2 jdk8底层的数组是 Node[],而非Entry[]
    3 首次调用put方法时,底层创建长度为16的数组
    4 JDK8底层使用 数组+链表+红黑树(当数组的某个索引位置上以链表形式存在的数据个数>8且当前数组长度>64,此时索引位置上的所有数据改为使用红黑树存储)

4. Common methods in the Map interface

V put(K key,V value)	向map中添加数据
  
V remove(Object key)	通过指定key移除键值对
    
void clear()	清空map集合
    
Object get(Object key)		通过key获取指定value
    
Boolean containsKey(Object key)		是否包含指定的key
    
Boolean containsValue(Object value)		是否包含指定的value
    
int size() 		返回map键值对的个数
    
Boolean isEmpty()	判断map是否为空
    
Boolean equals(Object obj)	判断两个map是否相等

5. Map traversal

        //遍历所有key
        Set keySet = map.keySet();
        Iterator iterator = keySet.iterator();
        while(iterator.hasNext()){
    
    
            System.out.println(iterator.next());
        }

        //遍历所有value
        Collection values = map.values();
        Iterator iterator1 = values.iterator();
        while(iterator1.hasNext()){
    
    
            System.out.println(iterator1.next());
        }

        //遍历所有键值对
        Set set = map.entrySet();
        for (Object o : set){
    
    
            Map.Entry entry = (Map.Entry) o;
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

Seven, Collection tools

Collections is a tool class that can manipulate Set, List, and Map

reverse(List)	反转List中元素的顺序
    
shuffle(List)	对List集合中的元素进行随机排序
    
sort(List)		根据元素的自然排序对List集合元素进行升序排序
    
sort(List,Comparator)	根据指定的Comparator产生的顺序对List进行排序
    
swap(List,int,int)		将指定List集合中的i处元素和j处元素进行交换
    
int frequency(Collection Object)	返回指定元素出现的次数
    
void copy(List dest,List src)		将原集合复制带目标集合

Guess you like

Origin blog.csdn.net/weixin_45321793/article/details/110096891