Sets and their intersection, union and difference

The HashSet<E> generic class is similar to a mathematical set in terms of data organization, and can perform operations such as "intersection", "union", and "difference". The HashSet<E> generic class implements the generic interface Set<E>, and the Set<E> interface is a subinterface of the Collection<E> interface. Most of the methods in the HashSet<E> class are implementations of interface methods. When programming, you can use the interface callback technology , that is, assign the reference of the HashSet<E> object to the Collection<E> interface variable or Set<E> interface variable, then the interface can call the interface method implemented by the class .

 HashSet<E> generic class 

The object created by the HashSet<E> generic class is called a collection, such as
HashSet < String > set = HashSet < String >();
then set is a collection that can store String type data , set can call add (String s) method to add The data of String type is added to the collection, and the data added to the collection is called the elements of the collection . Sets are not allowed to have the same elements, that is, if b is already an element in the set, then it is invalid to perform set.add(b) operation . The initial capacity of the collection object is 16 bytes , and the load factor is 0.75, that is to say, if the elements added to the collection exceed 75% of the total capacity, the capacity of the collection will be doubled.

Common methods
The common methods of the HashSet<E> generic class are as follows.
public boolean add(E o); Adds the element specified by the parameter to the collection.

public void clear(): Empty the collection so that the collection does not contain any elements.

public boolean contains(Object o): Determine whether the data specified by the parameter belongs to the collection

public boolean isEmpty(): Determine whether the collection is empty

public boolean remove(Object o): The collection deletes the element specified by the parameter

public int size(): returns the number of collection elements

Object[] toArray(): Store the collection elements in an array and return the array

boolean containsAll(HanshSet set): Determine whether the current set contains the set specified by the parameter.
public Object clone(): Get a clone object of the current collection, the change of the elements in the object will not affect the elements in the current collection, and vice versa.
The collection can be traversed with the help of the generic class Iterator<E>, and a collection object can use the iterator() method to return an object of type Iterator<E>. If the collection is a collection of Student type, that is, the elements in the collection are objects created by the Student class, then the collection uses the iterator() method to return an Iterator<Student> type object, and the object uses the next() method to traverse the collection
.

We store the students' grades in a collection, and realize the traversal collection.

import java.util.*;
class Student{
	String name;
	int score;
	Student(String name,int score){
		this.name=name;
		this.score=score;
	}
}

public class E13_11 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Student zh = new Student("小美",99),
				wa = new Student("小哇",78),
				li = new Student("小李",67);
		HashSet<Student>set = new HashSet<Student>();
		HashSet<Student>subset = new HashSet<Student>();
		set.add(zh);
		set.add(wa);
		set.add(li);
		subset.add(wa);
		subset.add(li);
		//public boolean contains(Object o):判断参数指定的数据是否属于集合
		if(set.contains(wa)) {
			System.out.println("集合set中含有:"+wa.name);
			
		}
		if(set.containsAll(subset)) {
			System.out.println("集合set包含集合subset");
			
		}
		int number = subset.size();
		System.out.println("集合subset含有"+number+"个元素");
		Object s[]=subset.toArray();//Object[] toArray():将集合元素存放到数组中,并返回这个数组。
		for(int i=0;i<s.length;i++) {
			System.out.printf("姓名:%s,分数:%d\n",((Student)s[i]).name,((Student)s[i]).score);
		}
		number = set.size();
		System.out.println("集合set中有"+number+"个元素:");
		Iterator<Student>iter = set.iterator();
		while(iter.hasNext()) {
			Student te = iter.next();
			System.out.printf("姓名:%s,分数:%d\\n",te.name,te.score);
		}
	}

}

operation result:

The collection set contains: Xiaowa
The collection set contains the collection subset
The collection subset contains 2 elements
Name: Xiaoli, score: 67
Name: Xiaowa, score: 78
There are 3 elements in the collection set:
Name: Xiaoli, score: 67 \nName: Xiaomei, score: 99\nName: Xiaowa, score: 78\n


 intersection and difference of sets

The set object calls  the boolean retainAll (HashSet set) method to intersect with the set specified by the parameter, making the current set the intersection of two sets .
The set object calls the boolean addAll(HashSet set) method to perform a union operation with the set specified by the parameter , making the current set a union of two sets. The collection object calls the boolean removeAll (HashSet set) method to calculate the difference operation
with the set specified by the parameter , so that the current set becomes the difference between the two sets. The collection specified by the parameter must be the same type of collection as the current collection, otherwise the above method returns false.

Find the symmetric difference set of two sets A and B, that is, find the union of AB and BA.
 

import java.util.*;
public class E13_12 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		HashSet<Integer>A = new HashSet<Integer>(),
						B = new HashSet<Integer>();
		for(int i=1 ; i<=4; i++) {
			A.add(i);
		}
		B.add(1);
		B.add(2);
		B.add(5);
		B.add(6);
		HashSet<Integer>tempSet = (HashSet<Integer>)A.clone();
		A.removeAll(B); //A变成调用该方法之前的集合A与集合B的差集
		B.removeAll(tempSet); //B变成调用该方法之前的集合B与集合tempSet的差集
		B.addAll(A); //B就是最初的A与B的对称差
		
		int number = B.size(); 
		System.out.println("A和B的对称差集合有"+number+"个元素");
		Iterator<?> iter = B.iterator();
		while(iter.hasNext()) {
			System.out.printf("%d,",iter.next());
		}
	}
}

operation result:

The symmetric difference set of A and B has 4 elements
3,4,5,6,


1. Use "class name <generic list>" to declare a generic class. When using a generic class to declare an object, you must replace the generics in the generic list with concrete types (not basic data types).
2.  The object created by the LinkedList <E> generic class stores data in a linked list structure. The linked list is a data structure composed of several objects called nodes. Each node contains a data and a reference to the previous node. and a reference to the next node .
3. The Stack < E> generic class creates a stack object. The stack puts the first data put into the stack at the bottom, and puts the subsequent data on top of the existing data. The stack is always at the top Perform data input/output operations
4.  HashMap <K, V> generic class to create a hash map, which uses a hash table structure to store data and is used to store key/value data pairs , allowing any number of key/value Data pairs are stored together. Using a hash map to store data that needs to be retrieved frequently can reduce the overhead of retrieval.
5.  The TreeSet < E> class creates a tree set. The arrangement of the tree set nodes is different from that of the linked list, and they are not arranged in the order of addition. When the data in a tree set is an object created by the class that implements the Comparable interface, the nodes will be sorted according to the object's Size relationship ascending order
6.  The TreeMap <K,V> class creates a tree map, and the nodes of the tree map store "key/value" pairs. Unlike the tree set, the tree map is arranged. The projection guarantees that the nodes are arranged in ascending order according to the "keys" in the nodes .

Guess you like

Origin blog.csdn.net/m0_46965984/article/details/124370586