JAVA foundation-collection framework (three) Set collection, HashSet, LinkedSet, TreeSet collection introduction and principles

1. Overview and characteristics of Set

Because the API method of the Set collection is exactly the same as the Collection collection. So there is no special method without it.
So we only need to learn its two subclasses, one HashSet and the other TreeSet

Two, HashSet stores strings and traverses

It implements the Set interface and is supported by a hash table (actually a hashmap object). It does not guarantee the iteration order of the set; in particular, it does not guarantee that the order will last forever. This class allows the use of null elements.
Case:

HashSet<String> hashSet =new HashSet<String>();
		 boolean b1 = hashSet.add("a");
		 boolean b2= hashSet.add("a");
		 boolean b3= hashSet.add("b");
		 System.out.println(b1);			
		 System.out.println(b2);
		 System.out.println(b3);
		 System.out.println(hashSet);				
//HashSet的继承体系中有重写toString方法
		 for (String string : hashSet) {
    
    
			System.out.println(string);				
//只要使用那个迭代器迭代,那么就可以使用foreach循环
}	

The effect is as follows:
Insert picture description here
Tips: The Set collection has no index, cannot be repeated, and is disordered (inconsistent storage). There is a toString method in its inheritance system, so there is no need to write the toString() method.

Three, HashSet stores custom objects

Store custom objects and ensure the uniqueness of elements.
Example:
NoteBecause the set collection does not guarantee the order of the elements, So every storage is out of order

HashSet<Person> hashSet =new HashSet<Person>();
		hashSet.add(new Person("张三",12));
		hashSet.add(new Person("张三",12));
		hashSet.add(new Person("李四",13));
		hashSet.add(new Person("李四",13));
		hashSet.add(new Person("李四",13));
		System.out.println(hashSet);

The effect is as follows:
Insert picture description hereWhen we rewrite the equals method so that our name and age are the same, it means that the stored characters are the same. But in the Set collection, we cannot use the equals method to judge. But first set the value of hasCode.

@Override
	public boolean equals(Object obj) {
    
    
		Person person =(Person)obj;
		return this.name.equals(person.name) &&this.age ==person.age;
	}
	@Override
	public int hashCode() {
    
    
		// TODO Auto-generated method stub
		
		return 10;
	}

When the hasCode return value is the same, Which means that certain types of objects stored in our memory will be in the same location. Then the equals method is called, and the equals method is used to determine if our name and age are the same, it returns true, and no object storage is performed. If it returns false, the object will be stored in a cylindrical format. As shown in the figure:
But in order to ensure the efficiency of the program, weTry to ensure that the hasCode is different, And then execute the equals method. of courseIf the attribute values ​​are the same, the value of its hasCode must be the same. The return values ​​with different attributes are as different as possible. Compilers such as Eclipse can automatically generate code blocks for us. Shortcut key: ctrl+shifts +h can be generated. And we check the attributes of judgment. The drawing is as follows:
Insert picture description here

