地图:在Java地图中,我可以将函数分配给< K,V>中的值。对? [英] Maps : In Java Maps can I assign a function to the value in the <K,V> pair?

查看:76
本文介绍了地图:在Java地图中,我可以将函数分配给< K,V>中的值。对?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组字符串,我将用它作为Keys和一个特定的字符串,我想要一个函数被调用。那么是否有可能为该对中的值分配一个函数?

  exampleMap.get(SOME_STRING); //应该调用一个函数abc(); 


解决方案

将函数封装在Java接口中:

  public interface Task {
void doSomething();
}

然后用这个接口的实例打开地图:



$ p $ map.put(someString,new Task(){
@Override
public void doSomething(){
System.out.println(foo);
}
});
map.put(someOtherString,new Task(){
@Override
public void doSomething(){
System.out.println(bar);
}
});

然后调用与给定字符串 s

  map.get(s).doSomething(); 


I have a set of string which I will be using as the Keys and for a particular string I want a function to be called. So is it possible to assign a function to the value in the pair?

exampleMap.get("SOME_STRING"); // should call a function abc();

解决方案

Encapsulate your function in a Java interface:

public interface Task {
    void doSomething();
}

and then pouplate the map with instances of this interface:

map.put("someString", new Task() {
    @Override
    public void doSomething() {
        System.out.println("foo");
    }
});
map.put("someOtherString", new Task() {
    @Override
    public void doSomething() {
        System.out.println("bar");
    }
});

Then to call the function (task) associated with a given string s:

map.get(s).doSomething();

这篇关于地图:在Java地图中,我可以将函数分配给< K,V>中的值。对?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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