Set of java Collection

Source: Internet
Author: User

Set

A collection that does not contain duplicate elements. To be exact, set does not contain e1 and e2 elements that meet e1.equals (e2), and can contain at most one null element;

This implementation is not synchronous. If multiple threads access a set at the same time and at least one thread modifies the set, it must maintain external synchronization, it is usually done by performing a synchronization operation on the object that encapsulates the set. If such an object does not exist, it will be: Collections. synchronizedSet ();

HashSet

The elements in the set are unordered and do not overlap. The data structure is a hash table;

Principle of ensuring element uniqueness: determines whether the HashCode value of the element is the same. If the HashCode value is the same, The equals method of the element will continue to be determined to be true; when an object is stored in a HashSet set, you cannot modify the fields of the object involved in calculating the hash value. If modified, internal leakage may occur;

TreeSet

You can sort the elements in the Set:

(1) make the elements have a comparison, and the elements need to implement the Comparable interface to overwrite the compareTo method. This method also becomes the natural order of the elements;

(2) The element itself does not have a comparison, or the comparison is not necessary. In this case, the set itself needs to have a comparison. When the set is initialized, the comparison method [defines the Comparator (Comparator <> Interface) and transmits it as a parameter to the constructor of the set]

The following two methods are required for the TreeSet interface:

Class Obj implements Comparable <Obj> {

Public int compareTo (Obj o ){

Return this. name. compareTo (o. name );

}}

Class Comptor implements Comparator <ComptorObj> {

@ Override

Public int compare (ComptorObj o1, ComptorObj o2 ){

Return o1.name. compareTo (o2.name );

}}

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.