@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Person other = (Person) obj;
		if (age != other.age)
			return false;
		if (name == null) {
    
    
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public int hashCode() {
    
    
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

Notice why prime is 31?
Benefit: 31 is a prime number, which is a number that can be divisible by 1 and itself. And 31 is neither big nor small.

Fourth, the principle of how HashSet guarantees the uniqueness of elements

1. HashSet principle (emphasis)

  • We need to remove duplicate elements when we use the Set collection. If we compare equals() one by one when storing, the efficiency is low. The hash algorithm improves the efficiency of deduplication and reduces the number of times the equals() method is used.
  • When HashSet calls the add() method to store an object, first call the object's hashCode() method to get a hash value, and then look for objects with the same hash value in the collection
  • If there is no object with the same hash value, it is directly stored in the collection
  • If there are objects with the same hash value, compare equals() one by one with the objects with the same hash value. If the comparison result is false, it will be stored, and true will not be stored.

2. Store the object of the custom class in HashSet to repeat

  • The hashCode() and equals() methods must be rewritten in the class
  • hashCode(): The return value of objects with the same attribute must be the same, and the return value of different attributes should be as different as possible (improve efficiency)
  • equals(): Returns true for the same properties, false for different properties, and stores when it returns false.

V. Overview and use of LinkedHashSet

Overview of LinkedHashSet:

  • Its bottom layer is realized by linked list, which is in set collectionThe only one that can guarantee how to deposit itCollection. (Because it is a linked list implementation, it can record successive address values.)
  • It is a subclass of HashSet, so the element can be guaranteed to be unique, the same principle as HashSet.
    Features of LinkedHashSet: It can be guaranteed to be retrieved as it is stored. It means you can take it out as you put it in
LinkedHashSet<String> linkedHashSet =new LinkedHashSet<String>();
		linkedHashSet.add("a");
		linkedHashSet.add("a");
		linkedHashSet.add("a");
		linkedHashSet.add("b");
		linkedHashSet.add("b");
		linkedHashSet.add("c");
		linkedHashSet.add("d");
		
		System.out.println(linkedHashSet);

The effect is as follows:
Insert picture description here

Six, TreeSet stores Integer type elements and traverses

TreeSet is usedSort the elements, And it does not store the same data.

TreeSet<Integer> treeSet =new TreeSet<Integer>();
	treeSet.add(1);
	treeSet.add(1);
	treeSet.add(3);
	treeSet.add(3);
	treeSet.add(2);
	treeSet.add(2);
	treeSet.add(4);
	System.out.println(treeSet);

The effect is as follows:
Insert picture description here

Seven, TreeSet stores custom objects

When we simply store objects, we will report errors. becauseObject cannot be used for comparison. So we need to add interface methods to our bean class.

public class Person implements Comparable<Person>{
    
    
	private String name;
	private int age;
	public String getName() {
    
    
		return name;
	}
	public void setName(String name) {
    
    
		this.name = name;
	}
	public int getAge() {
    
    
		return age;
	}
	public void setAge(int age) {
    
    
		this.age = age;
	}
	
	public Person(String name, int age) {
    
    
		super();
		this.name = name;
		this.age = age;
	}
	@Override
	public String toString() {
    
    
		return "Person [name=" + name + ", age=" + age + "]";
	}
	@Override
	public int compareTo(Person o) {
    
    
		// TODO Auto-generated method stub
		
		return 1;
	}
}

TreeSet part

TreeSet<Person> treeSet =new TreeSet<Person>();
	treeSet.add(new Person("张三",12));
	treeSet.add(new Person("李四",12));
	treeSet.add(new Person("王五",13));
	treeSet.add(new Person("赵六",14));
	System.out.println(treeSet);

The effect is as follows:
Insert picture description here
Note: The return value of the CompareTo method:
If the number returned by return is 正数, the set is 怎么存怎么取.
If the number returned by return is 负数, the set is 倒序存储.
If the number returned by return is 0, it is in the set 存在一元素.

Eight, TreeSet guarantees the uniqueness of elementsNatural orderingPrinciple of

Insert picture description here
When we sort by age

Write the Person entity class in the Bean package

@Override
	public int compareTo(Person o) {
    
    
		// TODO Auto-generated method stub
		return this.age -o.age;
	}
TreeSet<Person> treeSet =new TreeSet<Person>();
	treeSet.add(new Person("张三",12));
	treeSet.add(new Person("李四",22));
	treeSet.add(new Person("周七",24));
	treeSet.add(new Person("王五",10));
	treeSet.add(new Person("赵六",24));
	System.out.println(treeSet);

The principle is as follows: The
Insert picture description here
effect is as follows:
Insert picture description here
At this time, we will find that one missing Zhao Liu element is very simple, because we only judged the age, soElements of the same age stored later will not be stored.
If we upgrade: sort by age

@Override
	public int compareTo(Person o) {
    
    
		// TODO Auto-generated method stub
		int num =this.age -o.age;
		return num == 0? this.name.compareTo(o.name):num;
	}

This method will perform a complete sort.

Nine, TreeSet stores custom objects and traverses Exercise 1 (sorted by name)

@Override
	public int compareTo(Person o) {
    
    
		int num = this.name.compareTo(o.name); 		
		//按照姓名排序
		return num== 0? this.age -o.age :num;		
		//年龄是次要条件
	}
TreeSet<Person> treeSet =new TreeSet<Person>();
treeSet.add(new Person("李四",22));
treeSet.add(new Person("张三",12));
treeSet.add(new Person("周七",24));
treeSet.add(new Person("王五",10));
treeSet.add(new Person("赵六",24));
System.out.println(treeSet);

The effect is as follows:
Insert picture description here

10. TreeSet stores custom objects and traverses Exercise 2 (sorted by the length of the name)

	@Override
	public int compareTo(Person o) {
    
    
		// TODO Auto-generated method stub
		int length =this.name.length() - o.name.length();	
		//比较姓名长度
		int num =length == 0 ?this.name.compareTo(o.name):length;
		//完全有一种可能,名字长度一样,内容是不一样的
		return num==0? this.age -o.age:num;		
		//完全有一种可能,姓名和长度均相同
	}

11. TreeSet guarantees the uniqueness of elementsComparator sortPrinciple of

TreeSet(Collection <? super E> comparator): Construct a new empty TreeSet, which sorts according to the specified comparator.
Requirements: Sort the strings according to length

TreeSet<String> treeSet =new TreeSet<String>(new CompareByLen());			
//Comparator c = new CompareByLen();
	treeSet.add("aaaaaaaaaa");
	treeSet.add("z");
	treeSet.add("wc");
	treeSet.add("nba");
	treeSet.add("cba");
	System.out.println(treeSet);

Create a new class

class CompareByLen  implements Comparator<String>{
    
    
	@Override
	public int compare(String s1, String s2) {
    
    		
//按照字符串的长度比较
		// TODO Auto-generated method stub			
		int num = s1.length() -s2.length();			
//长度为主要条件
		return num==0? s1.compareTo(s2): num ;		
//内容为次要条件
	}
	
}

The effect is as follows: the
Insert picture description hereprinciple is as follows:
Insert picture description here

Take it out from the left one by one, if not, take the right one.

12. TreeSet principle

1. Features
TreeSet is used for sorting, you can specify an order, and the objects will be arranged in the specified order after they are stored.
2. How to use

a. Natural order (Comparable)

  • The add() method of the TreeSet class will promote the stored object to Comparable type
  • Call the compareTo() method of the object and compare the objects in the collection
  • Store according to the result returned by the compareTo() method

b. Comparator order (Comparator)

  • When creating TreeSet, you can make a Comparator
  • If a subclass object of Comparator is passed in, the TreeSet will be sorted according to the order in the comparator
  • The add() method automatically calls the compare() method in the Comparator interface to sort
  • The called object is the first parameter of the compare method, and the object in the collection is the second parameter of the compare method

c. The difference between the two methods

  • The TreeSet constructor does not pass anything, by default in the order of Comparable in the class (if not, an error will be reported as ClassCastException)
  • If TreeSet is passed into Comparator, Comparator will be given priority

Guess you like

Origin blog.csdn.net/Mr_GYF/article/details/108719802