I'm experimenting with Java HashSet class and its toArray() method. Below is the code I have came up with. The compiler did not display any error but when I run the code, the IDE outputs the error message:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at JTOCollection.TheCollectionInterface.main(TheCollectionInterface.java:26)
Java Result: 1
Due to my inexperience, I can't fully understand the complete reason behind the error message, could someone please explain it to me?
Set<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
set1.add(2);
Integer[] intArray = (Integer[]) set1.toArray();
for(Integer i : intArray){
System.out.println(i);
}
because you are using public Object[] toArray()
instead of public <T> T[] toArray(T[] a)
.
use this:
Integer[] intArray = set1.toArray(new Integer[set1.size()]);
docs for : public <T> T[] toArray(T[] a)
Returns an array containing all of the elements in this collection; the runtime type of the returned array is that of the specified array. If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this collection.