Java collection (knowledge points are in the example)

catalogue

Set concept

Concept:

Application scenario:

        Architecture of collection framework

List

Differences between ArrayList and ListedList:

ArrayList

LinkedList

Set

HashSet

hashCode and equals

What is an iterator?

Map

HashMap

Final summary:

ArraysList

HashSet

HashMap

Iterator (iterator)

hashCode and equals

Set concept

Concept:

A collection is a tool class that can store any number of containers with common properties.

Application scenario:

---The amount of stored data cannot be predicted

---Data with one-to-one relationship is stored at the same time

---Data addition, deletion, modification and query are required

---Data duplication problem

Architecture of collection framework

List

---List is an ordered and repeatable set of elements, also known as sequence.

characteristic:

---Precise insertion and deletion

---The two main implementation classes are ArrayList and ListedList

Differences between ArrayList and ListedList:

ArrayList is based on the implementation of dynamic array data structure, and the speed of accessing elements is better than LinkedList.

LinkedList is an implementation based on linked list data structure, which occupies a large memory space, but it is better than ArrayList when inserting or deleting data in batch.
For the requirement of fast access to objects, the implementation efficiency using ArrayList will be better.

When you need to frequently insert and delete elements into the collection, LinkedList is more effective than ArrayList.

ArrayList

---The bottom layer of ArraysList is implemented by array
---Dynamic growth to meet the needs of the program
---Insert and delete data at the end of the list is valid
---Suitable for finding and updating elements
---The element inside can be null

Let's use an exercise directly to learn about ArrayList more intuitively

import java.util.ArrayList;
import java.util.List;

public class ArrayListTest {
	public static void main(String[] args) {
		//Define ArrayList
		List discipline=new ArrayList();
	    //add() method for adding elements
		discipline.add("mathematics");
		discipline.add("language");
		discipline.add("English");
		//The size() method to get the number of elements in the list
		System.out.println("The number of subjects in the list is:"+discipline.size());
		//get() method to access the output
		for(int i=1;i<=discipline.size();i++) {
			System.out.println("The first"+i+"Gewei"+discipline.get(i-1));
		}
		System.out.println("---------------------------");
		//Change the elements in the list, using the set() method
		discipline.set(2, "Basketball");
		//The size() method to get the number of elements in the list
		System.out.println("The number of subjects in the list is:"+discipline.size());
		for(int i=1;i<=discipline.size();i++) {
			System.out.println("The first"+i+"Gewei"+discipline.get(i-1));
		}
		System.out.println("---------------------------");
		//Delete the elements in the list and use the remove() method
		discipline.remove(2);
		System.out.println("The number of subjects in the list is:"+discipline.size());
		//get() method to access the output
		for(int i=1;i<=discipline.size();i++) {
			System.out.println("The first"+i+"Gewei"+discipline.get(i-1));
		}
	}
}

The output result is:

The number of subjects in the list is: 3
 The first is mathematics
 The second is language
 The third is English
---------------------------
The number of subjects in the list is: 3
 The first is mathematics
 The second is language
 The third is basketball
---------------------------
The number of subjects in the list is: 2
 The first is mathematics
 The second is language

LinkedList

Like ArrayList, LinkedList is sorted by index position, but its elements are linked Bi directionally

---Suitable for quick insertion and deletion of elements
---LinkedList implements two interfaces: List and Queue

Similarly, let's use the example just now to understand LinkedList:

(1) :

import java.util.LinkedList;

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

		//Define LinkedList

		LinkedList discipline=new LinkedList();

	    //add() method for adding elements

		discipline.add("mathematics");
		discipline.add("language");
		discipline.add("English");
		System.out.println("The number of subjects in the list is:"+discipline.size());
		for(int i=1;i<=discipline.size();i++) {
			System.out.println("The first"+i+"Gewei"+discipline.get(i-1));
		}
		System.out.println("---------------------------");

		//Add data to the beginning of the linked list

		discipline.addFirst("Basketball");

		//Add data to the end of the linked list

		discipline.addLast("rap");
		System.out.println("The number of subjects in the list is:"+discipline.size());
		for(int i=1;i<=discipline.size();i++) {
			System.out.println("The first"+i+"Gewei"+discipline.get(i-1));
		}
		System.out.println("---------------------------");

		//Judge whether the list contains the specified element, and use the contains method

		boolean flag=discipline.contains("rap");
		if(flag) {
			System.out.println("eureka");
		}else {
			System.out.println("Can't find");
			
		}
	}
}

Operation results:

The number of subjects in the list is: 3
 The first is mathematics
 The second is language
 The third is English
---------------------------
The number of subjects in the list is 5
 The first is basketball
 The second is mathematics
 The third is language
 The fourth is English
 The fifth is rap
---------------------------
eureka

(2) :

