Set of java Sets

Source: Internet
Author: User

Set of java Sets

The set can store multiple objects, but it does not remember the storage sequence of elements or allow repeated elements in the set (different set sets have different judgment methods ).

 

1.HashSet class

HashSet stores elements in a set based on the Hash algorithm, which provides good access and search performance. When some elements are added to a HashSet, The HashSet obtains the HashCode value of the object based on the HashCode () method of the object, and then determines the position of the element based on the value of the HashCode.

Features of HashSet: 1. The storage sequence and addition sequence are different.

2. HashSet is not synchronous. If multiple threads access a HashSet at the same time, if two or more threads modify the values in the Set, the thread must be synchronized through code.

3. HastSet allows null elements in the set.

In a HashSet set,To determine whether two elements are the same, the two objects are equal through the equals () method, and the return values of the HashCode () method are equal.If two elements are equal through the equals () method, and the return value of HashCode () is different, HashSet saves the two objects in different places.

Note:If you add a variable object to a HashSet and the subsequent object modifies the instance variable of the variable object, it may be the same as other elements in the set.

Class R {int count; public R (int count) {this. count = count;} public String toString () {return "R [count:" + count + "]";} public boolean equals (Object obj) {if (this = obj) return true; if (obj! = Null & obj. getClass () = R. class) {R r = (R) obj; return this. count = r. count;} return false;} public int HashCode () {return this. count ;}} public class HashSetTest {public static void main (String [] args) {HashSet hs = new HashSet (); hs. add (new R (5); hs. add (new R (-3); hs. add (new R (9); hs. add (new R (-2); // output: [R [count: 9], R [count: 5], R [count:-3], R [count:-2] System. out. println (hs); Iterator it = hs. iterator (); R first = (R) it. next (); first. count =-3; // output: [R [count:-3], R [count: 5], R [count:-3], R [count: -2] System. out. println (hs); // output: whether to include an object whose count is-3: false System. out. println ("whether to include objects whose count is-3:" + hs. contains (new R (-3); // output: whether to include an object whose count is-2: false System. out. println ("whether to include objects whose count is-2:" + hs. contains (new R (-2 )));}}

In this example, the code first. count =-3 changes the instance variable in the set and places the count as-3 element where count is 9. As a result, HashSet cannot accurately access the element.An error occurs when other elements are identified, for example, whether the set contains-2 or-3.

(The above sentence is something I understand myself. I don't feel very good about it. Let's take a look at it for me)

2. LinkedHashSet class

LikedHashSet is a subclass of HashSet. It also determines the storage location of elements based on the HashCode value of the elements. However, it can also maintain the order of adding elements using a linked list, this allows elements to be saved in the insert sequence.

Public class LinkHashSetTest {public static void main (String [] args) {LinkedHashSet lh = new LinkedHashSet (); lh. add (1); lh. add (2); lh. add (3); // output: [1, 2, 3] System. out. println (lh); lh. remove (1); lh. add (1); // output: [2, 3, 1] System. out. println (lh );}}

3. TreeSet

TreeSet is the implementation class of the SortedSet interface. TreeSet ensures that the elements in the set are in the sorting State (the so-called sorting State means that the elements are sorted according to certain rules, such as ascending and descending ).

Compared with the HashSet set.

 Comparator comparator ():If the TreeSet uses custom sorting, this method returns the Comparator used for custom sorting. If the natural sorting is used, null is returned.

Object first ():Returns the first element of the set.

Object last ():Returns the last element of the set.

Object lower (Object e ):Returns the element that is located before the specified Element e in the collection (that is, the element smaller than the maximum element of the specified element, the reference Element e does not need to be an element in the set ).

Object higher (Object e ):Returns the element that is located after the specified Element e in the collection (that is, the smallest element greater than the specified element, and the reference Element e does not need to be an element in the set ).

SortedSet subSet (Object fromElement, Object toElement ):Returns all the elements in the set between fromElemt and toElement (including fromElent itself, excluding toElement itself ).

SortedSet headSet (Object toElement ):Returns a subset of the set, which consists of elements smaller than the toElement.

SortedSet tailSet (Object fromElement ):Returns a subset of the set, which consists of elements greater than or equal to fromElement.

Public class TreeSetTest {public static void main (String [] args) {TreeSet ts = new TreeSet (); ts. add (5); ts. add (2); ts. add (10); ts. add (-9); // output: null proves to be a natural sorting System. out. println (ts. comparator (); // output:-9 System. out. println (ts. first (); // output: 10 System. out. println (ts. last (); // output: 2 System. out. println (ts. lower (3); // output: 10 System. out. println (ts. higher (5); // output [5, 10] System. out. println (ts. subSet (3, 12); // output: [-9, 2, 5] System. out. println (ts. headSet (10); // output: [5, 10] System. out. println (ts. tailSet (5 ));}}

TreeSet supports two sorting methods: Natural sorting and custom sorting. By default, TreeSet uses natural sorting.

Natural sorting:TreeSet calls the compareTo (Object obj) method of the Set element to compare the size relationship between the elements and arrange the set in ascending order. This method is called natural sorting.

Custom sorting:Custom sorting is based on user requirements and needs to be designed by yourself. If you want to customize sorting, for example, you can use the Comparator interface to help sort data in descending order.

PS:

1. If you want the TreeSet to run properly, the TreeSet can only add the same type of objects.

2. the only criterion for determining equal elements in a TreeSet set is that 0 is returned after two objects are compared using the comparator (Object obj) method; otherwise, they are considered unequal.

3. EnumSet class

The EnumSet class is a collection class designed for enumeration classes. All elements in the EnumSet must be enumeration values of the specified enumeration type. This enumeration type is explicitly or implicitly specified when an EnumSe class is created. The collection elements of the EnumSet are also ordered. The EnumSet determines the sequence of the collection elements by defining the enumerated values in the Enum class.

EnumSet provides the following common class methods to create an EnumSet object:
EnumSet allOf (Class elementType ):Creates an EnumSet that contains all enumeration values in the specified enumeration class.

EnumSet complement (EnumSet s ):Create an EnumSet whose element type is the same as that in the specified EnumSet. The new EnumSet contains the EnumSet that is not included in the original set, the remaining enumeration values of this enumeration class (the new EnumSet set and the collection element in the original EnumSet set are all enumeration values in this enumeration class ).

EnumSet copyOf (Collection c ):Use a common set to create an EnumSet set.

EnumSet copyOf (EnumSet s ):Create an EnumSet set that corresponds to the specified EnumSet.

EnumSet noneOf (Class elementType ):Create an empty EnumSet set whose element type is the specified enumeration type.

EnumSet of (E first, E... rest ):Create an EnumSet that contains one or more enumerations. The input enumerated values must belong to the same enumeration class.

EnumSet range (E from, E ):Create an EnumSet from THE from enumerated value to all enumerated values in the to enumerated value range.

Enum Season {SPRING, SUMMER, FALL, WINTER} public class EnumSetTest {public static void main (String [] args) {EnumSet es1 = EnumSet. allOf (Season. class); // output: [SPRING, SUMMER, FALL, WINTER] System. out. println (es1); EnumSet es2 = EnumSet. noneOf (Season. class); // output: [] System. out. println (es2); es2.add (Season. WINTER); es2.add (Season. SPRING); // output: [SPRING, WINTER] System. out. println (es2); EnumSet es3 = EnumSet. of (Season. SPRING, Season. WINTER); // output: [SPRING, WINTER] System. out. println (es3); EnumSet es4 = EnumSet. range (Season. SPRING, Season. WINTER); // output: [SPRING, SUMMER, FALL, WINTER] System. out. println (es4); EnumSet es5 = EnumSet. complementOf (es4); // output: [] System. out. println (es5 );}}

------------ "Crazy java handout" 8.3set 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.