当前位置:网站首页>Detailed explanation of set

Detailed explanation of set

2022-07-01 05:21:00 Customer bank

Catalog

One .Set aggregate

Two .HashSet aggregate

 foreach Loop traversal

Iterator traverses the array   

3、 ... and .TreeSet aggregate


One .Set aggregate

Set A collection is actually an interface ,HashSet and TreeSet Realized Set Interface , all Set Methods HashSet and TreeSet Also have .

characteristic :

  • set Sets are unordered , Not repeated ( Disorder means not in the order in which we add to the set )
  • Traverse through foreach, iterator , Cannot pass subscript , because set Set has no subscript
  • The initial capacity is 16, Load factor 0.75 times , Expansion capacity increase 1 times  

   


Two .HashSet aggregate

  • HashSet It's the realization of Set Collection interface , therefore Set Set has , It also has .
  • It only stores unique elements and allows null values . Storing unique elements means , If you add two 1, So there's one 1 be killed , Only 1 One 1 There is .
  • from HashMap Support .
  • The insertion order is not maintained
  • Thread unsafe

 

  •  foreach Loop traversal

      If some elements are added, they will be covered , You can press and hold Ctrl Click on add Go in and see the source code . There is one in the source code boolean Methods , This method determines whether the newly added element already exists in the collection , If false Then there are already the same elements as this element , If true Then there is no such element , Add to the set .

  notes : If you already have an element
        

package com.yjx.test;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.junit.Before;
import org.junit.Test;



public class Test01 {
	
	
	private Set<Integer> set=new HashSet<Integer>();
	
	@Before
	public void list() {
		set.add(1);
		set.add(1);
		set.add(2);
		set.add(3);
		set.add(3);
		set.add(4);
		set.add(5);
		set.add(6);
	
	}
	
	
	
	@Test
	public void test01() {
		for(Integer e:set) {
			System.out.println(e);
		}
	}
	

}

  set The method in the source code for adding a collection to determine whether an element exists in the collection

  

boolean add(E e);

Get the results :

  

  • Iterator traverses the array   

     hasNext: Determine if there are any elements in the set

  public void test02() {
     Iterator<Integer>it=set.iterator();
    	while(it.hasNext()) {
    		System.out.println(it.next());
    	}
    }

  Get the results :

  

 

  

  We create a student entity class , Then add the students to the set .

  •   Stundet Class must implement hashCode() and equals Method , Because they are used to compare whether two objects are equal and consistent
  • You can try in stundet Class , And remove the difference between the two methods , If Studnet There is no such method in , So even if id Equal to name and age , It can still be added

  Studnet class

package com.yjx.test;

