How can I convert a Java HashSet to a primitive int array?

后端 未结 8 1973
既然无缘
既然无缘 2020-12-01 09:03

I\'ve got a HashSet with a bunch of Integers in it. I want to turn it into an array, but calling

hashset.toArray();
         


        
8条回答
  •  被撕碎了的回忆
    2020-12-01 09:58

    You could also use the toArray(T[] contents) variant of the toArray() method. Create an empty array of ints of the same size as the HashSet, and then pass it to the toArray() method:

    Integer[] myarray = new Integer[hashset.size()];
    doSomething(hashset.toArray(myarray));
    

    You'd have to change the doSomething() function to accept an Integer[] array instead of int[]. If that is not feasible, you'd have convert the array of values returned by toArray to int[].

提交回复
热议问题