We then use LinkedList to manage custom classes:

Create a Student class

public class Student{
	public String stuNum;//Student number
	public String stuName;//full name
	public int age;//Age
	public Student(String stuNum, String stuName, int age) {
		this.stuNum = stuNum;
		this.stuName = stuName;
		this.age = age;
	}
	public String getStuNum() {
		return stuNum;
	}
	public void setStuNum(String stuNum) {
		this.stuNum = stuNum;
	}
	public String getStuName() {
		return stuName;
	}
	public void setStuName(String stuName) {
		this.stuName = stuName;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	@Override
	public String toString() {
		return "Student [stuNum=" + stuNum + ", stuName=" + stuName + ", age=" + age + "]";
	}
	
}

LinkedList class:

public class LinkedListTest {

	public static void main(String[] args) {
		LinkedList stuList=new LinkedList();
		Student stu1 = new Student("001", "Zhang Da", 20);
		Student stu2 = new Student("002", "Zhang Er", 19);
		Student stu3 = new Student("003", "Zhang San", 18);
		
		/*Come on, come on!!!
		 * Add students to the linked list and use push()
		 * LinedList While implementing the List interface, it also implements the Queue interface
		 * push And pop are used to add and retrieve data from the Queue
		
		*/
		stuList.push(stu1);
		stuList.push(stu2);
		stuList.push(stu3);
		System.out.println("The linked list is:"+stuList);
		
		//You can think of the linked list as a small test tube. First add the data to the linked list (test tube) and then pop it up
		//Based on the principle of first in and last out
		
		System.out.println("---------------------------");
		
		//Pop up data
		
		System.out.println("Pop up data is:"+stuList.pop());
		System.out.println("---------------------------");
		
		//To get the element without removing it, the peek() method
		
		System.out.println("use peek The data of the method is:"+stuList.peek());
		System.out.println("---------------------------");
		
		//Get the element and delete the element from the linked list at the same time, using the poll() method
		
		System.out.println("call poll Elements output after:"+stuList.poll());
		
		System.out.println("---------------------------");
		
		//Output all data
		
		System.out.println("The remaining linked lists are:"+stuList);
	}

}

The operation result is:

The linked list is:[Student [stuNum=003, stuName=Zhang San, age=18], Student [stuNum=002, stuName=Zhang Er, age=19], Student [stuNum=001, stuName=Zhang Da, age=20]]
---------------------------
Pop up data is:Student [stuNum=003, stuName=Zhang San, age=18]
---------------------------
use peek The data of the method is: Student [stuNum=002, stuName=Zhang Er, age=19]
---------------------------
call poll Elements output after: Student [stuNum=002, stuName=Zhang Er, age=19]
---------------------------
The remaining linked lists are:[Student [stuNum=001, stuName=Zhang Da, age=20]]

Set

A Set is a Set whose elements are unnecessary and cannot be repeated. It is called a Set.

HashSet

---HashSet is an important implementation class of Set, which is called hash Set

---The elements in the HasSet are out of order and cannot be repeated

---HashSet only allows one null element

---It has good access and search performance

In the old example, students in the middle school, but different from the past, HashSet needs to rewrite hashCode and equals methods

hashCode and equals


For example, String objects are compared in the order of ASCII values, but in the Object class, each value is different. When we pass the same Object into the HashSet, the default method will recognize that they are different, and the same Object will be passed into the HashSet, which violates the characteristics of the HashSet. So we need to rewrite the hashCode and equals methods.


When comparing custom values, use hashCode, equals
If the hashCode values of two objects are not equal, they must be unequal
If the hashCode values are equal, you also need to use the equals method to determine whether their attributes are equal

In the meantime, let's look at iterators

What is an iterator?

---The Iterator interface provides many methods to iterate over collection elements.

---Each collection class contains iterative methods that can return iterator instances.

---The iterator can delete the elements of the underlying collection during the iteration process, but it cannot directly call the remove(Object Obj) method of the collection to delete. It can be deleted through the remove() method of the iterator.


Iterator traverses various elements in a unified way
hasNext() detects whether there is a next element in the collection
next() returns the next element of the collection

Student class

public class Student{
	public int stuId;
	public String name;
	public float score;
	
	public Student() {
	}

	public Student(int stuId, String name, float score) {
		this.stuId = stuId;
		this.name = name;
		this.score = score;
	}

	public int getStuId() {
		return stuId;
	}

	public void setStuId(int stuId) {
		this.stuId = stuId;
	}

	public String getName() {
		return name;
	}

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

	public float getScore() {
		return score;
	}

	public void setScore(float score) {
		this.score = score;
	}

	@Override
	public String toString() {
		return "Student [stuId=" + stuId + ", name=" + name + ", score=" + score + "]";
	}

