Difference between HashSet and TreeSet, hashsettreeset

Source: Internet
Author: User
Tags comparable

Difference between HashSet and TreeSet, hashsettreeset

I. Problems

1. How does HashSet and TreeSet use the hashCode () and equal () methods?

2. When and why must the Comparable interface be implemented for objects in TreeMap and TreeSet?

Ii. Answer:

1. HashSet is implemented through HashMap, and TreeSet is implemented through TreeMap, except that Set only uses the Map key.

2. The key and Set of Map have a common feature that is the uniqueness of the Set. TreeMap has an extra orderliness.

3. hashCode and equal () are used by HashMap. Because no sorting is required, you only need to pay attention to location and uniqueness.

A. hashCode is used to calculate the hash value, and the hash value is used to determine the index of the hash table.

B. An index in the hash table stores a linked list. Therefore, you must use the equal method to cycle the objects in the comparison chain to locate the Entry corresponding to the key value.

C. put: If the hash table is not located, add an Entry in front of the linked list. If it is located, replace the value in the Entry and return the old value.

D. when overwriting key hashCode () and equal (), be sure not to associate them with variable attributes. Otherwise, hashCode will change and equal will also be false, in this way, the Map won't be able to find it, and such an object cannot be released because it cannot be found, which becomes an invalid reference (equivalent to memory leakage ).

4. Because TreeMap needs to be sorted, a Comparator is required to compare the size of the key value. Of course, it is also located using Comparator.

A. Comparator can be specified when you create a TreeMap. Comparator. compare is used for sorting.

B. If no Comparator is specified during creation, the key. compareTo () method is used. This requires that the key must implement the Comparable interface.

C. TreeMap is implemented using the Tree data structure, so you can use the compare interface to complete the positioning.

Import java. util. hashSet; import java. util. iterator; public class WpsklHashSet {// use of Set in java (repeated objects are not allowed): public static void main (String [] args) {HashSet hashSet = new HashSet (); String a = new String ("A"); String B = new String ("B "); string c = new String ("B"); hashSet. add (a); hashSet. add (B); System. out. println (hashSet. size (); String cz = hashSet. add (c )? "This object does not exist": "already exists"; System. out. println ("test whether an object can be added" + cz); System. out. println (hashSet. isEmpty (); // test whether the System contains an object. out. println (hashSet. contains ("A"); Iterator ir = hashSet. iterator (); while (ir. hasNext () {System. out. println (ir. next ();} // test whether an object can be deleted. out. println (hashSet. remove ("a"); System. out. println (hashSet. remove ("A"); // after testing, if you want to use the ir variable again, you must update the following ir = hashSet. iterator (); while (ir. hasNext () {System. out. println (ir. next () ;}}/ *** through this program, you can also test the sequeness of adding elements to the tree set and the ordering of output */import java. util. treeSet; import java. util. iterator; public class TreeSetTest {public static void main (String [] args) {TreeSet tree = new TreeSet (); tree. add ("China"); tree. add ("America"); tree. add ("Japan"); tree. add ("Chinese"); Iterator iter = tree. iterator (); while (iter. hasNext () {System. out. println (iter. next ());}}}

Another difference (thanks to the andygulin friend "baidu Knows ):

1. TreeSet is implemented by the binary difference tree. Data in the Treeset is automatically sorted, and null values are not allowed.

2. HashSet is implemented in a hash table. The data in HashSet is unordered and can be put into null, but only one null can be put. The values in both cannot be repeated, just as the unique constraint in the database.

3. HashSet requires that the Put object must implement the HashCode () method. The Put object is identified by the hashcode code, and the String object with the same content is the same as the hashcode, therefore, the entered content cannot be repeated. However, objects of the same class can be placed in different instances.

Summary

The above is all about the differences between HashSet and TreeSet, and I hope to help you. If you are interested, you can continue to refer to other related topics on this site. If you have any shortcomings, please leave a message. Thank you for your support!

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.