Collections - Java

collection introduction

A collection can be regarded as an enhanced array, which can put elements of the same type in a unified position. Collections can be divided into single-column collections and double-column collections.

The general interface of a single-column collection is: Collection, and the interfaces inherited from Collection are: List and Set. The elements in List can be repeated, and the elements in Set cannot be repeated. List has two implementation classes: ArrayList and LinkedList. Set has two implementation classes: HashSet and TreeSet.

The general interface of the double-column collection is: Map, and the two implementation classes of Map are: HashMap and TreeMap.

iterator

Iterator

方法:
Iterator it = list.iterator();
it.hasNext();
it.next();
删除:
it.remove(); 用来删除该迭代器指向的元素。

Get the iterator object, and use the iterator object to iterate data, that is, data traversal.

package day01;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class Demo01 {
    
    
    public static void main(String[] args) {
    
    
        Collection<String> coll = new ArrayList<>();
        coll.add("1");
        coll.add("2");
        coll.add("3");
        coll.add("4");
        coll.add("5");

//        获取迭代器对象 Iterator.利用Iterator的对象方法,hasNext判断是否有下一个,
//        使用next取出下一个元素
        Iterator<String> iter = coll.iterator();
        while (iter.hasNext()) {
    
    
            System.out.println(iter.next());
        }
    }
}

When using next, the iterator takes the currently pointed element and points to the next element.

Set collection

概述:
    Set集合特点:
    可以去除重复
    存取顺序不一致
    没有带索引的办法,所以不能使用普通for循环遍历,也不能通过索引来获取,删除Set集合里面的元素。

Set集合练习
    存储字符串并遍历。

Basic use of set collections. The set collection cannot be repeated, if the elements are repeated, only one of them will be kept.

Inconsistent access sequence. Set has no index, and ordinary for loops cannot be used.

 private static void demo02() {
    
    
        Set<String> set = new HashSet<>();
        set.add("Hello");
        set.add("world");
        set.add("Hello");

//        增强for循环
        for (String s : set) {
    
    
            System.out.println(s);
        }
//        迭代器循环
        Iterator<String> iterator = set.iterator();
        while (iterator.hasNext()) {
    
    
            System.out.println(iterator.next());
        }
    }

HashSet

底层使用哈希表
重写HashCode 和 equals方法。

TreeSet

TreeSet集合特点
	不包含重复元素的集合
	没有带索引的方法
	可以将元素按照规则进行排序
	底层使用红黑树
	必须给定排序规则。

natural sort

Natural sorting needs to implement the comparable interface and rewrite the compareTo method in it. this is the object that is currently being sorted, and o is the object already in the collection. If the return value is < 0, it means that this should be on the left, otherwise it should be on the left On the right, if it is 0, it means that the object is duplicated, and no operation is performed.

 private static void demo04() {
    
    
        Student s1 = new Student("陈歌", 18);
        Student s2 = new Student("王文", 19);
        Student s3 = new Student("双双", 18);
        Student s4 = new Student("之言", 33);
        TreeSet<Student> set = new TreeSet<>();
//        存入学生到TreeSet集合
        set.add(s1);
        set.add(s2);
        set.add(s3);
        set.add(s4);

        for (Student s : set) {
    
    
            System.out.print(s.getName() + " ");
            System.out.println(s.getAge());
        }

    }
package day01;

//写一个学生类,并使用TreeSet集合来存储5个学生
//按照自定义的规则进行排序,自然排序
public class Student implements Comparable<Student> {
    
    
    private String name;
    private Integer age;

    public Student(){
    
    

    }

    public Student(String name,Integer age){
    
    
        this.name = name;
        this.age = age;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public Integer getAge() {
    
    
        return age;
    }

    public void setAge(Integer age) {
    
    
        this.age = age;
    }

    @Override
    public int compareTo(Student o) {
    
    
        int result = this.getAge() - o.getAge();
        result = result == 0 ? this.getName().compareTo(o.getName()) : result;
        return result;
    }
}

comparator sort

Comparator sorting is not written in a Student object, but in a collection, and a comparator can be written in a parameterized method in the collection. By overriding the compare method.

