Map.Entry:如何使用它? [英] Map.Entry : How to use it?

查看:222
本文介绍了Map.Entry:如何使用它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个计算器。
我把我的按钮放在一个HashMap集合,当我想把它们添加到我的类扩展Jpanel,我不知道如何获得按钮从我的收藏。
所以我发现在网上我的代码的最后两行,但我不知道他们的意思。

I'm working on creating a calculator .. I put my buttons on a HashMap Collection and when I want to add them to my Class which extends Jpanel, I don't know how can I get the buttons from my collection. So I found On the net the 2 last lines of my code, but I don't know their meaning.

这是我的代码:

import java.awt.Component;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.swing.JButton;
import javax.swing.JPanel;


public class PanneauCalcul extends JPanel {

    private HashMap<String, JButton> listbouton = new HashMap<String, JButton>() ;

    public PanneauCalcul() {
        for(int i = 0; i < 10; i ++) {
            listbouton.put("num" + i, new JButton("" + i)) ;
        }

        listbouton.put("add", new JButton("+")) ;
        listbouton.put("soustract", new JButton("-")) ;
        listbouton.put("multiply", new JButton("x")) ;
        listbouton.put("divise", new JButton("/")) ;
        listbouton.put("equal", new JButton("=")) ;

        Set entrys = listbouton.entrySet() ;

        Iterator iter = entrys.iterator() ;

        while(iter.hasNext()) {
            Map.Entry me = (Map.Entry)iter.next();  //don't understand 
            this.add((Component) me.getValue()) ;   //don't understand
        }

        EcouteCalcul ecout = new EcouteCalcul(this) ;
    }
}

我不明白我们如何使用 Map.Entry - 这是一个接口 - 不重新定义 Map.Entry 的函数。

I don't understand how can we use Map.Entry -which is an interface- without redefining Map.Entry's functions.

推荐答案

Map.Entry 是一个键及其值组合成一个类。允许你遍历 Map.entrySet(),而不是迭代 Map.keySet(),然后获取每个键的值。更好的方式来写你所拥有的是:

Map.Entry is a key and its value combined into one class. The allows you to iterate over Map.entrySet() instead of having to iterate over Map.keySet(), then getting the value for each key. A better way to write what you have is:

for (Map.Entry<String, JButton> entry : listbouton.entrySet())
{
  String key = entry.getKey();
  JButton value = entry.getValue();

  this.add(value);
}

如果这不清楚,让我知道, 。

If this wasn't clear let me know and I'll amend my answer.

这篇关于Map.Entry:如何使用它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