我有一个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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
Son*_*nül 10
HashSet类提供高性能的集合操作.集合是一个不包含重复元素的集合,其元素没有特定的顺序.
返回值如果将元素添加到HashSet对象,则返回true;否则返回false. 如果元素已存在,则返回false.
HashSet是一种优化的集合.它的构造函数消除了非唯一元素.
例如;
string[] array = new string[] {"one", "one", "two", "two", "three", "three"};
HashSet<string> hash = new HashSet<string>(array);
string[] array2 = hash.ToArray();
Run Code Online (Sandbox Code Playgroud)
array2 将会 {"one", "two", "three"}
如果要添加重复值,则List<int>集合允许您添加重复值.