2
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?

StackExchange123
  • 1,871
  • 9
  • 24
  • 4
    Just compare the references: `arr1 == arr2` --- As for `equals()`, it returns true because the [javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#equals-java.lang.Object-) says it has to. Same as the javadoc of [`hashCode()`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#hashCode--) says the two lists must return the same value. Which you would know if you **read the documentation**. – Andreas May 25 '20 at 02:54
  • 1
    Hashcodes aren't unique and aren't used to determine equality. – user207421 May 25 '20 at 03:06
  • @Andreas Thanks that works. But how to get a uniuqe number or a string for an object then? – StackExchange123 May 25 '20 at 03:13
  • @user207421 Is there some unique value that I can use? since I can't get the address in memory, is there anything other that the address that I can get? – StackExchange123 May 25 '20 at 03:14
  • 2
    `==` compares the reference values. Isn't that what you want? – user207421 May 25 '20 at 03:40
  • @user207421 Well, yes that's what I was asking for. But I'm just curious, is there any unique value for each object? that I can get? Maybe the current address in memory or something. – StackExchange123 May 25 '20 at 04:13
  • 4
    There is `System.identityHashcode()`. – user207421 May 25 '20 at 04:29

0 Answers0