The use method of set interface in Java _java

Source: Internet
Author: User
Tags comparable

The set interface in Java has the following characteristics:

Duplicate elements are not allowed;
The element position in the collection is not in order;
There is only one element with a value of NULL.

Because the set interface in Java mimics the set abstraction in mathematics, the corresponding attribute of the set in mathematics is:

The opposite sex: in a set, any two elements are considered to be different, that is, each element can only appear once.
disorder: in a set, the status of each element is the same, and the elements are unordered. The order relation can be defined on the set, and after the order relation is defined, the elements can be sorted according to the order relation. But in terms of the characteristics of the set itself, there is no inevitable order between elements.
the nature of the empty set: The null is a subset of all sets

The set does not save duplicate elements. The most commonly used in set is test attribution, and you can easily ask if an object is in a set. Set has exactly the same interface as collection, so there is no additional functionality. In fact set is collection, but behavior is different.

The main features of the set interface are HashSet, TreeSet, and Linkedhashset. Each of the same items is saved only one copy. They also have different points, the difference is as follows:

1.HashSet:

HashSet uses a rather complex way of storing elements, and using HashSet to get the elements in the collection as quickly as possible is highly efficient (in space for time). is based on hashcode and equals to Pangdong whether the same object, if hashcode, and equals returns True, is the same object and cannot be stored repeatedly.

Package cn.set;

Import Java.util.HashSet;
Import Java.util.Set;

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;
 }
}
public class Hashsettest {public
 static void Main (string[] args) {
  set<student> Set = new Hashset<stud Ent> ();
  Student S1 = new Student (1);
  Student s2 = new Student (1);
  Student s3 = new Student (2);
  Set.add (S1);
  Set.add (S2);
  Set.add (S3);
  for (Student s:set) {
   System.out.println (s);
  }
 }
}

As shown in the example above, the hashcode () and Equals () methods are rewritten to distinguish the object from the same object. If you annotate both methods, all student objects are considered different objects and can be stored.

2.TreeSet

TreeSet also cannot hold duplicate objects, but TreeSet will automatically sort, and errors will be given if the objects are not sorted, so the objects that are stored must specify collations. Sorting rules include natural sorting and customer sorting.

① Natural Sort: TreeSet to add which object on which object class to implement the Java.lang.Comparable interface, and override the Comparato () method, return 0 means the same object, otherwise different objects.

② Customer Sort: Create a third party class and implement Java.util.Comparator interface. and override the method. The definition set form is TreeSet ts = new TreeSet (new Third party Class ());

The following example uses TreeSet to store objects that are naturally sorted:

Package cn.set;
Import Java.util.Set;

Import Java.util.TreeSet;
 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 = (Student1) obj;
  if (stu.id = = this.id) return true;
 return false;
 public int compareTo (Student1 o) {return (this.id-o.id); } public class Treesettest {public static void main (string[] args) {set<student1> Set = new Treeset<stude
  Nt1> ();
  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);

 }
 }

}

The output results are:

The following example uses TreeSet to store objects sorted by the customer:

Package com.set;
Import Java.util.Set;

Import Java.util.TreeSet;
 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 = (Student1) obj;
  if (stu.id = = this.id) return true;
 return false;
 public int compareTo (Student1 o) {return (this.id-o.id); } public class Treesettest {public static void main (string[] args) {set<student1> Set = new Treeset<stude
  Nt1> ();
  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);

 }
 }

}

The output results are:

We all know that list stored in accordance with the order of insertion, in fact, you can also use natural sorting and customer sorting list set, please see:

Package cn.set;
Import java.util.ArrayList;
Import java.util.Collections;

Import java.util.List; Class MySort1 implements java.util.comparator<student3>{public int compare (Student3 O1, Student3 O2) {return O2
 . id-o1.id;
 Class STUDENT3 implements comparable<student3>{int id;
 public Student3 (int id) {this.id = ID;
 @Override public String toString () {return this.id+ "";
 public int compareTo (Student3 o) {return (this.id-o.id); } public class Listsort {public static void main (string[] args) {list<student3> List = new Arraylist<stud
  Ent3> ();
  Student3 S1 = new Student3 (5);
  Student3 s2 = new Student3 (1);
  Student3 s3 = new Student3 (2);
  Student3 S4 = new Student3 (4);
  Student3 S5 = new Student3 (3);
  List.add (S1);
  List.add (S2);
  List.add (S3);
  List.add (S4);
  List.add (S5);
  SYSTEM.OUT.PRINTLN (list);
  Natural sort: collections.sort (list);
  SYSTEM.OUT.PRINTLN (list);
  Customer sort Collections.sort (list, new MySort1 ()); SysteM.OUT.PRINTLN (list);

 }
}

The output results are:
[5, 1, 2, 4, 3]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

Here is a description of the set collection interface in Java to implement the principle of not duplicating the inserted object:

In the Java collection, the rule that determines whether two objects are equal is:

1), to determine whether the hashcode of two objects are equal
if not equal, the two objects are not equal, complete
If equal, transfer to 2)
(This is only to improve the storage efficiency of the requirements, in fact, can not, in theory, but if not, the actual use of efficiency will be greatly reduced, so we here to do it as required.) We will focus on this issue later. )
2), to determine whether two objects are equal to the equals operation
if not equal, two objects are considered unequal
If equal, two objects are considered equal (equals () is the key to determining whether two objects are equal)

For objects of the generic class (other than the encapsulated type object such as String):

If the generic class does not override the Hashcode () and Equals () methods, then its object is compared to the hashcode () method in the inherited object class, and the Hashcode () method in the object class is a local method that compares the return value of the method. Compare the address of the object (reference address) and use the new method to create objects of the same content, two of which are of course different objects. Unless you override the Hashcode () method. The Equals () method defined in the object class is also a comparison of the object's address. In a word: if you do not rewrite the hashcode () and Equals () methods of the normal class, the object reference address in the Set collection is not the same, and the object is not duplicated.

For objects such as String, Integer, double And so on):

Because these encapsulated classes themselves have overridden the hashcode () method, the return value of the overridden method is related to the content of the object, not to the reference address. The Equals () method in these encapsulated classes is also overridden to compare the contents of the object, rather than the reference address. A word Summary: Objects of class string are compared to their contents in the collection, and the same content overrides existing objects.

The above is the entire content of this article, I hope to help you learn.

Related Article

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.