	@Override
	public int hashCode() {
		return Objects.hash(name, score, stuId);
	}

	@Override
	public boolean equals(Object obj) {
		//Judge whether the objects are equal, and return true if they are equal, so there is no need to continue comparing properties
		if(this==obj)
			return true;
		//Judge whether obj is an object of Student class
		if(obj.getClass()==Student.class)
		{
			Student student=(Student)obj;
			return student.getStuId()==(stuId)&&student.getName().equals(name);
		}
		return false;
	}

	
}

Main function:

public class HashSetTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet<Student> set=new HashSet<Student>();
		Student stu1=new Student(1,"T",87.0f);
		Student stu2=new Student(2,"L",95.0f);
		Student stu3=new Student(3,"W",65.0f);
		set.add(stu1);
		set.add(stu2);
		set.add(stu3);
        System.out.println("When duplicate elements are not added:");
		Iterator<Student> iterator=set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}

		System.out.println("---------------------------");
        //Enter duplicate elements;
		Student stu4=new Student(1, "T",87.0f);
		set.add(stu4);
        System.out.println("After adding duplicate elements:");
		iterator=set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		
	}

}

When there is a duplicate element input, the output result is:

When duplicate elements are not added:
Student [stuId=3, name=W, score=65.0]
Student [stuId=1, name=T, score=87.0]
Student [stuId=2, name=L, score=95.0]
---------------------------
After adding duplicate elements:
Student [stuId=3, name=W, score=65.0]
Student [stuId=1, name=T, score=87.0]
Student [stuId=2, name=L, score=95.0]

Map

---The data in the Map is stored in the form of key value pairs
---Key value exists as an object instance of type Entry
---You can quickly find value through the value of key
---A map cannot contain duplicate key s, but can have many value s
Each key can be mapped to at most one value

HashMap


---Implementation of Map interface based on hash table
---Null values and null keys are allowed
---The key value cannot be repeated
---The Entry objects in the HashMap are unordered

Don't say much. Go to student and learn about HashMap through student

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.Set;


public class DictionaryDemo {

	public static void main(String[] args) {
		
		//Define a generic class animal
		
		Map<String, String> student=new HashMap<String, String>();
		
		//Add key value pairs of words and comments to the HashMap
		//Enter data from the keyboard
		
		Scanner in = new Scanner(System.in);
		int i=0;
		
		//key is represented by name and value is represented by student number
		
		while(i<2) {
			System.out.println("Please enter student name:");
			String name=in.next();
			System.out.println("Please enter student ID:");
			String ID=in.next();
			student.put(name,ID);
			i++;
		}
		
		//Print out the value of value (directly using the iterator)
		//Using the values() method, the return value is collection, that is, a collection, and then using the iterator method of the collection

		System.out.println("-----------------------------------");
		Iterator<String> it=student.values().iterator();
		System.out.println("By iterator method:");
		while(it.hasNext()) {
			System.out.println("Student number:"+it.next());
		}
		System.out.println("-----------------------------------");

		//Print the value of name (key) and student number (value)
		//Through entrySet() method
		
		Set<Entry<String,String>> entrySet=student.entrySet();
		System.out.println("adopt entrySet()method:");
		for(Entry<String,String> entry:entrySet) {
			System.out.print(entry.getKey()+"-");
			System.out.println(entry.getValue());
		}
		System.out.println("-----------------------------------");

		//Find the student number by name and output it

		System.out.println("Enter the name you want to find:");

		//Use the keySet() method
		
		String strSearch = in.next();
		boolean flag=false;
		String Key = null;

		//1. Get keySet

		Set<String> keySet=student.keySet();

		//2. Traverse keySet

		for(String key:keySet) {
			if(strSearch.equals(key)) {
				flag=true;
				Key=key;
				break;			
			}
		}
		if(flag==true) {
			System.out.println("eureka!The student number is:"+student.get(Key));
		}else {
			System.out.println("Can't find!");
		}
	}


}

Final summary:

ArraysList


---The bottom layer is implemented by array
---Elements are ordered and repeatable
---Unlike arrays, ArraysList can grow dynamically to meet the needs of the program
---Element value can be null

HashSet


---Elements are unordered and cannot be repeated
-Only one null element is allowed

HashMap


---The key value cannot be repeated
---Null values and null keys are allowed
---Entries in the HashMap are arranged out of order

Iterator (iterator)


---The Iterator interface traverses various sets of elements in a unified manner

hashCode and equals


If String objects are compared, they are compared in the order of ASCII values
Compare the user-defined values with hashCode and equals
When the hashCode values of two objects are not equal, they must be unequal
If the hashCode values are equal, you also need to use the equals method to determine whether their attributes are equal

Tags: Java Back-end

Posted on Sat, 20 Nov 2021 05:03:57 -0500 by overlordofevil