-5
    HashSet<List<int>> hs = new HashSet<List<int>>();
    
    List<int> list1 = new List<int>();
    list1.Add(1);
    list1.Add(2);
    
    List<int> list2 = new List<int>();
    list2.Add(1);
    list2.Add(2);
    
    hs.Add(list1);
    hs.Add(list2);
    
    Console.WriteLine(hs.Count);

The above code prints '2'. Should it not be '1'? The same in java will print '1'.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • 7
    Because `List` is a reference type, therefore, `list1 != list2`. You need to pass an `IEqualityComparer` to the [constructor](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.hashset-1.-ctor?view=net-6.0#system-collections-generic-hashset-1-ctor(system-collections-generic-iequalitycomparer((-0)))) of the HashSet if you want to have custom comparison logic. – 41686d6564 stands w. Palestine Jun 06 '22 at 16:32
  • Can you tell me why the same in java prints one? ArrayList is also a reference type – Siddharth b Jun 06 '22 at 16:35
  • 3
    I don't know if that's true in Java but assuming it is, the answer would be: because they're two different languages with two different sets of rules. – 41686d6564 stands w. Palestine Jun 06 '22 at 16:37
  • From the Javadoc for HashSet: "More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2))". Essentially it calls .equals which probably has some kind of logic in it for comparing the elements of the array. C# doesn't really have a standard like .equals so is probably just checking whether they point to the same memory address. – Will Moffat Jun 06 '22 at 16:42
  • 1
    adding to @WillMoffat comment, if you want your comparison to be done on the list's values instead of their reference, you could write your own IEqualityComparer that does so (https://learn.microsoft.com/pt-br/dotnet/api/system.collections.generic.iequalitycomparer-1) – Carlos Moreira Jun 06 '22 at 17:06

1 Answers1

0

ArrayList (or rather AbstractList) in Java overrides the equals and hashCode methods. HashSet in Java uses hashCode and equals to determine the equality of two instances. Two lists with the same elements in the same order are considered equal.

HashSets in C# will use reference equality by default, therefore two list distinct instances are never equal. You need to provide the proper IEqualityComparer when constructing your HashSet.

knittl
  • 246,190
  • 53
  • 318
  • 364