【问题标题】:How I can convert the hashmap to array?如何将哈希图转换为数组?
【发布时间】:2017-06-20 10:06:13
【问题描述】:

我想把 hashmap 放到数组中

我创建哈希图

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

然后放一些地图数据

我将这个 hashmap 的值转换为数组,所以

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

但是会出现错误;

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

我知道当我想将 hashmap 的值排列成数组时,使用 .values.toArray() 但可能不正确;

这种方式不对吗?

【问题讨论】:

标签: android arrays hashmap


【解决方案1】:
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

数组。不带参数的 toArray 会创建一个对象数组,因为在运行时会丢失列表的类型信息。

【讨论】:

  • 感谢您节省了我的时间
【解决方案2】:

请使用以下代码将 HashMap 转换为 Array ,您可以根据自己的情况将 String 更改为 File。

   //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()])

【讨论】:

  • 你可以跳过中间的ArrayList。另外,为什么不直接使用File
  • @4castle 是的,你是对的,我只是放了示例代码来做到这一点,这就是使用 String 的原因。
猜你喜欢
  • 2015-11-26
  • 2019-10-27
  • 2019-05-23
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-01
  • 2015-09-13
相关资源
最近更新 更多