Set set of Java collections

Source: Internet
Author: User
Tags set set

A set collection can store multiple objects, but it does not remember the order in which the elements are stored, nor does it allow duplicate elements in the collection (different set sets have different methods of judging).

1.HashSet class

HashSet stores the elements in the collection according to the hash algorithm, which provides good access and lookup performance. When adding elements to HashSet, HashSet will get the hashcode value of the object based on the Hashcode () method of the object, and then determine the position of the element based on the values of those hashcode.

HashSet features: 1. The order of storage and the sequence of additions are different

2.HashSet is not synchronous, and if multiple threads access a hashset at the same time, assuming that two or more threads have modified the values in the collection, the thread must be synchronized through code.

3.HastSet allows the elements in the collection to be null.

In the HashSet collection, the criteria for judging the two elements are the same: two objects are equal through the Equals () method, and the return value of the Hashcode () method is equal. If there are two elements that compare equality through the Equals () method, and the return value of Hashcode () is different, HashSet saves the two objects in a different place.

Note: If you add a Mutable object to HashSet, the subsequent object modifies the variable object's instance variable, which may cause it to be the same as other elements in the collection.

classr{intcount;  PublicRintcount) {         This. count=count; }     PublicString toString () {return"R[count:" + Count + "]"; }     Public Booleanequals (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 inthashcode () {return  This. Count; }} Public classHashsettest { Public Static voidMain (string[] args) {HashSet hs=NewHashSet (); Hs.add (NewR (5)); Hs.add (NewR (-3)); Hs.add (NewR (9)); Hs.add (NewR (-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: Contains the object with a count of-3: falseSystem.out.println ("does not contain a count of-3 object:" + hs.contains (NewR (-3))); //output: Contains the object with a count of-2: falseSystem.out.println ("does not contain a count of-2 object:" + hs.contains (NewR (-2))); }}

In this example, the code first.count=-3 changes the instance variables in the collection, placing the count-3 element where the count is 9, resulting in hashset not being able to access the element accurately. Other elements can also be judged as errors, such as determining whether a collection contains -2,-3.

(The above sentence is my own understanding, the total feeling is not very right, everyone help me to see)

2.LinkedHashSet class

Likedhashset is a subclass of HashSet, which also determines where an element is stored based on its hashcode value, but it can use a linked list to maintain the order in which elements are added, allowing elements to be saved in the order in which they are inserted.

 Public classLinkhashsettest { Public Static voidMain (string[] args) {linkedhashset LH=NewLinkedhashset (); 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, and TreeSet can guarantee that the set elements are in the sort state (the so-called sort state, that is, the elements are sorted according to certain rules, such as ascending, descending order).

Compared to the HashSet collection.

Comparator Comparator (): If TreeSet takes a custom sort, the method returns the Comparator used for the custom sort, and returns null if the natural sort is used.

Object First (): returns the element in the collection.

Object Last (): returns the final element in the collection.

object Lower (Object e): returns the element that precedes the specified element e in the collection (that is, the largest element less than the specified element, and the reference element e does not have to be an element in the collection).

object Higher (Object e): returns the element 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 have to be an element in the collection).

SortedSet Subset (object fromelement, Object toelement): returns all the elements in the collection between FROMELEMT and Toelement (containing the fromelent itself, Does not contain the toelement itself).

SortedSet HeadSet (Object toelement): Returns a subset of this set, consisting of elements less than toelement.

SortedSet Tailset (Object fromelement): Returns a subset of this set consisting of elements greater than or equal to fromelement.

 Public classTreesettest { Public Static voidMain (string[] args) {TreeSet ts=NewTreeSet (); Ts.add (5); Ts.add (2); Ts.add (10); Ts.add (-9); //output: null proof is natural sortSystem.out.println (Ts.comparator ()); //Output: -9System.out.println (Ts.first ()); //Output: TenSystem.out.println (Ts.last ()); //Output: 2System.out.println (Ts.lower (3)); //Output: TenSystem.out.println (Ts.higher (5)); //output [5, ten]System.out.println (Ts.subset (3, 12)); //output: [-9, 2, 5]System.out.println (Ts.headset (10)); //output: [5, ten]System.out.println (Ts.tailset (5)); }}

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

Natural Sort: TreeSet invokes the CompareTo (Object obj) method of the collection element to compare the size relationship between elements, and then makes the collection in ascending order, which is called natural ordering.

Custom sorting: custom Sorting is a sort of design that needs to be designed according to the user's requirements. If you need custom sorting, such as requiring data to be sorted in descending order, you can use the help of the comparator interface.

Ps:

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

The only criterion for determining the equality of elements in a 2.TreeSet collection is that two objects are compared by the comparator (object obj) method, and 0 are returned, otherwise they are considered unequal.

3.EnumSet class

The Enumset class is a collection class designed specifically for enumeration classes, and all elements in the Enumset must be enumerated values of the specified enumeration type that are specified explicitly or implicitly when the Enumse class is created. The collection elements of the Enumset are also ordered, and Enumset determines the order of the collection elements in the order in which the enumeration values are defined within the enum class.

Enumset provides the following common class methods to create a Enumset object:
enumset AllOf (Class elementtype): creates a Enumset collection that contains all the enumeration values in the specified enumeration class.

Enumset complement (Enumset s): creates a Enumset collection whose element type is the same as the element type in the specified Enumset, and the new Enumset collection contains the original Enumset collection, The remaining enumeration values for this enumeration class (the new Enumset collection plus the collection elements in the original Enumset collection are all enumerated values in the enumeration class).

Enumset copyOf (Collection C): use a normal collection to create a Enumset collection.

Enumset copyOf (enumset s): creates a Enumset collection of the same type as the collection element that specifies a Enumset collection.

enumset noneof (Class elementtype): Creating an element type is an empty Enumset collection of the specified enumeration type.

Enumset of (e First, E ... rest): creates a collection that contains one or more enumerations that are worth Enumset, and the incoming enumeration values must belong to the same enumeration class.

Enumset Range (e from, E to): creates a Enumset collection from the From enumeration value to all enumeration values in the to enumeration value range.

enumseason{Spring,summer,fall,winter} Public classEnumsettest { Public Static voidMain (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 collection

Set set of Java collections

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.