【问题标题】:Attemping to add a value to a HashSet doesn't change the amount of values in it尝试向 HashSet 添加值不会更改其中的值数量
【发布时间】:2013-12-28 20:51:14
【问题描述】:

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

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

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);
                }
            }
      }
}

【问题讨论】:

  • 为什么这个问题被否决了?
  • 我看到在发布问题时进行了研究。最好先学习基础知识。

标签: c# hashset


【解决方案1】:

不,这不是错误。这正是 HashSet 应该如何工作的。

HashSet&lt;T&gt; 类提供高性能的集合操作。集合是不包含重复元素且其元素没有特定顺序的集合。

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

如果您想要一个允许重复的集合,请查看List&lt;T&gt;

【讨论】:

    【解决方案2】:

    来自HashSet&lt;T&gt; Class

    HashSet 类提供高性能的集合操作。一套 是一个不包含重复元素的集合,并且其 元素没有特定的顺序。

    来自HashSet&lt;T&gt;.Add Method

    如果将元素添加到 HashSet 对象,则返回 true; 如果元素已经存在则返回 false。

    HashSet 是一种优化集合。它的构造函数消除了非唯一元素。

    例如;

    string[] array = new string[] {"one", "one", "two", "two", "three", "three"};
    HashSet<string> hash = new HashSet<string>(array);
    string[] array2 = hash.ToArray();
    

    array2 将是 {"one", "two", "three"}

    如果要添加重复值,List&lt;int&gt; 集合允许您添加重复值。

    【讨论】:

      【解决方案3】:

      HashSet 的主要功能之一是确保没有重复项

      【讨论】:

        猜你喜欢
        • 2016-01-21
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2021-04-10
        • 1970-01-01
        相关资源
        最近更新 更多