Java 如果未指定 toArray 方法,如何使用 toArray() 将 hash Set 转换为数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33593371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:48:10  来源:igfitidea点击:

How to convert hash Set into array using toArray() if the method toArray is not specified?

javacollectionshashset

提问by ERJAN

Looking at the java api for java collections framework, I could not find toArray() method in HashSet, there is toArray() method in abstract class Set.

查看java集合框架的java api,我在HashSet中找不到toArray()方法,抽象类Set中有toArray()方法。

class Ideone {
    public static void main (String[] args) throws java.lang.Exception {
        Set x = new HashSet();
        x.add(4);
        //ArrayList<Integer> y = x.toArray(); this does not work !
        int[] y = x.toArray();//this does not work!

        System.out.println(x.toArray());//this gives some weird stuff printed : Ljava.lang.Object;@106d69c
    }
}

How do I convert hashset into array if there is no toArray() specified?

如果没有指定 toArray(),如何将 hashset 转换为数组?

采纳答案by Eran

Of course HashSetimplements toArray. It must implement it, since it implements the Setinterface, which specifies this method. The actual implementation is in AbstractCollectionwhich is the super class of AbstractSetwhich is the super class of HashSet.

当然HashSet实现toArray. 它必须实现它,因为它实现了Set指定此方法的接口。实际的实现是在AbstractCollectionwhich is the super class AbstractSetwhich is the super class of HashSet.

First of all, you shouldn't use raw types.

首先,您不应该使用原始类型。

Use :

用 :

Set<Integer> x = new HashSet<>();
x.add(4);

Then convert to array :

然后转换为数组:

Integer[] arr = x.toArray(new Integer[x.size()]);

Using x.toArray()would give you an Object[].

使用x.toArray()会给你一个Object[].

回答by SamTebbs33

Make sure that you declare the generic for the HashSet

确保您声明了泛型 HashSet

Set<Integer> x = new HashSet<>();

And convert it to an array like so:

并将其转换为数组,如下所示:

int[] y = new int[x.size()];
int c = 0;
for(int x : x) y[c++] = x;

回答by M Sach

First Line

第一行

ArrayList y = x.toArray(); this does not work !

ArrayList y = x.toArray(); 这行不通!

First of all you used Set x = new HashSet();i.e raw type . Compiler does not know that s it going to contain integer object but with above line on left hand side you are saying its going to be arraylist of integer where actually its an array

首先,您使用了 Set x = new HashSet();ie 原始类型。编译器不知道它将包含整数对象,但是在左侧的上面一行中,您说它将是整数数组列表,而实际上它是一个数组

Second line

第二行

int[] y = x.toArray();//this does not work!

int[] y = x.toArray();//这不起作用!

with above line on left hand side you are saying its going to be array of integer where actually its an array of objects

上面一行在左边,你说它是整数数组,实际上它是一个对象数组

This will work

这将工作

Object[] y = x.toArray();

But this is not the right way . You should not use raw types

但这不是正确的方法。你不应该使用原始类型

 Set<Integer> x = new HashSet<>();
 Integer[] intArray= x.toArray(new Integer[x.size()]);

System.out.println(x.toArray());//this gives some weird stuff printed : Ljava.lang.Object;@106d69c

System.out.println(x.toArray());//这会打印出一些奇怪的东西:Ljava.lang.Object;@106d69c

Its printing toStringrepresentation of array object . Thats why you are seeing it as Ljava.lang.Object;@106d69c

它的打印 toString表示数组对象。这就是为什么您将其视为Ljava.lang.Object;@106d69c

If you want to print each element , iterate over it and then print it.

如果要打印每个元素,请遍历它然后打印它。

回答by paiego

It looks like you originally wanted to create an ArrayList rather than a simple Array. So, try this!

看起来您最初想要创建一个 ArrayList 而不是一个简单的 Array。所以,试试这个!

class Ideone 
{
        public static void main (String[] args) throws java.lang.Exception   
        {
            Set x = new HashSet();
            x.add(4);
            ArrayList<Integer> y = new ArrayList<>(x);
            System.out.println(y);
        }
}

回答by sjzack

Comparison in JDK 7 sorting a small map, using TreeSet, ArrayListand Array:

JDK 7 中排序小地图的比较,使用TreeSet,ArrayListArray

long start  = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   TreeSet a   = new TreeSet(payloads.keySet());                           
} 
System.out.println("TreeSet: "    + (System.currentTimeMillis()-start) + " ms.");
start       = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   ArrayList a = new ArrayList(payloads.keySet()); 
   Collections.sort(a);    
} 
System.out.println("ArrayList: "  + (System.currentTimeMillis()-start) + " ms.");
start       = System.currentTimeMillis(); 
for(int i=0; i<10000000; i++){ 
   String[] a = payloads.keySet().toArray(new String[payloads.size()]); 
   Arrays.sort(a);    
} 
System.out.println("Array: "  + (System.currentTimeMillis()-start) + " ms.");

Yields:

产量:

TreeSet: 1527 ms.
ArrayList: 943 ms.
Array: 485 ms.

树集:1527 毫秒。
数组列表:943 毫秒。
阵列:485 毫秒。

回答by sjzack

We can iterate through the loop and store the values into the array.

我们可以遍历循环并将值存储到数组中。

int[] answer = new int[set1.size()];
int i = 0;
for (int num : set1) {
      answer[i++] = num;
}