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

ERJ*_*JAN 16 java collections hashset

看一下java api for java collections framework,我在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
    }
}
Run Code Online (Sandbox Code Playgroud)

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

Era*_*ran 33

当然是HashSet实施toArray.它必须实现它,因为它实现了Set指定此方法的接口.实际的实现是AbstractCollection超类中AbstractSet的超类HashSet.

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

使用 :

Set<Integer> x = new HashSet<>();
x.add(4);
Run Code Online (Sandbox Code Playgroud)

然后转换为数组:

Integer[] arr = x.toArray(new Integer[x.size()]);
Run Code Online (Sandbox Code Playgroud)

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


Sam*_*s33 5

确保您声明了泛型HashSet

Set<Integer> x = new HashSet<>();
Run Code Online (Sandbox Code Playgroud)

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

int[] y = new int[x.size()];
int c = 0;
for(int x : x) y[c++] = x;
Run Code Online (Sandbox Code Playgroud)