Summary of Java Collection knowledge (II.)

Source: Internet
Author: User

Set Set
Set and collection are basically the same, set does not allow duplicate elements, and the elements within the collection are unordered.
1) HashSet class
Features: There is no guarantee that the ordering of elements, not synchronous, multi-threaded operation requires code to ensure its synchronization, the collection element value can be null. HashSet adds the original when it calculates its storage location based on the hashcode value of the element, which is convenient and quick for the element. (The function of the hash algorithm is to ensure that the retrieved object is quickly found, and the storage location of the element is calculated based on the hashcode value of the element, thus quickly locating the element position.) )
HashSet determines whether elements are equal through the Equals () method, and the Hashcode () method return values must also be equal.
code example:

/*** Override the Equals method without overriding the Hashcode method *@authorAdministrator **/ Public classDemo1 {@Override Public Booleanequals (Object obj) {return true; }} /*** Override the Hashcode method without overriding the Equals method *@authorAdministrator **/ Public classDemo2 {@Override Public inthashcode () {return1; }} /*** Override Equals Method and Hashcode method *@authorAdministrator **/ Public classDemo3 {@Override Public Booleanequals (Object obj) {return true; } @Override Public inthashcode () {return2; }}  Public classHashsetdemo { Public Static voidMain (string[] args) {HashSet ss=NewHashSet (); //insert two objects equal to Equals methodSs.add (NewDemo1 ()); Ss.add (NewDemo1 ()); //insert two objects equal to HashcodeSs.add (NewDemo2 ()); Ss.add (NewDemo2 ()); //insert equals and Hashcode equal objectsSs.add (NewDemo3 ()); Ss.add (NewDemo3 ()); //Output ResultsSYSTEM.OUT.PRINTLN (ss); }}

The output is:

[Email protected], [email protected], [email protected], [email protected], [email protected]]

The above output indicates that hashset judgment element equality must be equal to the Equals method and the Hashcode method return value, such as the Demo3 class

HashSet Basic Usage code example:

 Public classHashsettest { Public Static voidMain (string[] args) {Set<String> HashSet =NewHashset<string>(); //adding elementsHashset.add ("Set Set"); Hashset.add ("List Collection"); Hashset.add ("Map Collection"); //Delete ElementHashset.remove ("Map Collection"); //traversing elements       for(String string:hashset) {System.out.println (string); } Iterator<String> iter =Hashset.iterator ();  while(Iter.hasnext ()) {String str=(String) iter.next ();      System.out.println (str); }   }}

2) TreeSet class

Features: The use of red-black tree structure to store elements, elements are ordered, support two sorting methods, natural sorting and custom ordering, TreeSet can only add one type of object storage elements when the object must override the comparable interface CompareTo (Object obj) method, Otherwise, a ClassCastException exception is thrown. The TreeSet collection determines whether two objects are equal, and whether the CompareTo (object obj) method compares returns 0, returns 0 equals, or is not equal.

 Public class  Public class  treesettest {   publicstaticvoid Main (string[] args) {      new  TreeSet ();      Treeset.add (new  Test ());      Treeset.add (new  Test ());      System.out.println (TreeSet);   }}

Output Result:

Exception in thread "main" Java.lang.ClassCastException:com.zzl.demo.Test cannot is cast to Java.lang.comparable
    at Java.util.TreeMap.compare (Unknown source) at   java.util.TreeMap.put (Unknown source)   at Java.util.TreeSet.add (Unknown Source) at   com.zzl.demo.TreeSetTest.main (Treesettest.java:10)

Summary: Because TreeSet additional red-black tree algorithms are required to maintain the order of the elements, so TreeSet performance is inferior to HashSet when you need to keep the sort Set when you use the TreeSet , otherwise it is recommended to use HashSet .

Summary of Java Collection knowledge (II.)

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.