Set of (two) -HashSet and TreeSet and LinkedHashSet

HashSet

Reference article:

https://blog.csdn.net/tingzhiyi/article/details/52152487
https://blog.csdn.net/xingjiyuan26/article/details/49514631
https://blog.csdn.net/a724888/article/details/80295328

  1. It defines
    the underlying implementation is to use a hash table, the object is stored in a region corresponding to a hash value, if the object is stored in hashset, you need to override the hashcode method.

  2. basic method

hashset.clear():从此 set 中移除所有元素。

hashset.remove(Object o):如果指定元素存在于此 set 中,则将其移除。

hashset.isEmpty():如果此 set 不包含任何元素,则返回 true。

hashset.contains(Object o):如果此 set 包含指定元素,则返回 true。

hashset.size():返回此 set 中的元素的数量(set 的容量)。
  1. Features :
  • You can add an element types: basic types and custom object can be.
  • Non-thread-safe
  • The saved data are unordered
  • Realization set interfaceElements can not be repeated
  1. How to determine the repeated screening element
    First, a equals and hashcode return two values are the same method to determine whether two objects are the same, and the source code,Since the internal hashset be stored according hashmapUsing the map to put the method determines whether there is a key (return key is present, instead of returning empty)
public boolean add(E e ) {
        return map.put(e, PRESENT)== null;
    }
  1. HashSet caused by a memory leak
    that is, when you save an object,Also rewrote his hashcode, and then when you store the object in your collection to hashsetWhen you modify your hashcode, you will find that you can not call the remove method to delete the set of objects, eventually leading to memory leaks, see the following code details
public class MPoint {
     private int x;
     private int y;
 
     public MPoint() {
     }
 
     public MPoint( int x, int y) {
            this. x = x;
            this. y = y;
     }
 
     public int getX() {
            return x;
     }
 
     public void setX(int x) {
            this. x = x;
     }
 
     public int getY() {
            return y;
     }
 
     public void setY(int y) {
            this. y = y;
     }
 	//重写hashcode
     @Override
     public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + x; //x参与计算hash值
            return result;
     }
 
     @Override
     public boolean equals(Object obj) {
            if ( this == obj)
                 return true;
            if ( obj == null)
                 return false;
            if (getClass() != obj.getClass())
                 return false;
           MPoint other = (MPoint) obj;
            if ( x != other. x)
                 return false;
            if ( y != other. y)
                 return false;
            return true;
     }
}

The main function test

public class HashSetTest {
 
     public static void main(String[] args) {
           HashSet<MPoint> set = new HashSet<MPoint>();
           MPoint mp1 = new MPoint(1, 6);
           MPoint mp2 = new MPoint(2, 7);
           MPoint mp3 = new MPoint(1, 6);
 
            set.add( mp1);
            set.add( mp2);
            set.add( mp3);
            set.add( mp1);
 
           System. out.println( set.size()); // 结果为2
 
            mp1.setX(3);
            set.remove( mp1);
           System. out.println( set.size()); // 结果还是为2,说明没有删除成功
           System. out.println( set.contains( mp1)); // 结果为false,修改了参与计算hash值的变量,其对象不能再被找到
           System. out.println( set.remove( mp1)); // 结果为false,修改了参与计算hash值的变量,其对象不能被删除
 
            mp2.setY(2);
           System. out.println( set.contains( mp2)); // 结果为true,没有修改关键属性的对象可以被找到
           System. out.println( set.remove( mp2)); // 结果为true,没有修改关键属性的对象可以被删除
           System. out.println( set.size()); // 结果还是为1
     }
}

HashTree

Original link https://blog.csdn.net/u012050154/article/details/51459679

  1. Define
    the underlying implementation is based on the red-black tree, save the data source using TreeMap,

  2. Two common usage

  • basic type
public class TreeSetTest {
	public static void main(String[] args) {
		Set<String> set = new TreeSet<String>();
		set.add("abc");
		set.add("xyz");
		set.add("rst");
		
		System.out.println(set);//可以直接输出
		
		Iterator itSet = set.iterator();//也可以遍历输出
		while(itSet.hasNext())
			System.out.print(itSet.next() + "\t");
		System.out.println();
	}
}

  • Custom objects (just remember to implement the Comparable method in a custom object)
//自定义数据类型,并在自定义的数据类型中实现CompareTo方法  
class Teacher implements Comparable {  
    int num;  
    String name;  
  
    Teacher(String name, int num) {  
        this.num = num;  
        this.name = name;  
    }  
  
    public String toString() {  
        return "学号:" + num + " 姓名:" + name;  
    }  
  
    public int compareTo(Object o) {  
        Teacher ss = (Teacher) o;  
        int result = num > ss.num ? 1 : (num == ss.num ? 0 : -1);  
        if (result == 0) {  
            result = name.compareTo(ss.name);  
        }  
        return result;  
    }  
}  
  
public class TreeSetTest {  
    public static void main(String[] args) {          
        Set<Teacher> treeSet = new TreeSet<Teacher>();  
        treeSet.add(new Teacher("zhangsan", 2));  
        treeSet.add(new Teacher("lisi", 1));  
        treeSet.add(new Teacher("wangwu", 3));  
        treeSet.add(new Teacher("mazi", 3)); 
		
        System.out.println(treeSet);//直接输出
		
        Iterator itTSet = treeSet.iterator();//遍历输出
        while(itTSet.hasNext())  
            System.out.print(itTSet.next() + "\t");  
        System.out.println();  
    }   
}  
  1. Feature
  • We do not allow null values
  • Not allowed to repeat
  • Ordered
  1. Duplicate data screening method
    relies Comparable interface is not returned to 0 is determined.

LinkedHashSet (HashSet extension)

  1. Define : the bottom layer is an array of single chain + + + doubly linked list of red-black tree

  2. Features :

  • LinkedHashSet storage element is disordered, but due to the presence of doubly linked list, the order of an Element iteration is equal to the order of addition of elements, note this is not the access order
  • LinkedHashSet did not own methods, all methods inherited from its parent class HashSet, therefore, all operations LinkedHashSet way as if the same for HashSet operation.
  1. How to maintain insertion order
    LinkedHashSet use LinkedHashMap object to store its elements, the elements are inserted into LinkedHashSet in fact it is regarded as the key to save LinkedHashMap up.

Each key-value pair LinkedHashMap is through the interior of the static class Entry <K, V> instantiated. The Entry <K, V> class inherits HashMap.Entry class.

This adds two static class member variables, before and after insertion to maintain order LinkedHasMap elements. The two member variables point to an element of a front and rear, which makes doubly linked list LinkedHashMap have similar performance.

to sum up

  1. Are unrepeatable, hashset disorder, treeset order
  2. LinkedHashSet is hashset can maintain insertion order version
  3. Different deduplication implementation of internal
  4. treeset allow null
Published 36 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/s_xchenzejian/article/details/101512987