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

ERJAN picture ERJAN · Nov 8, 2015 · Viewed 51k times · Source

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.

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?

Answer

Eran picture Eran · Nov 8, 2015

Of course HashSet implements toArray. It must implement it, since it implements the Set interface, which specifies this method. The actual implementation is in AbstractCollection which is the super class of AbstractSet which 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[].