Dark Horse Programmer-java Foundation-Set Set

Source: Internet
Author: User
Tags comparable set set sorted by name

-----Java Training, Android training, iOS training,. NET training, look forward to communicating with you!

Set

The elements stored in set are unordered and cannot be duplicated. The removal method can only say iterators.

Set System

--| Set sub-interface, characterized in that elements are unordered, elements are not repeatable

--| HashSet: The underlying data structure is a hash table, which is thread insecure and out of sync.

--| TreeSet: You can sort the elements in the Set collection (Red-black tree)

HashSet guarantees the principle of element uniqueness

Guaranteed element uniqueness is mainly through the element hash value, when the hash value is not considered to be different elements, when the hash value is dependent on the elements of the Equals method, to determine whether the same object, When the Equals method returns False, it is considered not the same object at this point, the object can still be stored in hashset, when equals returns True as the same object, when the current object cannot be persisted in HashSet. It is important to note that the Equals method is only judged when the hashcode is the same.

TreeSet guarantees the principle of element uniqueness

The data structure is a red-black tree, which guarantees the uniqueness of the elements in two ways:

    1. To make the element itself comparable, the element is required to implement the comparable interface and overwrite the CompareTo () method.
    2. When the first method does not meet the requirements, you can take the second method, customize the comparer, and then implement the comparator interface and overwrite the Compare () method.

Case Demo:

1.hashSet implementation Element Uniqueness

Package set;/** * Requirements: The person object is deposited into the hashset and the same name is stated as the same as the age. * Step: * 1, define the person class, including name, age property * 2, to implement HashSet element uniqueness needs to overwrite hashcode (), Equals method * 3, iterate out each element * * */import Java.util.HashSet;    Import Java.util.iterator;class Person {private String name;    private int age;        Person (String Name,int age) {this.name=name;    This.age=age;    } public String GetName () {return name;    } public int Getage () {return age;    }//Replication Hashcode method public int hashcode () {return This.name.hashCode () + age*100; }//Replication Equals method public Boolean equals (Object o) {if (! (        o instanceof person) return false;        Person p= (person) o;    Return This.name.equals (p.name) &&this.age==p.age;        }}public class Hashsetdemo {public static void main (string[] args) {HashSet hs=new HashSet ();        Hs.add (New person ("lisi01", 20));        Hs.add (New person ("lisi02", 30));        Hs.add (New person ("lisi03", 40)); Hs.add (New PErson ("lisi03", 40));//the same element Iterator It=hs.iterator ();            while (It.hasnext ()) {person p= (person) it.next (); System.out.println ("My name is:" +p.getname () + ";        And my age is: "+p.getage ()); }    }}

2, TreeSet to achieve the uniqueness of the element

Package Set;import Java.util.comparator;import Java.util.iterator;import java.util.treeset;/** * Requirement 1: The person object is deposited into the hashset, and the same name is specified with the same age, sorted by name. * Requirement 2: Custom collation, sorted by age, when age is in natural order by name * Step: * 1, define person class, including name, age attribute * 2, to implement TreeSet element uniqueness requires implementation of comparable interface, and overwrite CompareTo ( Method * 3, custom comparator, implement comparator interface, overwrite compare () method * * */class person implements comparable<person>{private String nam    E    private int age;        Person (String Name,int age) {this.name=name;    This.age=age;    } public String GetName () {return name;    } public int Getage () {return age;        } public int compareTo (person o) {int num=this.name.compareto (o.name);        if (num==0) return this.age-o.age;    return num;        }}//second sort, sorted by age class Mycompatator implements comparator{//Sort public int Compare by name (object O1, Object O2) {        Person p1= (person) O1;        Person p2= (person) O2;        int Num=p1.getname (). CompareTo (P2.getname ()); if (num==0)//when nameIf age is the same, it is considered the same person.            {if (P1.getage () >p2.getage ()) return 1;            else if (P1.getage () <p2.getage ()) return-1;        else return 0;    } return num; }}public class Treesetdemo {public static void main (string[] args) {TreeSet ts=new TreeSet (New Mycompatator ())        ;        Ts.add (New person ("lisi01", 20));        Ts.add (New person ("lisi02", 40));        Ts.add (New person ("lisi03", 40));        Ts.add (The new person ("lisi03", 40));//the same element Iterator It=ts.iterator ();            while (It.hasnext ()) {person p= (person) it.next ();        System.out.println ("My name is:" +p.getname () + ", and my Age is:" +p.getage ()); }            }}

Dark Horse Programmer-java Foundation-Set Set

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.