Javase Getting Started learning the set interface of 36:java set framework and its implementation class HashSet and TreeSet

Source: Internet
Author: User

A set interface

The set interface can correspond to the concept of a set in mathematics. The set interface is a sub-interface of the collection interface, and the set interface is not specified between multiple objects

Explicit order. Please refer to the API documentation (how important it is to take the API documentation with you at any time), as described in the collection interface.

With. Just behave differently (set does not allow repeating elements).

The set collection does not allow repeating elements, because set determines that two objects are the same not using the = = operator, but rather by the Equals () method. That is, two objects

Using the Equals () method to compare the return True,set cannot accept two equal objects.

Let's do a test:

Import java.util.*;p ublic class testset{public      static void Main (string[] args) {          set<string> books = new Ha Shset<string> ();                    Add a String Object          Books.add (new string ("I am the object of the Test"));                    Add a String object again,          //Because two string objects compare equality by the Equals method, add fails, return false          Boolean result = Books.add ("I am the object of the test");                    SYSTEM.OUT.PRINTLN (result);                    The following output sees only one element of the collection          System.out.println (books);        }  

Operation Result:


Description: In the program, the book Collection two times the string object added is obviously not an object (the program uses the new keyword to create a string object),

When the = = operator is used to determine the return false, the Equals method is used to return true, so it cannot be added to the set collection, only one meta can be output at a time.

Of

methods defined in the set interface:



The knowledge in the set interface is also applicable to HashSet, TreeSet and other implementation classes. The set interface implementation class provided in the J2SDK API has

HashSet, TreeSet, and so on, we have to introduce each.

Two Realization class HashSet

HashSet (hash set) is an important implementation class for the set interface. HashSet uses a rather complex way to store elements, using

The hashset is able to get the elements in the collection as quickly as possible, with very high efficiency (space-time). According to the Hashcode () method and the Equals () method

If the break is the same object, if the Hashcode () method is the same, and the Equals () method returns True, it is the same object and cannot be stored repeatedly.

HashSet the methods defined in the implementation class:


HashSet stores the elements of a collection by a hash algorithm, so it has good access and lookup performance.

features of HashSet:

(1) HashSet is not synchronous, multiple thread accesses are required to ensure synchronization through code.

(2) The collection element value can be null.

(3) HashSet set the criterion for judging the equality of two elements is that two objects are compared by Equals () method, and two objects are hashcode () square

The return value of the method is also equal.

Instance code:

Import java.util.*;p ublic class Testhashset  {public      static void Main (string[] args) {          set<object> Books = new Hashset<object> ();          Add 2 a objects, 2 B objects, and 2 C object          Books.add (new A ()) to the Books collection respectively.          Books.add (New A ());          Books.add (New B ());          Books.add (New B ());          Books.add (New C ());          Books.add (New C ());          SYSTEM.OUT.PRINTLN (books);      }  } The Equals method of class A always returns TRUE, but does not override its Hashcode () method  class A{public      boolean equals (Object obj)  {          return true;      }  }  The Hashcode () method of Class B always returns 1, but does not override its Equals () method  class b{public      int hashcode () {          return 1;      }  }  The Hashcode () method of class C always returns 2, but does not override its Equals () method  class c{public      int hashcode () {          return 2;      }      public boolean equals (Object obj) {          return true;      }  }  

Operation Result:


Description

(1) The ToString () method provided by the object class always returns the class name +@+hashcode (16 decimal number) value of the implementation class of the objects, so you can see the above

The result of the program output. You can output your desired form by overriding the ToString () method.

(2) Even if 2 a objects return true through Equals (), the hashset still treats them as 2 objects, even if the hashcode () of 2 B objects is returned

Return the same values, but HashSet still treats them as 2 objects. That is, if you put an object into HashSet, if you override that object, the Equals () party

The Hashcode () method should also be rewritten. The rule is that if 2 objects return true through the Equals method, the two objects '

Hashcode should also be the same.

Knowing the method above, let's take a look at the following example:

Import java.util.*;p Ublic class Testhashset {public    static void Main (string[] args) {        set<student> Set = NE W hashset<student> ();        Add two identical objects        Student s1 = new Student (1);        Student s2 = new Student (1);        Student s3 = new Student (2);        Set.add (S1);        Set.add (S2);        Set.add (S3);//Traverse object in set for        (Student s:set) {            System.out.println (s);}}    } Class student{    int id;    public Student (int id) {        this.id = ID;    }    @Override public    String toString () {        return this.id+ "";    }    @Override public    int hashcode () {        return this.id;    }    @Override public    boolean equals (Object obj) {        if (obj instanceof Student) {            Student  stu = (Student) obj;            if (stu.id = = this.id)                return true;        }        return false;    }}

Operation Result:


As shown in the previous example, after overriding the Hashcode () and Equals () methods to differentiate the consent object, the same object cannot be stored. If you comment the two

method, all student objects are considered different objects and can be stored.

Three realization class TreeSet

TreeSet can also not store duplicate objects, but TreeSet will be automatically sorted, if the stored objects can not be sorted will be error, so the objects stored

Collation must be specified.

TreeSet Implement the class definition method:



sorting rules include natural sorting and customer ordering.

(1) Natural sort: TreeSet which object is to be added implements the Java.lang.Comparable interface on which object class, and overrides

The Comparato () method, which returns 0, represents the same object, otherwise a different object.

(2) Customer sequencing: Establish a third-party class and implement the Java.util.Comparator interface. and override the method. Defines the form of a collection as TreeSet ts =

New TreeSet (new Third Party category ());

The following example stores a naturally ordered object with TreeSet:

Import java.util.*;p Ublic class Testtreeset {public static void main (string[] args) {set<student1> Set =        New Treeset<student1> ();        Student1 S1 = new Student1 (5);        Student1 s2 = new Student1 (1);        Student1 s3 = new Student1 (2);        Student1 S4 = new Student1 (4);        Student1 S5 = new Student1 (3);        Set.add (S1);        Set.add (S2);        Set.add (S3);        Set.add (S4);        Set.add (S5);        for (Student1 s:set) {System.out.println (s);    }}}class Student1 implements comparable<student1>{int id;    public Student1 (int id) {this.id = ID;    } @Override Public String toString () {return this.id+ "";    } @Override public int hashcode () {return this.id; } @Override public boolean equals (Object obj) {if (obj instanceof Student1) {Student1 stu = (stu            DENT1) obj;        if (stu.id = = this.id) return true; } RetuRN false;    } public int compareTo (Student1 o) {return (this.id-o.id); }}

Operation Result:


The following example stores a client-ordered object with TreeSet:

Import java.util.*;p Ublic class TestTreeSet2 {public static void main (string[] args) {set<student2> Set        = new Treeset<student2> (new Mysort ());        Student2 S1 = new Student2 (5);        Student2 s2 = new Student2 (1);        Student2 s3 = new Student2 (2);        Student2 S4 = new Student2 (4);        Student2 S5 = new Student2 (3);        Set.add (S1);        Set.add (S2);        Set.add (S3);        Set.add (S4);        Set.add (S5);        for (Student2 s:set) {System.out.println (s);        }}}class Mysort implements java.util.comparator<student2>{public int compare (Student2 O1, Student2 O2) {    return o2.id-o1.id;    }}class student2{int id;    public Student2 (int id) {this.id = ID;    } @Override Public String toString () {return this.id+ "";    } @Override public int hashcode () {return this.id;       } @Override public boolean equals (Object obj) {if (obj instanceof Student2) {     Student2 stu = (Student2) obj;        if (stu.id = = this.id) return true;    } return false; }}

Operation Result:

Description: As can be seen from the running result, TreeSet is not sorted according to the order in which the elements are inserted, but rather by the actual values of the elements.

TreeSet uses the red-black tree's data structure to sort the elements, which are described in the following article.

Javase Getting Started learning the set interface of 36:java set framework and its implementation class HashSet and TreeSet

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.