1

I want hashmap to array

I create the hashmap

Map<Integer,File> selectedFiles = new Hashmap<>();

and put it some Map data

And I convert this hashmap's values to array so

File[] files = (File[]) selectedFiles.values().toArray();

But errors occur;

java.lang.Object[] cannot be cast to java.io.File[]

I know that when I want the hashmap's values to array, use .values.toArray() but maybe it is not corret;

This way is wrong?

Polaris Nation
  • 1,085
  • 2
  • 18
  • 49
  • Possible duplicate of [The easiest way to transform collection to array?](http://stackoverflow.com/questions/3293946/the-easiest-way-to-transform-collection-to-array) – 4castle Feb 03 '17 at 05:33
  • Unless you have other reasons, Android advice is to use [SparseArray](https://developer.android.com/reference/android/util/SparseArray.html) instead of Map: less boxing, lower memory usage. – ephemient Feb 03 '17 at 05:51
  • Possible duplicate of [Java: how to convert HashMap to array](http://stackoverflow.com/questions/1090556/java-how-to-convert-hashmapstring-object-to-array) – faranjit Feb 03 '17 at 06:32

2 Answers2

2
Map<Integer, File> selectedFiles = new HashMap<>();
    selectedFiles.put(1, null);

    File[] files = selectedFiles.values().toArray(
            new File[selectedFiles.size()]);

    System.out.println(files);// We will get the object [Ljava.io.File;@15db9742

arrays. toArray without parameters creates an object array because the type information of the list is lost at runtime.

Rahul Vashishta
  • 184
  • 2
  • 6
0

Please use below Code to convert HashMap to Array ,You can change String to File in your case.

   //Creating a HashMap object

    HashMap<String, String> map = new HashMap<String, String>();

    //Getting Collection of values from HashMap

    Collection<String> values = map.values();

    //Creating an ArrayList of values

    ArrayList<String> listOfValues = new ArrayList<String>(values);

   // Convert ArrayList to Array

   String stringArray[]=listOfValues.toArray(new String[listOfValues.size()])
Chetan Joshi
  • 5,582
  • 4
  • 30
  • 43