J2EE Quick Start Collection Framework [02]

Catalog

1. LinkedList implementation stack

1. Instantiate Chain List

2. Stack

3. Stack Out

4. Calculate the number of stacks

5. Instantiation testing

6. The results show that:

2. Implementation Class under Set Interface

1,HashSet

(1) Disorder

(2) No repetition

2,TreeSet

(1) Order

(2) Sorting method: natural sorting

(3) Comparator sorting

1. LinkedList implementation stack

1. Instantiate Chain List

    // Chain List Instantiation
	private LinkedList link = new LinkedList();

2. Stack

	/**
	 * Stack
	 * @param obj
	 */
	public void push(Object obj) {
		// Add the first one each time
		link.addFirst(obj);
	}

3. Stack Out

	/**
	 * Stack Out
	 * @return
	 */
	public Object pop() {
		// Get Top Stack
		Object first = link.getFirst();
		// remove
		link.removeFirst();
		// Return
		return first;
	}

4. Calculate the number of stacks

	/**
	 * Calculate the number of stacks
	 * @return
	 */
	public int size() {
		return link.size();
	}

5. Instantiation testing

	public static void main(String[] args) {
		// Initialization
		MyStack stack = new MyStack();
		// Stack
		stack.push("a"); 
		stack.push("b");  
		stack.push("c");  
		stack.push("d");  
		stack.push("e"); 
		// loop
		while (stack.size() != 0) {
			System.out.println(stack.pop());
		}
	}

6. The results show that:

e
d
c
b
a

2. Implementation Class under Set Interface

1,HashSet

(1) Disorder

Unordered means that the order of insertion is not consistent with the order of removal (as can be seen from the output)

Set<String> set = new HashSet<String>();
set.add("a");
set.add("d");
set.add("c");
set.add("b");
for (String s : set) {
System.out.println(s);
}

The results show that:

When an object enters a HashSet, it is automatically sorted after hash values are computed using the HashCode method inside the object, so the data is read after internal sorting, so the order of storage is different from that of extraction (elements are reorganized internally by sorting), and each time the data output is the same order without changing the data

(2) No repetition

HashSet underlying data structure is a hash table, HashSet is not thread safe but efficient, and collection elements can be null.

	Set<Student> set=new HashSet<>();
		set.add(new Student(1,"zs",17,"female"));
		set.add(new Student(2,"ls",14,"male"));
		set.add(new Student(3,"ww",17,"male"));
		set.add(new Student(1,"zs",18,"female"));
		
		//The equals method compares Object types by default, Object types by reference, and memory addresses by comparison
		//Override the equals method, comparing hashcode values before equals
		/*Student stu=new Student();
		stu.equals(null);*/
		
		set.forEach(System.out::println);
		System.out.println("-------------------");
		

Hash value obtained by two object hashCode() methods, if two hash values are the same, then call equals() method to compare if both are the same, then it is determined to be the same element and cannot be saved

The results show that:

Student [sid=3, sname=ww, sage=17, ssex=male]
Student [sid=1, sname=zs, sage=18, ssex=female]
Student [sid=1, sname=zs, sage=17, ssex=female]
Student [sid=2, sname=ls, sage=14, ssex=male]

HashSet guarantees element uniqueness by element rewriting hashCode() and equals(), which cannot be guaranteed without rewriting

Override hashCode() and equals() methods:

@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		//Compare student numbers only
		//result = prime * result + sage;
		result = prime * result + sid;
		//result = prime * result + ((sname == null) ? 0 : sname.hashCode());
		//result = prime * result + ((ssex == null) ? 0 : ssex.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		//true: already exists 
				//false: does not exist, allow add
				//Is the current object the same as an obj object
		if (this == obj)
			return true;
		//obj object is empty
		if (obj == null)
			return false;
		//Current object type is not equal to obj object type
		if (getClass() != obj.getClass())
			return false;
		return true;
	}

The results show that:

Student [sid=1, sname=zs, sage=17, ssex=female]
Student [sid=3, sname=ww, sage=17, ssex=male]
Student [sid=2, sname=ls, sage=14, ssex=male]

2,TreeSet

(1) Order

The underlying data structure is a binary tree, the elements in the collection are unique, and the elements can be sorted

TreeSet<String> set=new TreeSet<String>();
set.add("jack");
set.add("rose");
set.add("alien");
for (String s : set) {
System.out.println(s);
}

The results show that:

 

(2) Sorting method: natural sorting

Make the classes that need to be sorted implement the Comparable interface, override the method (because String implements this interface, the data above is ordered)

  If Return Value>0,He is old
  If Return Value=0,Equal
  If Return Value<0,I am old

Modify the code to sort by school number:

@Override
	public int compareTo(Student o) {
		// Descending order
		return -(this.getSid()-o.getSid());
	}

Instantiation test:

      //Natural Comparison Interface Test
		Set<Student> set=new TreeSet<>();
		set.add(new Student(2,"zs",17,"female"));
		set.add(new Student(3,"ls",13,"male"));
		set.add(new Student(1,"ww",15,"female"));
		set.forEach(System.out::println);
		

The results show that:

Student [sid=3, sname=ls, sage=13, ssex=male]
Student [sid=2, sname=zs, sage=17, ssex=female]
Student [sid=1, sname=ww, sage=15, ssex=female]
-------------

(3) Comparator sorting

Define a comparator that implements the Comparator interface to override the compare method:

package com.zking.utils;
import java.util.Comparator;
import com.zking.entity.Student;
/**
 * Descending by name comparison
 * @author Administrator
 */
public class NameComparator implements Comparator<Student> {
	@Override
	public int compare(Student a, Student b) {		
		return -(a.getSname().hashCode()-b.getSname().hashCode());
	}
}

Instantiation test:

		//Comparator Test
		Set<Student> set2=new TreeSet<>(new NameComparator());
		set2.add(new Student(2,"zs",17,"female"));
		set2.add(new Student(3,"ls",13,"male"));
		set2.add(new Student(1,"ww",15,"female"));
		set2.forEach(System.out::println);

According to the result of descending names:

Student [sid=2, sname=zs, sage=17, ssex=female]
Student [sid=1, sname=ww, sage=15, ssex=female]
Student [sid=3, sname=ls, sage=13, ssex=male]

Tags: Java data structure linked list programming language

Posted by Phairest on Wed, 01 Jun 2022 16:35:09 +0530