public class Stundet {
	
	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public Stundet() {
		// TODO Auto-generated constructor stub
	}
	
	
	public Stundet(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stundet other = (Stundet) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Stundet [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	
	
	

}

  Method

  Students like this id Same name as the student , But different ages , So they are not the same person , Both will be added .

 

 public void test03() {
		 // First create a collection 
		 Set<Stundet> set=new HashSet<Stundet>();
		 set.add(new Stundet(1," Zhang San ",18));
		 set.add(new Stundet(1," Zhang San ",19));
		 set.add(new Stundet(3," Zhang Wu ",16));
		 set.add(new Stundet(5," Zhang Liu ",11));
		 set.add(new Stundet(3," Zhang Qi ",12));
		 
		 for(Stundet s:set) {
			 System.out.println(s);
		 }
	 }

  Get the results :

 

  

  But if we will be the first and the second will id And the name and age are set to the same , Then only one will be added .

   

 public void test03() {
		 // First create a collection 
		 Set<Stundet> set=new HashSet<Stundet>();
		 set.add(new Stundet(1," Zhang San ",18));
		 set.add(new Stundet(1," Zhang San ",18));
		 set.add(new Stundet(3," Zhang Wu ",16));
		 set.add(new Stundet(5," Zhang Liu ",11));
		 set.add(new Stundet(3," Zhang Qi ",12));
		 
		 for(Stundet s:set) {
			 System.out.println(s);
		 }
	 }

Get the results : And it will help us according to id Make a sort

  

  If we want to sort by age , This is where it comes in TreeSet, So let's look down .

3、 ... and .TreeSet aggregate

  • Is a collection containing ordered elements without repetition
  • The function is to provide orderly Set aggregate , Sort naturally or according to what is provided Comparator Sort
  • TreeSet Is based on TreeMap Realized

  What to use TreeSet aggregate ?

  When we want to sort by what, we can use TreeSet aggregate , Here's how to use TreeSet Set to sort . 

 

  •     The first method

      We use Comparator Make a sort , You can grow up , You can also go from big to small , But there is a big problem with this method , If there are people of the same age , Then only one will stay , The others will not exist in the set .

  

This is sorted from small to large , Want from big to small , Just o2.getAge-o1.getAge.

public void test04() { 
		TreeSet<Stundet> tree=new TreeSet<Stundet>(new Comparator<Stundet>() {
			@Override
			public int compare(Stundet o1, Stundet o2) {
				 
				return o1.getAge() - o2.getAge();
			}
			
		});
		// First create a collection 
		
		tree.add(new Stundet(1," Zhang San ",18));
		tree.add(new Stundet(3," Zhang Wu ",16));
		tree.add(new Stundet(5," Zhang Liu ",18));
		tree.add(new Stundet(4," Zhang Qi ",12));
		tree.add(new Stundet(6," Zhang Qi ",12));
		 
		 for(Stundet s:tree) {
			 System.out.println(s);
		 }
	}

      Get the results :

    

  

    We just said , Appear at the same age , Only one will be left , How to solve this problem , Look at the following code .

  We added a judgment , When age is subtracted to 0, They are equal , Then according to their id Sort . This problem can be solved .

public void test04() { 
		TreeSet<Stundet> tree=new TreeSet<Stundet>(new Comparator<Stundet>() {
			@Override
			public int compare(Stundet o1, Stundet o2) {
				 if(o1.getAge() - o2.getAge()==0) {
					 return o1.getId()-o2.getId();
				 }
				return o1.getAge() - o2.getAge();
			}
			
		});
		// First create a collection 
		
		tree.add(new Stundet(1," Zhang San ",18));
		tree.add(new Stundet(3," Zhang Wu ",16));
		tree.add(new Stundet(5," Zhang Liu ",18));
		tree.add(new Stundet(4," Zhang Qi ",12));
		tree.add(new Stundet(6," Zhang Qi ",12));
		 
		 for(Stundet s:tree) {
			 System.out.println(s);
		 }
	}

    Get the results : All the data exists ,id According to the order from small to large .

    

   

     

  •       The second method

    We are Studnet Make judgments in entity classes , Realization Comparable

package com.yjx.test;

import java.util.Comparator;

public class Stundet implements Comparable<Stundet>{
	
	private Integer id;
	private String name;
	private Integer age;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
	public Stundet() {
		// TODO Auto-generated constructor stub
	}
	
	
	public Stundet(Integer id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((age == null) ? 0 : age.hashCode());
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Stundet other = (Stundet) obj;
		if (age == null) {
			if (other.age != null)
				return false;
		} else if (!age.equals(other.age))
			return false;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}
	@Override
	public String toString() {
		return "Stundet [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
	
	
	@Override
	public int compareTo(Stundet o) {
		if(o.getAge()-this.getAge()==0) {
			return o.getId()-this.getId();
		}
		return o.getAge()-this.getAge();
	}


	  
	
	

}

  Test method code

@Test
	public void test05() { 
		TreeSet<Stundet> tree=new TreeSet<Stundet>();
		// First create a collection 
		
		tree.add(new Stundet(1," Zhang San ",18));
		tree.add(new Stundet(3," Zhang Wu ",16));
		tree.add(new Stundet(5," Zhang Liu ",18));
		tree.add(new Stundet(4," Zhang Qi ",12));
		tree.add(new Stundet(6," Zhang Qi ",12));
		 
		 for(Stundet s:tree) {
			 System.out.println(s);
		 }
	}

  This method is also possible , You'd better make a judgment , Avoid data of the same size and leave only one such case . 

That's all for today's study . 

原网站

版权声明
本文为[Customer bank]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010516540180.html