Java study notes: HashSet, TreeSet and LinkedHashSet

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/sinat_38393872/article/details/91128302

This article is a summary of their own learning, learning materials is crazy Java handouts third edition, edited Gang, Electronics Industry Publishing House.

Note: This article is to use the HashSet, TreeSet, LinkedHashSet and EnumSet often summarize methods, as well as to their nature do the summary.

These three are inherited Collection, Collection of commonly used method in this blog inside https://blog.csdn.net/sinat_38393872/article/details/90904958

Let me talk about three features of HashSet

  • The arrangement order and the addition order inconsistency
  • Asynchronous Collection: If you want to keep pace, then manually add the code
  • Collection elements may be null

HashSet talk about the process of storage elements. Set HashSet is based on the added characteristic Hash table, so the only bit of HashSet is stored and the search process quickly, the time overhead is constant level. When HashSet storage, calls stored in the storage object hashCode () method hashCode, and then obtain the position of the storage object storage according hashCode.

If there are two equal hashCode element values ​​but not equal, then hashSet think these are two different elements. So when you want to use a custom class object hashSet storage, not only to equals () method override, but also on the hashCode () method override. Here to talk about hashCode () overrides rule.

If we have a plurality of value, depending on the type of the value, corresponding to the calculated hashCode are not the same, the following calculation rule is, the set value is the value of f

The type of instance variables Calculation
boolean hashCode = (f ? 0 : 1)
byte, short, char, int hashCode = (int) f
long hashCode = (int) (f^(f>>>32))
float hashCode = Float.floatToIntBits(f)
double

long l = Double.doubleToLongBits(f);

hashCode = (int) (l ^ (l >>> 32));

Reference types hashCode = f.hashCode()

After obtaining the value of each hashCode, hashCode multiplied by these different numbers and then adding the resulting number is to be returned hashCode.

For example, we have a custom class

class A{
    int value1;
    long value2;
}

hashCode to the class A is calculated by value1 and value2. Then according to the above rules, value1 and value2 the following code hashCode

hashCode1 = value1;
hashCode2 = (int) (value2 ^ (value2 >>> 32));

The final should be returned hashCode

return ((hashCode1 << 5)- hashCode1) + ((hashCode2 << 3) - hashCode2); //乘31和乘7是随机选
//的两个数,也可以选其它的数字,只要是两个不同的质数就行

The complete code is as follows

class A{
    int value1;
    long value2;
    public int hashCode(){
        hashCode1 = value1;
        hashCode2 = (int) (value2 ^ (value2 >>> 32));
        return ((hashCode1 << 5)- hashCode1) + ((hashCode2 << 3) - hashCode2); 
    }
}

After calculating each value multiplied by the corresponding hashCode also primes added for different reasons, in order to prevent obviously different keywords, the addition result is exactly equal to such a case. For example, a memory object has two value calculated hash values ​​are 1 and 2, two other storage object value calculated hash values ​​are 1 and 2, two different objects calculated Ha Greek values, like fishes should either be additive, then you are wrong, so are multiplied by different numbers, which can effectively prevent this from happening. As for why multiplied by a prime number, I would like to not understand, it is best to write the book and be consistent.


Now the LinkedHashSet

LinkedHashSet nothing to talk about, only its properties are worth mentioning.

The internal LinkedHashSet also hashCode () to store, but it is maintained with an internal linked list, the performance was slightly lower than HashSet. But when traversing element stronger than HashSet.

 


Now is the TreeSet link

TreeSet is a collection of automatic sorting, and general Set comparison, it provides more ways

Comparator comparator()

If TreeSet uses a self-defined sorting method, then this method returns a custom comparator. If you are using the default sort, the return is null.

 

Object first();
Object last();

Respectively, return the first and last elements

Object lower(Object e);
Object higher(Object e);

Returns are located before and after the element specified element. Wherein the element e may be not a TreeSet, e is a guideline.

SortedSet subSet(Object fromElement, Object toElement)

Set to return a subset of, the range is from to fromElement (inclusive) to toElement, exclusive (not included). Note that this is not the return of a new collection, just a View source collection, a view, a projection, Java documentation is written

This means that you change this subset, it will suffer the same change in the source collection.

Code validation as follows

public class test{
	public static void main(String[] args){
		TreeSet c = new TreeSet();  //c是源集合
		c.add(1);
		c.add(2);
		c.add(3);
		c.add(4);
		c.add(5);
		//现在c中的元素是(1,2,3,4,5)
		SortedSet a = c.subSet(1,3);
		//a是(1,2)
		a.remove(2);
		//删除a中的[2]之后,源集合中的[2]也应该被删除了
		Iterator it = c.iterator();
		while(it.hasNext()) {
			System.out.print(it.next() + " ");
		}
	}
}

The output of this program is

This verified the above mentioned content. Let's start talking about other methods

SortedSet headSet(Object toElement);    //小于
SortedSet tailSet(Object toElement);    //大于等于

Returns the specified elements are less than equal to and greater than the specified subset of elements, is the return of the projection.

  • Custom sorting TreeSet

TreeSet an ordered set, the default is sorted according to the system compareTo (Object obj) method. We do not want to use the default method will want to use a custom method is a custom collation, the following explains how to customize the collation.

TreeSet is sorted according to compareTo (Object obj) to row, so the custom collation as long as we want to add elements to sort TreeSet in succession Comparable interface, which override the compareTo (Object obj) and equals (Object obj) method It can be. Code Example below.

//我们要将A添加到TreeSet,就要对A添加排序规则。
class A implements Comparable{
	private int value;
	private String string;
	A(int value, String string){
		this.value = value;
		this.string = string;
	}
	public int getValue() {
		return value;
	}
	//两个A的对象相等的标准应该是值相等,即value和string都相等
	public boolean equals(Object obj) {
		if(this == obj) {
			return true;
		}
		if(obj != null && obj.getClass() == A.class) {
			A a = (A) obj;
			if(a.value == this.value) {
				if(a.string.equals(this.string)) {
					return true;
				}
			}	
		}
		return false;
	}
	//这里设定比较的规则是先比较value,value相等的情况再比较字符串
	@Override
	public int compareTo(Object obj) {
		A a = (A) obj;
		if(this.value > a.value) return 1;
		if(this.value < a.value) return -1;
		if(this.value == a.value) {
			int result = this.string.compareTo(a.string);
			if(result > 0) return 1;
			if(result < 0) return -1;
		}
		return 0;
	}	
}

 

 


Now speak EnumSet class

EnumSet is designed specifically for the enumeration class set of elements in the set are ordered in the same order of enumerated values ​​Enum class order.

Enum internal bits stored in the form of a vector, so Enum take up very little space, and operating efficiency is very high.

Enum no constructor to create instances of the class, the program can create an instance of the class by the method Enum. Class methods are described below.

EnumSet allOf(Class elementType)    //创建一个包含指定枚举类里所有枚举值的EnumSet集合。
EnumSet complementOf(EnumSet s)    //创建一个其元素类型和指定EnumSet里元素类型相同的EnumSet集合,新的

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/sinat_38393872/article/details/91128302