Collection: Collection, List, Set

The inheritance system of Java collections:
Insert picture description here

Collection

As can be seen from the system diagram, there are two major categories in the Collection collection, List Collection and Set Collection, both of which inherit the Collection interface.

The bottom layer of the Collection is the Object[] array, which can store any type of element. When storing the basic data type, first convert the basic type to the corresponding packaging type, because the packaging class is a subclass of Object and can be stored.

Collection collection commonly used methods:

  • boolean add(): add element
  • void clear(): clear the collection
  • boolean remove(): delete an element
  • boolean isEmpty(): Determine whether the set is empty
  • boolean contains(): whether to contain an element
  • int size(): returns the number of elements in the collection

Iterator:

The iterator is a mode that separates the traversal behavior of the sequence type data structure from the traversed object. We don’t need to care about the underlying data structure of the sequence. As long as we get this object, we can use the iterator to traverse the inside of the object. data

(1) Create an iterator object

  • Iterator it = object.iterator();

(2) Iterator method

  • boolean hasNext(): Determine whether there is an element under the cursor, return true if it has, and return false if it is not. When the iterator is generated, the cursor is not pointing to the first element, but at the top, without pointing to any element , The cursor will not automatically reset, after use, it must be regenerated

  • next(): Move the cursor down one place and return the data at that place

  • remove(): delete the element pointed to by the current cursor

(3) Matters needing attention

Once the iterator is created, if elements are added or deleted from the collection, the iterator must be regenerated, otherwise an exception will be reported.java.util.ConcurrentModificationException

When using iterators for traversal, if you need to delete elements, you can only use the remove method of the iterator, not the remove method of the collection

List

List the set of storage elements , orderly and repeatable . Ordered means that the access sequence is consistent, and the specified subscript can indicate the uniqueness of the data, so there can be duplicate data.

The List interface has two implementation classes, ArrayList and LinkedList.

  • ArrayList: The bottom layer is an array, the query efficiency is high, and the adding and deleting efficiency is low
  • LinkedList: The bottom layer is a doubly linked list, the query efficiency is low, and the adding and deleting efficiency is high

The bottom layer of ArrayList is an index array. The subscript starts at 0 and the initial capacity is 10. If it is full, it will be expanded. The capacity is 1.5 times the original capacity. It is not thread-safe and efficient.

LIst common methods:

  • add(E e): add the specified element to the end
  • add(int index,E e): Add the specified element to the specified position, and the original position content will move backwards uniformly
  • set(int index,E e): change the value of the element at the specified position
  • get(int index): Get the element at the specified index
  • remove(int index): delete the element at the specified index
  • remove(Object o): remove the specified element

LinkedList common methods:

  • add(E e): add to the end
  • push(E e): add to the head
  • addFirst(E e): add to the head
  • addLast(E e): add to the end
  • offerFirst(E e) is added to the head and returns true if it succeeds
  • offerLast(E e): add to the end, return true if successful
  • get(int index): Return the data corresponding to the specified subscript (the linked list has no subscript, but a simulated subscript, which is convenient for us to query and use)

Set

Set collection element characteristics: disordered, unique

There are TreeSet and HashSet implementation classes. The bottom layer of TreeSet is a red-black tree, and the bottom layer of HashSet is a hash table.

(1) TreeSet

The bottom layer is the red and black numbers, and the elements are stored in order

  • Number: default from small to large
  • String: compare bit by bit, compare each bit ASCII code by default
  • Date: Default comparison natural date yesterday-today-tomorrow
	TreeSet treeSet = new TreeSet();
	// 如果字符串有多个字符,先比较各自的第一位,谁小谁先输出
	// 如果第一位相同,再比较第二位,以此类推
	//所以先输出 101 ,后输出11
	treeSet.add("11");
	treeSet.add("101");
	for (Object object : treeSet) {
    
    
		System.out.print(object);
	}

Comparators

There are two types of comparators: element comparator and comparator class

Why string, Integer, Date can be sorted?

  • Because they all implement the Comparable interface

When using TreeSet to add data, it will automatically call the compareTo() method of the object to compare the elements in the collection

What if we want to store custom types?

  • Implement the Comparable interface and rewrite the compareTo method

(1) Customize the data type, implement the Comparable interface, and rewrite the compareTo method

class User implements Comparable{
    
    
	private int age;

	public int getAge() {
    
    
		return age;
	}

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

	public User(int age) {
    
    
		super();
		this.age = age;
	}

	@Override
	public String toString() {
    
    
		return "User [age=" + age + "]";
	}

