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

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

问题描述

我正在创建一个计算器. 我将按钮放在HashMap集合中,当我想将它们添加到扩展了JPanel的类中时,我不知道如何从集合中获取按钮. 因此,我在互联网上找到了我代码的最后两行,但是我不知道它们的含义.

I'm working on creating a calculator. I put my buttons in 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 internet 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. This 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天全站免登陆