HasnMap的问题
如何把HashMap中的内容,转换到数组,然后打印出来
{a={a=1}}变成aa 啊,请高手帮忙了
------解决方案--------------------//转化为数组
Object[] array=new Object[hashmap.size()];
int i=0;
for(Object O:hashmap)
Object[i++]=o;
//打印
for(Object o:array)
System.out.println(o);
------解决方案--------------------List list = new ArrayList();
for(Iterator it = hashMap.keySet().iterator();it.hasNext();)
{
Entry entry = hashMap.Entry(it.next());
list.add(entry);
}
Object[] arr = list.toArray();
for(Object o:array)
{
System.out.println(o);
}
------解决方案--------------------Map提供的有接口,可以直接转化为数组的,没必要那么麻烦:
Map m = new HashMap();
m.put(....);
.....
String[] arr = (String[])m.entrySet().toArray(new String[m.size()]);
------解决方案--------------------不知道是不是你要的效果,机器里没有jdk1.5
import java.util.HashMap;
import java.util.Map;
class HashMapToArray {
HashMapToArray() {
}
public static void main(String[] args) {
HashMapToArray c = new HashMapToArray();
Map map = c.getMap();
Object [] obj = c.toArray(map);
c.test(obj);
}
private Map getMap() {
Map map = new HashMap();
map.put( "1 ", "10 ");
map.put( "2 ", "20 ");
map.put( "3 ", "30 ");
map.put( "4 ", "40 ");
map.put( "5 ", "50 ");
return map;
}
private Object[] toArray(Map map) {
return map.entrySet().toArray(new Object[map.size()]);
}
private void test(Object[] obj) {
for (int i = 0; i < obj.length ; i++) {
System.out.println(obj[i]);
}
}
}