How to convert hash Set into array using toArray() if the method toArray is not specified?
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[]
.
Make sure that you declare the generic for the 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;
First Line
ArrayList y = x.toArray(); this does not work !
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
Second line
int[] y = x.toArray();//this does not work!
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
Its printing toString representation of array object . Thats why you are seeing it as Ljava.lang.Object;@106d69c
If you want to print each element , iterate over it and then print it.