Meet java-15.3 in the beginning hashset need to pay attention to the place

Source: Internet
Author: User

In this chapter we discuss the various implementations of the set that require attention.

Common implementation classes for the set interface are: Hashset,treeset,linkedhashset


1.HashSet

Everyone's impression of HashSet is that it can remove duplicate elements, each element is unique, but there is a premise that the Equals and Hashcode methods must be rewritten.

Most of the people's impressions are the following:

Package Com.ray.ch15;import Java.util.hashset;public class Test {public static void main (string[] args) {hashset< integer> set = new Hashset<integer> (); Set.add (1); Set.add (2); Set.add (3); for (int i = 0; i <; i++) {Set.add (i );} SYSTEM.OUT.PRINTLN (set);}}
Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In fact, the reason for this is that the Equals and Hashcode methods in the set inherit the object inside, and the two methods in object can easily compare the basic types of Java, even most of the Java type, Because most types have overridden the Equals and Hashcode methods.

So, let's customize our own type below to see:

Package Com.ray.ch15;import Java.lang.reflect.invocationtargetexception;import Java.util.hashset;import Java.util.set;public class Test<t> {public static <T> set<t> Fill (set<t> Set, class<t> Type) throws Instantiationexception, Illegalaccessexception,illegalargumentexception, SecurityException, InvocationTargetException, nosuchmethodexception {for (int i = 0; i <; i++) {Set.add (Type.getconstructor (Int.class) . newinstance (i));} return set;} public static <T> void Test (set<t> Set, class<t> type) throws IllegalArgumentException, Securityexception,instantiationexception, Illegalaccessexception,invocationtargetexception, nosuchmethodexception {Fill (set, type); Fill (set, type); Fill (set, type); SYSTEM.OUT.PRINTLN (set);} public static void Main (string[] args) throws Illegalargumentexception,securityexception, Instantiationexception, Illegalaccessexception,invocationtargetexception, nosuchmethodexception {test (New hashset<settype> (), settype.cl) Test (new Hashset
Output:

[6, 6, 3, 4, 9, 5, 2, 9, 1, 7, 5, 4, 1, 2, 9, 3, 7, 8, 8, 0, 2, 0, 4, 6, 7, 5, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Explain the above code:

(1) Fill method: Add data to the set passed in by generics and reflection

(2) test method: We fill in the data through the set to see if the set is going to be heavy

(3) SetType: Primitive type, just simple implementation of the Equals method and ToString method, ToString here by the output ID to represent the object

(4) Hashtype: Inherit the Settype, then realize the Hashcode method


Note the point:

(1) From the output we can see that the first Test method in main, its output is very many object ID, and there is a lot of repetition, this is because we did not rewrite the Hashcode method, in the Hashcode method of the object, Each object returns a different Hashcode, and the JVM determines that it is a distinct object, so how many objects we add to it will show how many objects

(2) Then the above explanation, the following Hashtype rewrite the Hashcode method, with the ID as standard, from the above code we can see that the ID is very likely to repeat, so the JVM will go heavy.

We can open the source code of HashSet and see the Add method:

Private Transient hashmap<e,object> map;public boolean add (E e) {return Map.put (E, PRESENT) ==null;    }
The object is put into the map, and we're opening the map's put method:

Public V put (K key, V value) {        if (key = = null)            return Putfornullkey (value);        int hash = hash (Key.hashcode ());        int i = indexfor (hash, table.length);        for (entry<k,v> e = table[i]; E! = null; e = e.next) {            Object K;            if (E.hash = = Hash && (k = e.key) = = Key | | key.equals (k))) {                V oldValue = e.value;                E.value = value;                E.recordaccess (this);                return oldValue;            }        }        modcount++;        AddEntry (hash, key, value, I);        return null;    }

It is in contrast to the hash value, so HashSet want to achieve the weight, must rewrite the Equals and Hashcode methods.

(3) because the above value is less, so the particularity of the order is not revealed, when we increase the creation of the object, the sort will be arranged in a certain order, rather than in the order we imagined. As for this sort of sorting, we'll talk about it later in the chapter. Here is the example code:

Package Com.ray.ch15;import Java.lang.reflect.invocationtargetexception;import Java.util.hashset;import Java.util.set;public class Test<t> {public static <T> set<t> Fill (set<t> Set, class<t> Type) throws Instantiationexception, Illegalaccessexception,illegalargumentexception, SecurityException, InvocationTargetException, nosuchmethodexception {for (int i = 0; i <; i++) {Set.add (Type.getconstructor (Int.class) . newinstance (i));} return set;} public static <T> void Test (set<t> Set, class<t> type) throws IllegalArgumentException, Securityexception,instantiationexception, Illegalaccessexception,invocationtargetexception, nosuchmethodexception {Fill (set, type); Fill (set, type); Fill (set, type); SYSTEM.OUT.PRINTLN (set);} public static void Main (string[] args) throws Illegalargumentexception,securityexception, Instantiationexception, Illegalaccessexception,invocationtargetexception, nosuchmethodexception {test (New hashset
Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18]


Summary: This chapter focuses on the areas that need to be noted for using HashSet.


This chapter is here, thank you.

-----------------------------------

Directory









Meet java-15.3 in the beginning hashset need to pay attention to the place

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.