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 NationPolaris Nation
asked Feb 3, 2017 at 5:30
-
Possible duplicate of The easiest way to transform collection to array?castletheperson– castletheperson2017年02月03日 05:33:13 +00:00Commented Feb 3, 2017 at 5:33
-
Unless you have other reasons, Android advice is to use SparseArray<File> instead of Map<Integer, File>: less boxing, lower memory usage.ephemient– ephemient2017年02月03日 05:51:09 +00:00Commented Feb 3, 2017 at 5:51
-
Possible duplicate of Java: how to convert HashMap<String, Object> to arrayfaranjit– faranjit2017年02月03日 06:32:03 +00:00Commented Feb 3, 2017 at 6:32
2 Answers 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
Polaris Nation
Thanks you save my time
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
castletheperson
You can skip the intermediate
ArrayList
. Also, why not just use File
?Chetan Joshi
@4castle Yes, you are right and I just put sample code to do this that's why using String .
default