Overview of Java single-column collections

Java Collection System

Collection

Collection is the top-level implementation of a single-column collection. It is an interface and provides the following methods

Method name Description
boolean add(E e) Add element
boolean remove(Object o) Remove the specified element from the collection
void clear() Clear the elements in the collection
boolean contains(Object o) Determine whether the specified element exists in the collection
boolean isEmpty() Determine whether the collection is empty
int size() The length of the collection, which is the number of elements in the collection

Collection traversal method

  1. Traverse through the iterator , the collection calls the iterator method to get an Iteratora object, the iterator provides the following methods
  2. By enhancing the for loop

for (element data type variable name: array/collection object name) { loop body;}

Method name Description
boolean hasNext() Determine whether there is the next element in the set
element next() Get the elements of the collection

List collection

List is still an interface, providing a more detailed interface

List collection features :

  • Indexed
  • Can store duplicate elements
  • A unique method for accessing ordered
    List collections
Method name description
void add(int index,E element) Insert the specified element at the specified position in this collection
E remove(int index) Delete the element at the specified index and return the deleted element
E set(int index,E element) Modify the element at the specified index and return the modified element
E get(int index) Returns the element at the specified index

Introduction to ListIterator

  • Obtained by the listIterator() method of the List collection, so it is a unique iterator of the List collection
  • A list iterator that allows the programmer to traverse in either direction, modify the list during iteration, and get the current position of the iterator in the list

Concurrent modification exception

  • The reason

    ​ In the process of iterator traversal, the elements in the collection are modified through the collection object, causing the iterator to obtain the elements to determine the expected modified value and the actual modified value are inconsistent, and then there will be: ConcurrentModificationException

  • Solution

    ​ Use the for loop to traverse, and then use the collection object to do the corresponding operation


Specific implementation of List collection

  1. ArrayList
  2. LinkedList

Features:
ArrayList:

  • The bottom layer is implemented by an array
  • Fast query
  • Slow to add and delete

LinkedList:

  • The bottom layer is implemented by a linked list
  • Slow query
  • Add and delete fast

LinkedList

Overview : Like the ArrayList collection, it is the specific implementation of List

Unique method

Method name Description
public void addFirst(E e) Insert the specified element at the beginning of the list
public void addLast(E e) Append the specified element to the end of this list
public E getFirst() Returns the first element in this list
public E getLast() Returns the last element in this list
public E removeFirst() Remove from this list and return the first element
public E removeLast() Remove from this list and return the last element

Set collection

set collection is an interface

set collection features:

  • Unordered access to elements
  • No index, only through iterator and enhanced for traversal
  • Cannot store duplicate elements

Hash value

  • About hash value is a value of type int JDK calculated according to the object address or number or string

  • How to get the hash value

    ​ Public int hashCode() in the Object class: returns the hash code value of the object

  • Features of hash value

    • The hash value returned by calling the hashCode() method multiple times for the same object is the same
    • By default, the hash values ​​of different objects are different. The hashCode() method can be rewritten to make the hash value of different objects the same

HashSet

Features of HashSet collection

  • The underlying data structure is a hash table
  • The iterative order of the collection is not guaranteed, that is to say, the order of elements may be inconsistent with the storage of the collection
  • There is no method with index, so it can only be traversed through iterator or enhanced for loop
  • Since the Set interface is implemented, the set cannot store duplicate elements

The principle of HashSet collection to ensure the uniqueness of elements

​ 1. Calculate the storage location based on the hash value of the object

  • If there is no element at the current position, store it directly
  • If there is an element at the current position, go to the second step

​ 2. Compare the hash value of the element of the current element with the existing element

  • If the hash value is different, store the current element
  • If the hash values ​​are the same, go to the third step

​ 3. Compare the contents of two elements through the equals() method

  • If the content is not the same, store the current element

  • If the content is the same, the current element is not stored

    Illustration:

Insert picture description here
Hash table

Insert picture description here

LinkedHashSet

LinkedHashSet collection features

  • The Set interface implemented by the hash table and the linked list has a predictable iteration order
  • The order of the elements is guaranteed by the linked list, which means that the storage and retrieval order of the elements is the same
  • The element is guaranteed to be unique by the hash table, which means that there are no duplicate elements

TreeSet

  • The elements are ordered and can be sorted according to certain rules, and the specific sorting method depends on the construction method
    • TreeSet(): Sort according to the natural ordering of its elements
    • TreeSet(Comparator comparator): Sort according to the specified comparator
  • There is no method with index, so you can't use ordinary for loop to traverse
  • Since it is a Set collection, it does not contain a collection of repeated elements

chestnut

package cn.dreamyi.demo1;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class StudentTest {
    
    
    public static void main(String[] args) {
    
    

        /**
         * List集合 元素有顺序 有索引的方法 元素可重复
         *      ArrayList 底层采用数组实现 容易查询 不易大量增删
         *      LinkedList底层采用链表实现 容易增删 不易大量查询
         *
         * Set集合 元素无序、没有索引、不能重复
         *      TreeSet 具有排序功能 无序
         *      HashSet 底层采用哈希表实现 无序 且唯一性
         *      LinkedHashSet 采用链表和哈希表实现 具有有序和元素不重复特点
         */

        /**
         * 案例需求
         *
         * - 用TreeSet集合存储多个学生信息(姓名,语文成绩,数学成绩),并遍历该集合
         * - 要求:按照总分从高到低出现
         */
        TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
    
    
            @Override
            public int compare(Student o1, Student o2) {
    
    
                int i = o1.getAllScore() - o2.getAllScore();
                i = i==0? o1.getChinese() - o2.getChinese(): i;
                i = i==0? o1.getName().compareTo(o2.getName()) : i;
                return i;
            }
        });

        Student stu1 = new Student("zhangsan", 96, 98);
        Student stu2 = new Student("wangwu", 94, 98);
        Student stu3 = new Student("zhaoliu", 90, 100);
        Student stu4 = new Student("libai", 90, 100);
        Student stu5 = new Student("dufu", 95, 99);
        treeSet.add(stu1);
        treeSet.add(stu2);
        treeSet.add(stu3);
        treeSet.add(stu4);
        treeSet.add(stu5);

        Iterator<Student> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
    
    
            Student stu = iterator.next();
            System.out.println(stu.getName() + ","
                    + stu.getChinese() + "," + stu.getMath() +","+stu.getAllScore());
        }

        System.out.println(treeSet.size());
    }
}




package cn.dreamyi.demo1;

public class Student{
    
    
    private String name;
    private int chinese;
    private int math;

    public Student() {
    
    
    }

    public String getName() {
    
    
        return name;
    }

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

    public int getChinese() {
    
    
        return chinese;
    }

    public void setChinese(int chinese) {
    
    
        this.chinese = chinese;
    }

    public int getMath() {
    
    
        return math;
    }

    public void setMath(int math) {
    
    
        this.math = math;
    }

    public Student(String name, int chinese, int math) {
    
    
        this.name = name;
        this.chinese = chinese;
        this.math = math;
    }

    public int getAllScore(){
    
    
        return this.chinese + this.math;
    }
}

Guess you like

Origin blog.csdn.net/weixin_42143994/article/details/113486929