Comparison and hashcode analysis of Arraylist_hashset
The role of the Hashcode () method
public static void Main (string[] args) {Collection Collection = new hashset<> (); Reflectpoint pt1 = new Reflectpoint (3, 3); Reflectpoint pt2 = new Reflectpoint (5, 5); Reflectpoint PT3 = new Reflectpoint (3, 3); Collection.add (PT1); Collection.add (PT2); Collection.add (PT3); Collection.add (PT1); PT1.Y = 7; Modified after the Hashcode value is different, resulting in the object can not be found, also can not delete collection.remove (PT1); /**
1. If the entity class only Overrides equals (), without overriding hashcode (), the total number of collection is 3
Because, when storing an object into the HashSet, if the Hashcode method is not overridden, the hashcode value calculated by the two objects is not the same (the Hashcode value is computed based on the object's address in memory)
I'm looking in my area, not in the area where the same object is stored, so this object will still be stored inside.
In order for equal objects to be found in the same area, there is a saying that if the equals of two objects is equal, then their hashcode should also be equal
If the object does not have to be stored in the hash set, there is no need to rewrite hashcode ();
* If the object to be put into HashSet does not override the Hashcode method and the Equals method, * Two objects are referenced differently, or are stored in HashSet, the default equals method uses = = To compare the memory address values of two objects * if overriding h Ashcode and Equals method, will be considered to be the same object, the back of the deposit will not be deposited * * When an object is stored in the HashSet collection, it is not possible to modify the object to participate in the calculation of the hash value of the field, otherwise, the object * Modified ha The hash value in the HashSet collection is different in this case, even if the * contains method uses the object's current reference as a parameter to retrieve the object in the HashSet collection, the result of the object will not be returned, which can also cause the Removes the current object separately from the Hset collection, causing a memory leak. */System.out.println (collection.size ()); /** * Typically, the two instance objects of a class are equal when compared with the Equals () method, their hashes must also be equal, but the opposite is not true, and the Equals method compares unequal objects can have the same hash code, or hash the same two objects , * The result of the Equals method comparison can be different, for example, equals of the string "BB" and "Aa" compare results, but the hashcode () result is equal. */System.out.println ("BB". Hashcode ()); System.out.println ("Aa". Hashcode ()); }
The memory leak problem can also be used for example,
The so-called memory leak is that this object is no longer used can always occupy memory space, cannot be released.
Arraylist_hashset comparison and hashcode analysis