【问题标题】:Convert a Set<Integer> to a primitive array [duplicate]将 Set<Integer> 转换为原始数组 [重复]
【发布时间】:2016-09-18 18:07:07
【问题描述】:

我正在使用以下代码将 Set 转换为 int[]

Set<Integer> common = new HashSet<Integer>();
int[] myArray = (int[]) common.toArray();

我收到以下错误:

 error: incompatible types: Object[] cannot be converted to int[]

在不使用 for 循环逐个添加元素的情况下进行转换的最干净的方法是什么?谢谢!

【问题讨论】:

  • 在 StackOverflow 上终于找到了一个格式正确且语法正确的问题

标签: java data-structures collections set


【解决方案1】:
Set<Integer> common = new HashSet<>();
int[] values = Ints.toArray(common);

【讨论】:

  • Integer[] != int[]
  • 现在改为使用 Guava 的辅助库。
【解决方案2】:

您不能显式地将某些内容强制转换为数组。

这样做:

Integer[] arr = new Integer[common.size()];
Iterator<Integer> iterator = common.iterator(); 
int i = 0;
while (iterator.hasNext()){
    arr[i++] = iterator.next();
}

【讨论】:

【解决方案3】:

你通常这样做:

Set<Integer> common = new HashSet<Integer>();
int[] myArray = common.stream().mapToInt(Integer::intValue).toArray();

【讨论】:

猜你喜欢
  • 2011-01-27
  • 2016-04-15
  • 2019-11-30
  • 2011-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多