日期:2014-05-20  浏览次数:20822 次

为什么List.toArray()之后不能转换类型?
Java code
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
         Map<String, Object> m1 = new HashMap<String, Object>();
         m1.put("1","1");
         Map<String, Object> m2 = new HashMap<String, Object>();
         m2.put("2","2");
         list.add(m1);
         list.add(m2);
         System.out.println(list.toString());
         Map[] arr = new HashMap[list.size()];
         Object[] objs = list.toArray();
         arr = (Map[])objs;


运行代码,出错
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;

------解决方案--------------------
返回的本来就是一个Object数组,只不过每一维放的都是HashMap
给你下面这个例子你说明白了

Java code

        Object obj[] = new Object[]{1,2,3};
        System.out.println(Integer[].class.isInstance(obj));
        System.out.println(Object[].class.isInstance(obj));
        
        Object obj2[] = new Integer[]{1,2,3};
        System.out.println(Integer[].class.isInstance(obj2));
        System.out.println(Object[].class.isInstance(obj2));//这个输出true是因为Object是Integer的super

------解决方案--------------------
Java code
package com.j913;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Test2 {
    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> m1 = new HashMap<String, Object>();
        m1.put("1","1");
        Map<String, Object> m2 = new HashMap<String, Object>();
        m2.put("2","2");
        list.add(m1);
        list.add(m2);
        System.out.println(list.toString());
        Map[] arr = new HashMap[list.size()];
        Object[] objs = list.toArray(arr);//这儿,,告诉转换时,Object[]里面存储的是Map,
        //不写的话Object[]里面放的都是Object类型的,下一步转换当然是错误的了。因为里面不对应。
       
        arr = (Map[])objs;
    }
}