I wrote a program as below:
public static void main(String[] args) {
Set<List<Integer>> s = new HashSet<>();
List<Integer> l1 = new ArrayList<>(List.of(1,2,3));
List<Integer> l2 = new ArrayList<>(List.of(1,2,3));
List<Integer> l3 = new ArrayList<>(List.of(3,2,1));
s.add(l1);
if(s.contains(l2)) {
System.out.println("l2 is already present");
}
if(s.contains(l3)) {
System.out.println("l3 is present");
} else {
System.out.println("l3 is absent");
}
}
Here is the output:
l2 is already present
l3 is absent
I have a general idea of equals and hashcode in Java and rough idea of Object type, etc.
Can someone explain conceptually how this thing able to compare internally a list of integers and find if it is already present? Notice that it works only if the order of elements in the list is same.
HashSetrelies on theequalsandhashCodemethods of the element type (which in your case isList). The documentation for those methods on theListtype is as follows:I.e. in summary, the
hashCodeandequalsimplementations forLists simply operate on each element of the list.