In the Java collection, the rule that determines whether two objects are equal is:
1) to determine whether the hashcode of two objects is equal
If not equal, the two objects are not equal, complete
If equal, transfer to 2)
2), to determine whether two objects are equal with equals, the equality returns true
Class Weibo
{
private String name;
Publicweibo (String name)
{
THIS.name = name;
}
Determine whether two Weibo are equal according to name
public boolean equals (Object O)
{
if (this = O)
{
return true;
}
if (o.getclass () = = Name.class)
{
Weibo Weibo = (Weibo) o;
return weibo.name.equals (name);
}
return false;
}
Returns a value based on the hashcode () of the Name object
public int hashcode ()
{
return Name.hashcode ();
}
public class Hashsettest
{
public static void Main (string[] args)
{
hashset<weibo> set = new hashset<weibo> ();
Set.add (New Weibo ("abc");
Set.add (New Weibo ("abc");
SYSTEM.OUT.PRINTLN (set);
}
}
Execution Result: Cannot insert a second object. The reason is what, because to judge Hashcode, then equals.
Weibo.hashcode returns the name, which means that when the name is the same, two Weibo hashcode are the same, so that the equals judgment is the same. HashSet
is not allowed to insert duplicates. So.
This is the principle that hashset determines whether objects are the same.
Conclusion The key in Hashtable, HashMap, HashSet and Linkedhashmap needs to judge the hashcode and equals of the Key object. The two methods need to be overridden.
Hashcode use, we know that the list and set are different, the elements in the list are ordered, the elements can be repeated, the set element is unordered, but the elements cannot be duplicated. If the guarantee is both orderly and not repeatable. To ensure that the elements do not repeat, can two elements of repetition should be based on what to judge. This is the Object.Equals method. However, if each additional element is checked once, the number of elements that are added to the collection is much more frequent when the elements are many.
Java uses the principle of a hash table, hash algorithm is also called hashing algorithm, is the data to a specific algorithm directly assigned to an address. Beginners can understand that the Hashcode method actually returns the physical address of the object store (which may not actually be).
With Hashcode, when the collection wants to add a new element, it first calls the Hashcode method of the element, and then it can navigate to the physical location where it should be placed.
If there is no element in this position, it can be stored directly in this position without any comparison; if there is already an element in this position,
The Equals method that calls it is compared to the new element, and the same is not saved, and the other addresses are hashed out.
So there is a problem of conflict resolution here. The number of actual calls to the Equals method is greatly reduced, almost one or two times.