var arr1 = new ArrayList<Integer>();
var arr2 = new ArrayList<Integer>();
System.out.println(arr1.hashCode());
System.out.println(arr2.hashCode());
System.out.println(arr1.equals(arr2));
Output:
1
1
true
After searching, I found this answer which explains why this is happening.
From the answer:
Here's the Java 8 implementation (it's actually implemented in
AbstractList
) :public int hashCode() { int hashCode = 1; for (E e : this) hashCode = 31*hashCode + (e==null ? 0 : e.hashCode()); return hashCode; }
And since the two arrays are empty, it's obvious that the hashCode
function would return 1
for both of the arrays.
My question is, given two ArrayLists
, how to determine whether they are the same or not? How can I be sure that modifing one ArrayList
won't affect the other? since I have no unique hash for each ArrayList
, I can't compare their hashes to know whether they're equal or not. How to get a unique hash for each object?
Also why the equals
function returns true
? Does it compare objects by hashes? Are they actually the same object? If yes then why and how to make different objects then?
And what are the classes other than ArrayList
that acts in this way?