Java 7 collection type 6th-Implementation of Set

Source: Internet
Author: User
Tags addall

The Set interface defines some common Set operations, which are similar to the methods defined in the Collection interface. The AbstractSet abstract class only implements the equals (), hashCode (), and removeAll () methods, which is very simple. Interested readers can view them by themselves.


1. HashSet


Features of the HashSet class:It can quickly locate the unordered elements in the Set and the elements in the Set (the so-called unordered is not completely unordered, but it is not like the List set to save objects in the order of objects inserted ).
With the implementation of HashMap, the implementation of HashSet is very simple. You only need to save the elements in the Set as the key value in the Map.

Public class HashSet
 
  
Extends AbstractSet
  
   
Implements Set
   
    
, Cloneable, java. io. Serializable {private transient HashMap
    
     
Map; // use the map key to save the Set element private static final Object PRESENT = new Object (); // The value is an Object public HashSet () {map = new HashMap <> ();}/*** Constructs a new set containing the elements in the specified * collection. the HashMap is created with default load factor * (0.75) and an initial capacity sufficient to contain the elements in * the specified collection. */public HashSet (Collection
     C) {map = new HashMap <> (Math. max (int) (c. size ()/. 75f) + 1, 16); addAll (c) ;}// omit other constructors}
    
   
  
 
