尝试将值添加到HashSet不会更改其中的值数量 [英] Attemping to add a value to a HashSet doesn't change the amount of values in it

查看:46
本文介绍了尝试将值添加到HashSet不会更改其中的值数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HashSet,当我使用集合的Add方法时,没有添加任何内容.输出仍然是2, 3, 5, 7, 11, 13,而来自.Count的输出是6.

I have a HashSet and when I use the Add method of the collection, nothing is added. The output is still 2, 3, 5, 7, 11, 13 and the output from .Count is 6.

这是一个错误还是我在这里做错了什么?

Is this a bug or am I doing something wrong here?

namespace AllerDiz
{
    class MainClass
        {
            public static void Main (string[] args)
            {
                HashSet<int> smallPrimeNumbers = new HashSet<int> { 2, 3, 5, 7, 11, 13 };
                smallPrimeNumbers.Add (3);
                smallPrimeNumbers.Add (5);
                smallPrimeNumbers.Add (7);
                Console.WriteLine ("{0}", smallPrimeNumbers.Count);
                foreach(int val in smallPrimeNumbers)
                {
                    Console.WriteLine ("HashSet Value= {0}", val);
                }
            }
      }
}

推荐答案

不,这不是bug.这正是 HashSet 应该如何工作的方式.

No, this is not a bug. This is precisely how a HashSet is supposed to work.

HashSet<T>类提供高性能的集合操作.集合是不包含重复元素且其元素没有特定顺序的集合.

The HashSet<T> class provides high-performance set operations. A set is a collection that contains no duplicate elements, and whose elements are in no particular order.

因此,如果您要添加的项目已存在于集合中,则该集合不会被修改.

So, if the item you are trying to add already exists in the set, the set is not modified.

如果要使用允许重复的集合,请查看 List<T> .

If you want a collection which does allow duplicates, look at List<T>.

这篇关于尝试将值添加到HashSet不会更改其中的值数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