-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'.

5
  • 7
    Because List<int> is a reference type, therefore, list1 != list2. You need to pass an IEqualityComparer to the constructor of the HashSet if you want to have custom comparison logic. Commented Jun 6, 2022 at 16:32
  • Can you tell me why the same in java prints one? ArrayList<Integer> is also a reference type Commented Jun 6, 2022 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. Commented Jun 6, 2022 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. Commented Jun 6, 2022 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 (learn.microsoft.com/pt-br/dotnet/api/…) Commented Jun 6, 2022 at 17:06

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.