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?

asked Feb 3, 2017 at 5:30
3

2 Answers 2

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.

answered Feb 3, 2017 at 5:41

1 Comment

Thanks you save my time
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()])
answered Feb 3, 2017 at 5:36

2 Comments

You can skip the intermediate ArrayList. Also, why not just use File?
@4castle Yes, you are right and I just put sample code to do this that's why using String .

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.