Collections in Java

Posted by jwilh on Sun, 02 Jan 2022 19:43:36 +0100

Single column collection

ArrayList

Variable array, default capacity 10. Automatically move the following elements after inserting them

Not thread safe

Vector

The main difference from ArrayList is that the thread of Vector is safe, and other usage methods are consistent with ArrayList

LinkedList

The bottom layer is realized by two-way linked list, and the memory space does not need to be continuous. The two address references at both ends of an element point to the previous and next element respectively, and the value is in the middle of the element.

Adding yuan Xu to the beginning and end of the linked list only requires the relevant reference address of an element in the linked list.

To insert an element in the middle, you only need to modify the reference address of the two elements

LinkedList adds, deletes and modifies elements very quickly, but random access is slow, because LinkedList needs to start from the first index

What is random access?

Gets the element in the list at the specified index position

 

Some special API s for LinkedList

list.addFirst()//Add element to first
list.addLast()//Add element to last
list.removeFirst()//Remove first element
list.removeLast()//Remove last element
list.pollFirst()//Pop up the first element, that is, remove the first element from the collection, and the return value is the first element
list.polllast()//Pop up the last element
list.pop()//Pop up linked list header element
list.pop()

Set set

HashSet

The bottom layer is implemented by HashMap, a non repeated Set set

HashSet set=new HashSet();
set.add(1);
set.add(2);
sout(set);
//The same element cannot be added to the collection

 

HashSet traversal:

1. for each traversal

        

for(Object obj:set){ sout(obj); }

2. Iterator

//Get an iterator object / / two methods in the iterator: 
//1. hasnext() determines whether there is a next element. It returns true but not false 
//2. next() gets the next element iterator iterator = set iterator(); 
while(tierator.hasnext())
{ 
Object obj=iterator.next();
 sout(next); 
}

 

TreeSet

Is a non repeating and sequential set

How does TreeSet keep order

Forced type conversion is carried out inside TreeSet to convert it into a Comparable (Interface) type. The size of two elements is compared through this comparator. Therefore, the elements placed in TreeSet must have an implementation method to implement the Comparable interface and sort through this comparator

TreeSet can specify a comparator when it is created

At this time, you do not need to inherit the comparable interface

public class TeacherComparator implements Comparator<Teacher>{//Generic type to be specified as Teacher
    public int compare(Teacher t1,Teacher t2){
        //code 
    }
}

//When creating a collection, a comparator object is passed in
TreeSet set = new TreeSet(new TeacherComparator);

 

LinkedHashSet

A HashSet that can maintain the insertion order of elements. It does not sort according to the rules, but the original order remains unchanged when inserting elements

Two column set

Store data in memory as key value pairs

What are key value pairs?

One ID corresponds to one value

Rules:

key cannot be repeated, but value can be repeated

HashMap

  1. All methods in the map interface are implemented
  2. Thread out of sync

//Create HsahMap object
HashMap map=new HashMap();
map.put(1,"First element");//The put() method assigns a value to the object
map.put(2,"Second element");

Working principle:

When new HashMap() is used, a new array will not be generated, but a space is opened up (the capacity of HashMap array is doubled when the capacity is expanded). A new array will be created only when the first element is added.

When adding an element, the hashcode will be calculated according to the key of the element, and the element in the array will be determined according to the hashcode.

When adding elements, if there are more than 8 linked lists, there are two cases

1. There are more than 8 elements in the linked list, but the length of the entire array does not exceed 64. At this time, the JVM will double and expand the array, and then recalculate the element address

2. If there are more than 8 elements in the linked list and the length exceeds 64, the whole linked list will be treed (red black tree). When there are less than 6 elements in a red black tree, it will be automatically converted to a linked list

3. When the array reaches the size specified by the load factor (0.75), it will be doubled and expanded. The maximum capacity is 2 ^ 30.

Notes to HashMap:

  1. The key cannot be repeated. If the key is the same, the value will be overwritten
  2. key can be any type, but this type needs to override equals and hashCode. Generally, String and int are used, and user-defined types are not used
  3. If the key is a basic type, it must be a wrapper class

Traversal of HashMap

Provides an API to traverse the Hash Map collection

1,entrySet

Set<map.Entry> set=map.entrySet();
for(Map.Entry entry:set){
    sout(entry.getKey()+":"+map.get(key));
}

2,keySet

Set<Integer> keys = map.keySet();
for(Integer key:keys){
    sout(key+":"+map.get(key));
}

3. If only value is traversed, use values()

Collection value=map.values();
for(Object obj:values){
    sout(obj);
}

TreeMap

Sequential map s are sorted by the key comparator. Commonly used String or basic types, which implement the Comparable interface

LinkedHashMap

A Map that can maintain the insertion order uses a two-way linked list internally to save the order of elements

Hashtable

And HashMap almost always, but threads are safe and inefficient.

ConcurrentHashMap

Thread is safe, but it does not use synchronized locks. It uses segmented locks and optional locks, which is more efficient than HashMap.

Topics: Java Eclipse JavaEE jar intellij-idea