 private static void demo05() {
    
    
        Teacher t1 = new Teacher("陈歌", 18);
        Teacher t2 = new Teacher("犯花痴", 24);
        Teacher t3 = new Teacher("风速", 20);
        Teacher t4 = new Teacher("白色", 16);
        TreeSet<Teacher> set = new TreeSet<>(new Comparator<Teacher>() {
    
    
            @Override
            public int compare(Teacher o1, Teacher o2) {
    
    
//                此时的o1就是即将进行排序的,o2是集合中已经排好序的。
                int result = o1.getAge() - o2.getAge();
                result = result == 0 ? o1.getName().compareTo(o2.getName()) : result;
                return result;
            }
        });
        set.add(t1);
        set.add(t2);
        set.add(t3);
        set.add(t4);

        for (Teacher t : set) {
    
    
            System.out.print(t.getName() + " ");
            System.out.println(t.getAge());
        }

    }

Summary of the two comparison methods:

Natural sorting: The custom class implements the Comparable interface, rewrites the compareTo method, and sorts according to the return value.

Comparator sorting: When creating a TreeSet, pass the Compartor's comparator object, rewrite the compare method, and sort according to the return value.

Rules for return values:

If the return value < 0, it means that the currently stored value is a smaller value, and it is stored on the left.

= 0, the current stored value is repeated.

The return value is a positive number, and the current stored value is a larger value, which is stored on the right.

binary tree

insert image description here

binary search tree

Balance cannot be maintained and performance is not guaranteed.
insert image description here

balanced binary tree

After adding nodes, check to see if the balance of the binary tree is broken. If the balance of the ring is broken, left or right rotation is required to re-balance.

left-handed

insert image description here

Right-handed

insert image description here

red black tree

The underlying principle of TreeSet is a red-black tree.

The red-black tree is not highly balanced, and its balance is realized according to the red-black rules.

rule:

每个节点是红色或黑色,根节点必须是黑色。

每个叶节点是黑色的

不能出现两个红色节点相连。

对每一个节点,到其所有后代叶结点的简单路径上,均包含相同数目的黑色节点。

insert image description here

Map collection

interface Map<K,V> K: the data type of the key, V: the data type of the value.

Keys cannot be repeated, but values ​​can be.

Key-value pairs are also called Entry objects.

insert image description here

   private static void demo06() {
    
    
//        Map的使用
        /*
        put(K key,V value)
        remove(Object key)
        void clear()
        boolean containsKey(Object key)
        boolean isEmpty()
        int size()
         */

        Map<String, String> map = new HashMap<>();
        map.put("1002", "王雯雯"); 
        map.remove("1001");
        map.clear();
        map.put("1001", "赵新龙");
        boolean flag = map.containsKey("1001");
        System.out.println(flag);
        System.out.println(map.size());
        System.out.println(map);
    }

Iterate over key-value pairs

The first way: (obtain value according to all keys)

private static void demo06() {
    
    
        Map<String, String> map = new HashMap<>();
        map.put("itheima01", "a");
        map.put("itheima02", "b");
        map.put("itheima03", "c");
        map.put("itheima04", "d");
        map.put("itheima05", "e");

//            获取所有的键
        Set<String> set = map.keySet();
        for (String key : set) {
    
    
            String value = map.get(key);
            System.out.println(key + " : " + value);
        }

    }

The second way: get each key-value pair

//        获取所有的entry
        Set<Map.Entry<String, String>> entries = map.entrySet();
        for (Map.Entry<String,String> entry : entries){
    
    
            System.out.println(entry.getKey() + " " + entry.getValue());
        }

Guess you like

Origin blog.csdn.net/qq_45022687/article/details/122583104