Usage of the set interface in Java

Source: Internet
Author: User
Tags comparable

The set interface in Java has the following characteristics:

    • Duplicate elements are not allowed;
    • The position of the elements in the collection is not sequential;
    • An element with and only one value of NULL.

Because the set interface in Java mimics the mathematical set abstraction, the corresponding mathematical set has the following characteristics:

    • Cross-specific: In a collection, any two elements are considered to be different, that is, each element can appear only once.
    • Disorder: In a set, each element's status is the same, and the elements are unordered. You can define an order relationship on a collection, and after you define the order relationship, the elements can be sorted by order. But in terms of the nature of the collection itself, there is no definite order between the elements.
    • The nature of an empty set: An empty assembly is a subset of everything

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. The set has exactly the same interface as the collection, so there is no additional functionality. In fact set is collection, but behaves differently.

The main thing that implements the set interface is HashSet, TreeSet, and Linkedhashset, which is that 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 fairly complex way to store elements, using HashSet to get the most out of the elements in the collection, with very high efficiency (space-time). Whether the same object is Pangdong according to Hashcode and equals, if Hashcode is the same, and equals returns True, it is the same object and cannot be stored repeatedly.

 PackageCn.set;ImportJava.util.HashSet;ImportJava.util.Set;classstudent{intID;  PublicStudent (intID) { This. ID =ID; } @Override PublicString toString () {return  This. id+ ""; } @Override Public inthashcode () {return  This. ID; } @Override Public Booleanequals (Object obj) {if(objinstanceofStudent) {Student Stu=(Student) obj; if(Stu.id = = This. ID)return true; }        return false; }} Public classHashsettest { Public Static voidMain (string[] args) {Set<Student> set =NewHashset<student>(); Student S1=NewStudent (1); Student S2=NewStudent (1); Student S3=NewStudent (2);        Set.add (S1);        Set.add (S2);        Set.add (S3);  for(Student s:set) {System.out.println (s); }    }}

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 annotate both methods, all student objects are considered different objects and can be stored.

2.TreeSet

TreeSet can also not hold duplicate objects, but TreeSet will be automatically sorted, if the stored objects can not be sorted will be an error, so the object must be stored to specify the collation. Sorting rules include natural sorting and customer ordering.

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

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

The following example stores a naturally ordered object with TreeSet:

 PackageCn.set;ImportJava.util.Set;ImportJava.util.TreeSet;classStudent1ImplementsComparable<student1>{    intID;  PublicStudent1 (intID) { This. ID =ID; } @Override PublicString toString () {return  This. id+ ""; } @Override Public inthashcode () {return  This. ID; } @Override Public Booleanequals (Object obj) {if(objinstanceofStudent1) {Student1 Stu=(Student1) obj; if(Stu.id = = This. ID)return true; }        return false; }     Public intcompareTo (Student1 o) {return( This. id-o.id); }} Public classTreesettest { Public Static voidMain (string[] args) {Set<Student1> set =NewTreeset<student1>(); Student1 S1=NewStudent1 (5); Student1 S2=NewStudent1 (1); Student1 S3=NewStudent1 (2); Student1 S4=NewStudent1 (4); Student1 S5=NewStudent1 (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 is:
1
2
3
4
5

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

 PackageCom.set;ImportJava.util.Set;ImportJava.util.TreeSet;classStudent1ImplementsComparable<student1>{    intID;  PublicStudent1 (intID) { This. ID =ID; } @Override PublicString toString () {return  This. id+ ""; } @Override Public inthashcode () {return  This. ID; } @Override Public Booleanequals (Object obj) {if(objinstanceofStudent1) {Student1 Stu=(Student1) obj; if(Stu.id = = This. ID)return true; }        return false; }     Public intcompareTo (Student1 o) {return( This. id-o.id); }} Public classTreesettest { Public Static voidMain (string[] args) {Set<Student1> set =NewTreeset<student1>(); Student1 S1=NewStudent1 (5); Student1 S2=NewStudent1 (1); Student1 S3=NewStudent1 (2); Student1 S4=NewStudent1 (4); Student1 S5=NewStudent1 (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 is:
5
4
3
2
1

We all know that the list is stored in the order of insertion, in fact, you can also use natural sort and customer sort to sort the list set, we see:

 PackageCn.set;Importjava.util.ArrayList;Importjava.util.Collections;Importjava.util.List;classMySort1ImplementsJava.util.comparator<student3>{     Public intCompare (Student3 O1, Student3 O2) {returno2.id-o1.id; }}classStudent3ImplementsComparable<student3>{    intID;  PublicStudent3 (intID) { This. ID =ID; } @Override PublicString toString () {return  This. id+ ""; }     Public intcompareTo (Student3 o) {return( This. id-o.id); }} Public classListsort { Public Static voidMain (string[] args) {List<Student3> list =NewArraylist<student3>(); Student3 S1=NewStudent3 (5); STUDENT3 S2=NewStudent3 (1); Student3 S3=NewStudent3 (2); Student3 S4=NewStudent3 (4); Student3 S5=NewStudent3 (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 SortCollections.sort (list,NewMySort1 ());    SYSTEM.OUT.PRINTLN (list); }}

The output is:
[5, 1, 2, 4, 3]
[1, 2, 3, 4, 5]
[5, 4, 3, 2, 1]

This article was reproduced from: http://www.cnblogs.com/liuling/archive/2013/04/16/set.html

Usage of the set interface in Java

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.