	@Override
	public int compareTo(Object o) {
    
    
		// this 是当前对象
		// o 是集合内对象
		// 返回值为0 表示相等,不添加
		// 返回大于0 表示要添加的元素大,则放到后面
		// 返回小于0 表示要添加的元素小,则放到前面
		User user = (User) o;
		// 升序
		return this.age - user.age;
		// 降序
		// return this.age - user.age;
	}	
}

(2) Test

public static void main(String[] args) {
    
    
	TreeSet treeSet = new TreeSet();
	
	//创建三个自定义类型对象
	User user1 = new User(11);
	User user2 = new User(13);
	User user3 = new User(6);
	
	//添加到TreeSet集合中
	treeSet.add(user1);
	treeSet.add(user2);
	treeSet.add(user3);
	
	for (Object object : treeSet) {
    
    
		System.out.println(object);
	}
}

Result: (According to the rewritten compareTo method, the objects are sorted in ascending order of age)

3
User [age=6]
User [age=11]
User [age=13]

The second sorting method of elements added by treeSet:

Use java.util.Comparator

  • Create a separate comparator class, implement the Comparator interface, and override the compare() method
  • Pass in anonymous inner class

Application scenarios for comparing using Comparable or Comparator

  • If the class of the added element is written by us, we should use Comparable, because for extension development, others can also use Comparator to implement new sorting functions
  • If the class of the added element is not what we wrote
  •  1 该类有排序(实现了Comparable) 比如Integer,但是默认排序结果不是我们想要的,那么我们可以使用Comparator进行调整排序,因为优先级高
    
  •  2 如果该类没有实现排序(没有实现Comparable), 这时候我们需要使用Comparator进行排序,因为我们不可能去改变人家类的源码
    

Example of using Comparator for sorting: The
Integer class implements the Comparable interface, but the default sorting method is ascending. We can use Comparator to sort in descending order.

public static void main(String[] args) {
    
    
	//参数传入内部类
	TreeSet treeSet = new TreeSet(new Comparator() {
    
    
		@Override
		public int compare(Object o1, Object o2) {
    
    
			Integer i1  = (Integer) o1;
			Integer i2  = (Integer) o2;
			return i2-i1;//降序
		}
	});
	//添加元素
	treeSet.add(1);
	treeSet.add(12);
	treeSet.add(11);
	treeSet.add(3);
	treeSet.add(5);
	//遍历输出
	for (Object object : treeSet) {
    
    
		System.out.println(object);
	}
}

Add Integer type data to the ArrayList and sort it:

	public static void main(String[] args) {
    
    
		ArrayList arrayList = new ArrayList();
		arrayList.add(2);
		arrayList.add(22);
		arrayList.add(12);
		arrayList.add(5);
		Collections.sort(arrayList);
		System.out.println(arrayList);//[2, 5, 12, 22]
	}

Because Integer implements Comparable, the default ascending order is
changed to descending order:

	public static void main(String[] args) {
    
    
		ArrayList arrayList = new ArrayList();
		arrayList.add(2);
		arrayList.add(22);
		arrayList.add(12);
		arrayList.add(5);
		Collections.sort(arrayList,new Comparator() {
    
    
			@Override
			public int compare(Object o1, Object o2) {
    
    
				Integer i1  = (Integer) o1;
				Integer i2  = (Integer) o2;
				return i2-i1;
			}
		});
		System.out.println(arrayList);//[22, 12, 5, 2]

	}

Hash table:

(1) The hash table is a data structure, but it is shielded in java and directly encapsulated into HashSet, HashMap and HashTable in the form of encapsulation. Among them, the hashTable is out of date.

(2) Structure: The
linked list (singly linked list) is stored in the array, and there are four attributes in the linked list node

  • key
  • value: data saved by itself
  • next: the address of the next node
  • hash

HashSet 和 HashMap

  • HashSet is the encapsulation of HashMap, which is essentially a HashMap
  • The default initial capacity is 16
  • After encapsulation, HashSet shields the value value and can only manipulate the key, so when using set to add, only need to pass in the key.

The hash table needs to use hashCode() and equals() to represent the uniqueness of the object.
Adding process:

  • Use the key in the added key-value pair, call the key's hashCode method, generate the hash value, and perform the hash algorithm to get the array subscript
  • Determine whether there is an element on the subscript, if not, save the key-value pair in the array
  • If there are objects in the array, call the equals method of the key and compare the elements in the array. If they are equal, the key is not added and the value value is overwritten.
  • If they are not equal, add the object to the next attribute of the existing element to form a linked list
  • If it is already a linked list when it is added, you need to compare whether the key is equal to the key of all the elements in the linked list

Guess you like

Origin blog.csdn.net/qq_41504815/article/details/113002267