weixin_42298593 2009-04-21 21:42
浏览 390
已采纳

怎么遍历Map集合中的对象?

import java.util.*;

public class TestMap {
public static void main(String[] args) {
Map map=new TreeMap();
map.put(1,new Elent(1,2));
map.put(2,new Elent(2,0));
map.put(3,new Elent(5,1));
map.put(4,new Elent(7,1));
printKeyValuePairs(map);

}

public static void printValues(Map map){
    Collection vs=map.values();
    Iterator it=vs.iterator();
    while(it.hasNext()){
        System.out.println(it.next());
    }
}

public static void printKeyValuePairs(Map map){
    Set ks=map.keySet();
    Iterator it=ks.iterator();
    while(it.hasNext()){
        Object key=it.next();
        Object value=map.get(key);
        System.out.println(key+"  "+value);
    }
}

}
class Elent{
int id,index;
public Elent(int id,int index){
this.id=id;
this.index=index;
}
public int getId(){
return id;
}
public int getIndex(){
return index;
}
}

怎么取KEY值为I的对象ID的值是否为0?

  • 写回答

3条回答 默认 最新

  • wanghaolovezlq 2009-04-21 21:58
    关注

    [code="java"]

    import java.util.*;

    public class TestMap {
    public static void main(String[] args) {
    Map map = new TreeMap();
    map.put(1, new Elent(1, 2));
    map.put(2, new Elent(2, 0));
    map.put(3, new Elent(5, 1));
    map.put(4, new Elent(7, 1));
    printKeyValuePairs(map);
    }

    public static void printValues(Map map) {
        Collection vs = map.values();
        Iterator it = vs.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
    
    public static void printKeyValuePairs(Map map) {
        Set ks = map.keySet();
        Iterator it = ks.iterator();
        while (it.hasNext()) {
            Object key = it.next();
            [color=red]//这里进行强制转换存在map里的value的类型啊
            Elent value = (Elent)map.get(key);
    
            System.out.println(key + "  " + value.getId());[/color]
        }
    }
    

    }

    class Elent {
    int id, index;

    public Elent(int id, int index) {
        this.id = id;
        this.index = index;
    }
    
    public int getId() {
        return id;
    }
    
    public int getIndex() {
        return index;
    }
    

    }

    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?