无法将整数发送到HashSet构造函数

问题描述 投票:-4回答:2

我试图用int初始化HashSet,但它没有用。

public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {
    Set<Integer> a = new HashSet<Integer>(123456);
    a.add(55);
    System.out.println(a);
  }
}

产出:[55]

为什么会发生这种情况,如何将单个int发送给HashSet构造函数?

谢谢!

java constructor hashset
2个回答
3
投票

你传递给Integer构造函数的HashSet代表了Set的初始容量。它没有将该值添加到Set

如果你想用单个元素构造一个Set,你可以使用(在Java 9中):

Set<Integer> a = Set.of(123456);

请注意,这个Set将是不可变的。

如果你想要一个可变的Set,你可以将不可变的Set传递给它的构造函数:

Set<Integer> a = new HashSet<>(Set.of(123456));

或者,在Java 7中:

Set<Integer> myset = new HashSet<>(Arrays.asList(123456));

1
投票

HashSet(int)构造函数允许您指定其初始容量。

如果要初始化其元素,则需要使用HashSet(Colletion)构造函数。例如。:

Set<Integer> a = new HashSet<>(Collections.singleton(123456));
© www.soinside.com 2019 - 2024. All rights reserved.