Java Collection Learning Collection (2)

Source: Internet
Author: User

The previous blog spoke about the basic operation of the collection interface, this blog mainly introduces the sub-interface set of the collection interface.
Set is an unordered set, its basic operation and collection interface is similar, the main difference is that the set cannot repeat the elements and the collection collection is possible. For set sets We are primarily concerned about its Hashset,treeset two implementation classes.

I. HashSet
HashSet is a typical implementation of the set interface, which is used most of the time when set sets are used; HashSet determines where the element is stored by the hash algorithm. It is important to note that an element with a value of NULL can be stored in hashset.
So how does the hashset work? Each time we pass in an element, HashSet calls the object's Hashcode () method to calculate the hashcode value of the object, and then determines where the element is stored in hashset based on that value. If two objects are equal by Equals (), but the computed hashcode values are not the same, then HashSet store them in a different location, and if the hashcode values of the two objects are equal, and the Equals () method is used to compare the unequal, Then HashSet will store them in the same position as a linked list.
Well, we can tell HashSet. The criterion for determining the equality of two objects is that two objects have the same hashcode value, and two objects return true through the Equals () method. So these two methods are very important to hashset, and we need to make sure that when the hashcode value of the two objects is the same, it will also return true through the Equals () method. In the following program, the A,b,c class overrides its own hashcode () and Equals () methods, respectively.

 Public classA  ///override the Equals () method of Class A so that it always returns True     PublicBooleanequals(Object obj) {return true; }} Public classB  ///rewrite the Hashcode () method of Class B so that it always returns 2     Public int hashcode(){return 2; }} Public classE =  ///rewrite the Equals () method of Class C so that it always returns True     PublicBooleanequals(Object obj) {return true; }  ///rewrite the C-Class Hashcode () method so that it always returns 3     Public int hashcode(){return 3; }} Public classhashcodetest { Public Static void Main(string[] args) {HashSet St =NewHashSet ();///Add two A,b,c class objects in turnSt.add (NewA ()); St.add (NewA ()); St.add (NewB ()); St.add (NewB ()); St.add (NewC ()); St.add (NewC ());//You can see that only one Class C is output, and A/B class outputs twoSystem. out. println (ST); }}

HashSet has a subclass called Linkedhashset, Linkedhashset's basic principle and hashset is the same, but Linkedhashset internal through a linked list to maintain the relative order of the inserted elements, This makes it seem that elements are saved in the order in which they are inserted, and when we traverse linkedhashset, we can output the elements in their input order.

Package Lkl;import Java.util.LinkedHashSet; Public classlinkedhashsettest { Public Static void Main(string[] args) {Linkedhashset LT =NewLinkedhashset (); Lt.add ("Java"); Lt.add ("C"); Lt.add ("C + +"); Lt.add ("Shell");///   from the two outputs below, the elements are always output in the input orderSystem. out. println (LT); Lt.remove ("Java"); Lt.add ("Java");///   The Java is put to the last after newly addedSystem. out. println (LT); }}

Two. TreeSet
TreeSet is another important subclass of set. Unlike HashSet, which determines where elements are stored in a hash, TreeSet internally maintains the relative order of elements through a red-black tree, and because of the order of elements in TreeSet, relative hashset, there are several additional methods available, as shown in the following code:

Package Lkl;import Java.util.TreeSet; Public classtreesettest { Public Static void Main(string[] args) {TreeSet ts =NewTreeSet (); Ts.add (1); Ts.add (-2); Ts.add (7); Ts.add (4);///   from the output below you can see that the TreeSet is orderlySystem. out. println (TS); ///Comparator Comparator ()    ///   If TreeSet has a custom sort, the comparator of custom sorting is returned    ///   returns null if a natural sort is usedSystem. out. println (Ts.comparator ()); //Object First (): Returns the element in the collection     //Object Last (): Returns the final element in the collectionSystem. out. println ("The first element in the collection is:"+ts.first ()); System. out. println ("The last element in the collection is:"+ts.last ()); //Object lower (object E): Returns the first element in the collection that is less than E, and e is not necessarily in the collection     //Object Higher (object E): Returns the first element in the collection that is greater than e    ///   If no element is satisfied, returns nullSystem. out. println ("The first element in the collection that is less than 5 is:"+ts.lower (5)); System. out. println ("The first element in the collection that is greater than 5 is:"+ts.higher (5)); ///SortedSet subset (Object e1,object E2): Returns a subset of set from E1-e2System. out. println (Ts.subset (1,5)); ///Sortset HeadSet (Object E): Returns a subset of elements that are less than e in the collectionSystem. out. println (Ts.headset (6)); ///Sortset Tailset (Object E): Returns a subset of elements that are greater than or equal to the E element in the collectionSystem. out. println (Ts.tailset (1));}}

Because TreeSet is ordered, it is always necessary to compare the size when inserting an element, which is always called by the object Obj1.compareto (Obj2) method when the size comparison is performed (returning a positive integer representing obj1 greater than OBJ2, Returns a negative integer that indicates that obj1 is less than Obj2 and returns 0 for equality), and only two objects return 0 o'clock through the CompareTo () comparison, and the two objects are considered equal. This leads to a problem where different objects cannot be inserted into TreeSet at the same time, because different objects cannot be compared by the Comparato () method, and an exception is thrown when we insert different objects into the TreeSet.
If we want to define our own rules for sorting, we can use the comparator interface. The interface contains a method of int compare (T t1,t T2), which returns a positive integer at T1>t2, in T1

Package Lkl;import Java.util.treeset;import Java.util.Comparator; Public classtreesetcomparatortest {///  TreeSet originally from small to large output, now custom-ordered///   can be achieved from large to small output     Public Static void Main(string[] args) {TreeSet ts =NewTreeSet (NewComparator () { Public int Compare(Object o1,object O2) {intM1= (int) O1;intM2= (int) O2;if(M1==M2)return 0;if(M1>M2)return-1;return 1;        }        }); Ts.add (1); Ts.add (2); Ts.add (-1); System. out. println (TS); }}

Finally, if we add a Mutable object to the set and then change the file in that object, it may cause the object to "not be visible" in the set, and if we include a mutable object in the set, then we should not change the value of the file in the back.

Java Collection Learning Collection (2)

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.