Public Iterator
 
  
Iterator () {// return map of the key value in the cyclic HashMap. keySet (). iterator ();} public boolean contains (Object o) {// search for the key value return map in HashMap. containsKey (o);} public boolean add (E e) {// key is the element to be added in the Set. The value is an empty Object return map. put (e, PRESENT) = null ;}
 

The objects in the Set implemented by the HashSet class must be unique. Therefore, you need to add the objects to the Set implemented by the HashSet class and implement the equals () method again, this ensures the uniqueness of the IDs of objects in the inserted collection.

The Set implemented by the HashSet class is sorted by hash code, and the storage location of the object is determined based on the object hash code, therefore, you need to add objects to the Set implemented by the HashSet class, and re-implement the hashCode () method to ensure that the objects in the inserted Set can be reasonably distributed in the Set, this allows you to quickly locate objects in a set.

Public class Person {private String name; private long id_card; public Person (String name, long id_card) {this. name = name; this. id_card = id_card;} public long getId_card () {return id_card;} public void setId_card (long id_card) {this. id_card = id_card;} public String getName () {return name;} public void setName (String name) {this. name = name;} public int hashCode () {// re-implement the hashCode () method final int PRIME = 31; int resu Lt = 1; result = PRIME * result + (int) (id_card ^ (id_card >>> 32); result = PRIME * result + (name = null )? 0: name. hashCode (); return result;} public boolean equals (Object obj) {// re-implement the equals () method if (this = obj) {return true ;} if (obj = null) {return false;} if (getClass ()! = Obj. getClass () {return false;} final Person other = (Person) obj; if (id_card! = Other. id_card) {return false;} if (name = null) {if (other. name! = Null) {return false ;}} else if (! Name. equals (other. name) {return false ;}return true ;}}
Compile the test program:

Public class TestSet {public static void main (String args []) {Set
 
  
HashSet = new HashSet
  
   
(); HashSet. add (new Person ("Mr. Ma", 22015); hashSet. add (new Person ("Miss Lee", 22018); hashSet. add (new Person ("Mr. Li", 22020); Iterator
   
    
It = hashSet. iterator (); while (it. hasNext () {Person person = it. next (); System. out. println (person. getName () + "" + person. getId_card ());}}}
   
  
 
The program running result is as follows:
Miss Li 22018
Mr. Li 22020
Mr. Ma 22015
If you want to keep the advantages of the HashSet class to quickly locate objects in the Set and save the objects in the Set in the order of insertion, You can implement the Set through the LinkedHashSet subclass of the HashSet class.

2. LinkedHashSet


LinkedHashSet, as its name implies, adds Linked support to the implementation of Hash. For LinkedHashSet, a linked list is connected to each node to ensure the order of determination. You can directly use the LinkedHashSet when you want to require efficient access performance with constant complexity and sorting at the same time.

It implements the Set interface. Each element stored in the Set must be unique because the Set does not store duplicate elements. However, the Set interface does not guarantee the order of elements to be maintained. LinkedHashSet has the query speed of HashSet and maintains the element Order (insertion order) using the linked list internally. Therefore, when the iterator is used to facilitate the Set, the result is displayed in the order of element insertion.

There is a constructor in HashSet, as follows:

 HashSet(int initialCapacity, float loadFactor, boolean dummy) {        map = new LinkedHashMap<>(initialCapacity, loadFactor); }    
This constructor has the package access permission and is implemented using javashashmap at the underlying layer. Therefore, javashashset obtains the instance by calling this constructor and maintains the element insertion sequence. The source code is as follows:

public class LinkedHashSet
 
     extends HashSet
  
      implements Set
   
    , Cloneable, java.io.Serializable {    private static final long serialVersionUID = -2851667679971038690L;    public LinkedHashSet(int initialCapacity, float loadFactor) {        super(initialCapacity, loadFactor, true);    }    public LinkedHashSet(int initialCapacity) {        super(initialCapacity, .75f, true);    }    public LinkedHashSet() {        super(16, .75f, true);    }    public LinkedHashSet(Collection
     c) {        super(Math.max(2*c.size(), 11), .75f, true);        addAll(c);    }}
   
  
 
Continue to write the previous test program.
Set
 
   hashSet = new HashSet
  
   ();
  
 
Change
Set
 
   hashSet = new LinkedHashSet
  
   ();
  
 
The output result is consistent with the insert sequence.


3. TreeSet


The TreeSet class not only implements the Set interface, but also implements the java. util. SortedSet interface to ensure that objects are obtained in an ascending order during collection traversal. Objects are arranged sequentially. Therefore, objects stored in the Set implemented by the TreeSet class must implement the Comparable interface. objects may be sorted progressively by the specified comparator, that is, objects in the Set implemented by the TreeSet class can be sorted by the comparator.
The following describes some source code of the TreeSet class:

Public class TreeSet
 
  
Extends AbstractSet
  
   
Implements NavigableSet
   
    
, Cloneable, java. io. Serializable {// use the key of NavigableMap to save the private transient NavigableMap element of the Set.
    
     
M; // use a PRESENT as the constructor of all values of the Map set private static final Object PRESENT = new Object (); // ---------- constructor ------------------------- // package access permission, creates a Set TreeSet (NavigableMap
     
      
M) {this. m = m;} // create public TreeSet () {this (new TreeMap
      
        ();} // Create a public TreeSet (Comparator
       Comparator) {this (new TreeMap <> (comparator);} public TreeSet (Collection
       C) {this (); // call the default constructor addAll (c) without parameters ); // Add existing elements in the Collection} // create a TreeSet public TreeSet (SortedSet
       
         S) {this (s. comparator (); addAll (s );}}
       
      
     
    
   
  
 

You can obtain some elements as follows:

 public NavigableSet
 
   subSet(E fromElement, boolean fromInclusive,E toElement,   boolean toInclusive) {        return new TreeSet<>(m.subMap(fromElement, fromInclusive,toElement,   toInclusive));    }    public NavigableSet
  
    headSet(E toElement, boolean inclusive) {        return new TreeSet<>(m.headMap(toElement, inclusive));    }    public NavigableSet
   
     tailSet(E fromElement, boolean inclusive) {        return new TreeSet<>(m.tailMap(fromElement, inclusive));    }    public SortedSet
    
      subSet(E fromElement, E toElement) {        return subSet(fromElement, true, toElement, false);    }    public SortedSet
     
       headSet(E toElement) {        return headSet(toElement, false);    }    public SortedSet
      
        tailSet(E fromElement) { return tailSet(fromElement, true); }
      
     
    
   
  
 


We can see from the several constructors above that the underlying layer is actually implemented through TreeMap.

Public class Person implements Comparable {private String name; private long id_card; public Person (String name, long id_card) {this. name = name; this. id_card = id_card;} public String getName () {return name;} public void setName (String name) {this. name = name;} public long getId_card () {return id_card;} public void setId_card (long id_card) {this. id_card = id_card;} public int compareTo (Object o) {// sort by serial number in ascending order by default Perso N person = (Person) o; int result = id_card> person. id_card? 1 :( id_card = person. id_card? 0:-1); return result ;}}
Public class TestSet {public static void main (String args []) {TreeSet
 
  
TreeSet = new TreeSet
  
   
(); Person p1 = new Person ("Mr. Ma", 22015); Person p2 = new Person ("Mr. Li", 22016); Person p3 = new Person ("Miss Wang ", 22018); Person p4 = new Person ("Mr. Yin", 22020); Person p5 = new Person ("Mr. Wang", 22012); treeSet. add (p1); treeSet. add (p2); treeSet. add (p3); treeSet. add (p4); treeSet. add (p5); System. out. println ("initialized set:"); Iterator
   
    
It = treeSet. iterator (); while (it. hasNext () {Person p = it. next (); System. out. println (p. getId_card () + "" + p. getName ();} System. out. println ("the set obtained by intercepting the previous part:"); it = treeSet. headSet (p1 ). iterator (); while (it. hasNext () {Person p = it. next (); System. out. println (p. getId_card () + "" + p. getName ();} System. out. println ("the set obtained by intercepting the middle part:"); it = treeSet. subSet (p1, p3 ). iterator (); while (it. hasNext () {Person p = it. next (); System. out. println (p. getId_card () + "" + p. getName ();} System. out. println ("the collection obtained by intercepting the following parts:"); it = treeSet. tailSet (p3 ). iterator (); while (it. hasNext () {Person p = it. next (); System. out. println (p. getId_card () + "" + p. getName ());}}}
   
  
 
The program running result is as follows:
Initialized set:
22012 Mr. Wang
22015 Mr. Ma
22016 Mr. Li
22018 Miss Wang
22020 Mr. Yin
The set obtained from the previous section is truncated:
22012 Mr. Wang
The set obtained by intercepting the intermediate part:
22015 Mr. Ma
22016 Mr. Li
The following part is taken to obtain the set:
22018 Miss Wang
22020 Mr. Yin
When using a Set implemented by the TreeSet class, you can also sort the objects in the Set by a separate comparator.
The comparator can be used as a separate class or an internal class of the corresponding class. In this example, the comparator is implemented by moving the internal class.
Import java. util. comparator; public class Person implements Comparable {private String name; private long id_card; public Person (String name, long id_card) {this. name = name; this. id_card = id_card;} public String getName () {return name;} public void setName (String name) {this. name = name;} public long getId_card () {return id_card;} public void setId_card (long id_card) {this. id_card = id_card;} public int compareT O (Object o) {// by default, Person person = (Person) o is sorted in ascending order of numbers; int result = id_card> person. id_card? 1 :( id_card = person. id_card? 0:-1); return result;} static class PersonComparator implements Comparator {public static final int NAME = 1; public static final int ID_CARD = 2; private int orderByColumn = 1; // by default, public static final boolean ASC = true; public static final boolean DESC = false; private boolean orderByMode = true; // The default value is public int compare (Object o1, Object o2) in ascending order. {// method for implementing the Comparator interface: Person p1 = (Person) o1; Person p2 = (Person) o2; int result = 0; // the default judgment result is equivalent to two objects: switch (orderByColumn) {// judgment sorting condition case 1: String s1 = CnToSpell. getFullSpell (p1.getName (); String s2 = CnToSpell. getFullSpell (p2.getName (); if (orderByMode) {// ascending result = s1.compareTo (s2);} else {// descending result = s2.compareTo (s1);} break; case 2: if (orderByMode) {// ascending result = (int) (p1.getId _ card ()-p2.getId _ card ());} else {// descending order result = (int) (p2.getId _ card ()-p1.getId _ card ();} break;} return result;} public void orderByColumn (int orderByColumn) {// used to set the sorting condition this. orderByColumn = orderByColumn;} public void orderByMode (boolean orderByMode) {// used to set the sorting method this. orderByMode = orderByMode ;}}}
Import java. util. *; public class TestSet {public static void main (String args []) {TreeSet
 
  
TreeSet1 = new TreeSet
  
   
(); Person p1 = new Person ("Mr. Ma", 22015); Person p2 = new Person ("Mr. Li", 22016); Person p3 = new Person ("Miss Wang ", 22018); treeSet1.add (p1); treeSet1.add (p2); treeSet1.add (p3); System. out. println ("sort by number in ascending order before customization:"); // creates a Set without customization. TreeSet is sorted by number in ascending order by default.
   
    
TreeSet2 = new TreeSet
    
     
(TreeSet1); // initializes the Iterator set through the constructor.
     
      
It1 = treeSet2.iterator (); while (it1.hasNext () {Person p = it1.next (); System. out. println (p. getId_card () + "" + p. getName ();} System. out. println ("sorted by number in descending order:"); // create a Set to sort by number in descending order. personComparator pc = new Person. personComparator (); // create the instance pc of the comparator (internal class. orderByColumn (Person. personComparator. ID_CARD); // sets the attribute pc for sorting. orderByMode (Person. personComparator. DESC); // sets the sorting method TreeSet.
      
        TreeSet3 = new TreeSet
       
         (Pc); // The comparator treeSet3.addAll (treeSet1) must be set through the constructor; // initialize the set Iterator
        
          It2 = treeSet3.iterator (); while (it2.hasNext () {Person p = it2.next (); System. out. println (p. getId_card () + "" + p. getName ());}}}
        
       
      
     
    
   
  
 
The program running result is as follows:
Sort by number in ascending order before customization:
22015 Mr. Ma
22016 Mr. Li
22018 Miss Wang
Sort by number in descending order after customization:
22018 Miss Wang
22016 Mr. Li
22015 Mr. Ma
























Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.