将Map转换为2维数组

时间:2012-06-04 11:15:41

标签: java data-structures

我有一张地图并尝试将其转换为二维数组。为此,我将Map的值转换为list,然后尝试转换为2维数组。

我的代码是

try {
List list = new ArrayList(layoutMap.values());
int listSize = list.size();
ArrayList[][] layoutList = new ArrayList[listSize][];
for(int i = 0; i < listSize; i++){
    List sublist = (ArrayList) list.get(i);
    int subListSize = sublist.size();
    layoutList[i] = new ArrayList[subListSize];
    for (int j = 0; j < subListSize; j++) {
    layoutList[i][j] =  (ArrayList) sublist.get(j);
    }
} 
} catch (Exception e) {
log.error("@layoutMapDetails () :", e);
}

当我这样做时,我得到了类强制转换异常com.pojo.layout.LayoutDetails cannot be cast to java.util.ArrayList有没有办法解决这个问题。将List转换为二维数组是正确的吗?这里的layoutMap是Map<Integer, List>

1 个答案:

答案 0 :(得分:0)

final Object[][] result = new Object[map.size()][2];

final Iterator<?> iter = map.entrySet().iterator();

int ii = 0;
while(iter.hasNext()){
    final Map.Entry<?, ?> mapping = (Map.Entry<?, ?>) iter.next();

    result[ii][0] = mapping.getKey();
    result[ii][1] = mapping.getValue();

    ii++;
}