hashMap可以很方便得得到某个key索引的值,但是如果要遍历hashMap,有什么办法可以很方便得得到第i个值?(如同get(i))
解决方案 »
- 关于锁的可重入性的一个小问题,诸位大神给讲一下
- 这道题选嘛呢?
- 怎么用Java下载中文网页?请给出代码。小弟将十分感谢!!!
- 向表user中更新用户的口令,在执行JSP过程中出错误,请大家帮我看看,非常感谢.
- 往父窗口的下拉框里加选项,就没有人会么,奇怪/
- 大家帮忙看这个问题String类型 变量
- 小弟求助
- 各位老大求教几个小问题,能给个思路或者代码更好,高分求教
- 谁用java作过his?高分赠送!
- if you need i can help you to pass ocp,ccnp,scjp,ciw.....
- 怎么把中文数字(不是金额)转换成整数
- Java Applet 简单问题,在线等候中....
可以用ArrayList等代替
HashMap hashmap = new HashMap();
hashmap.put("1","hashmap");
System.out.println(hashmap.get("1"));//只能根据键值取
ArrayList array = new ArrayList();
array.add("array");
System.out.println(array.get(0));//可以根据i遍历
public static Map.Entry getMapByIndex(HashMap hashmap, int i) {
HashMap map = hashmap;
Set entrySet = map.entrySet();
Object[] objs = entrySet.toArray();
if (i > -1 && i < objs.length) {
return (Map.Entry) objs[i];
}
return null;
}
HashMap map = new HashMap();
ArrayList list = new ArrayList();
public void put(Object key,Object value)
{
this.map.put(key,value);
this.list.add(key);
}
public String[] keys()
{
return (String[])list.toArray(new String[0]);
}
public Object get(Object key)
{
return this.map.get(key);
}
public static void main(String args[]){
LinkedHashMap h = new LinkedHashMap();
h.put("one", "a");
h.put("two", "b");
h.put("three", "c");
ArrayList e = new ArrayList(h.entrySet());
System.out.println(e);
}看一下结果就好了
"HashMap是不可以的,用LinkedHashMap就可以"我不知道你上面这句话什么意思,按照你最后的那个解法,用LinkedHashMap与HashMap有什么区别,你能告诉我吗?
HashMap<String,Object> hashmap = new HashMap<String,Object>();
Iterator it =hashmap.keySet().iterator();
while (it.hasNext()){
hashmap.get((String)it.next());
}
}
可以通过hashmap.keySet().iterator();
得到hashmap的key的迭代器。
key用String,然后自己可以写一个Object get(String s)方法来得到
while(i.hasNext)
{
Map.Entry map = (Map.Entry)i.next();
Object Key = map.getKey();
Object Value = map.getValue();
}