java 函数对象,Java中的函数对象

I wanna implement a javascript like method in java , is this possible ?

Say , I have a Person class :

public class Person {

private String name ;

private int age ;

// constructor ,accessors are omitted

}

And a list with Person objects:

Person p1 = new Person("Jenny",20);

Person p2 = new Person("Kate",22);

List pList = Arrays.asList(new Person[] {p1,p2});

I wanna implement a method like this:

modList(pList,new Operation (Person p) {

incrementAge(Person p) { p.setAge(p.getAge() + 1)};

});

modList receives two params , one is a list , the other is the "Function object", it loops the list ,and apply this function to every element in the list. In functional programming language,this is easy , I don't know how java do this? Maybe could be done through dynamic proxy, does that have a performance trade off compares to native for loop ?

解决方案

You can do it with an interface and an anonymous inner class implementing it, like

Person p1 = new Person("Jenny",20);

Person p2 = new Person("Kate",22);

List pList = Arrays.asList(p1, p2);

interface Operation {

abstract void execute(Person p);

}

public void modList(List list, Operation op) {

for (Person p : list)

op.execute(p);

}

modList(pList, new Operation {

public void execute(Person p) { p.setAge(p.getAge() + 1)};

});

Note that with varargs in Java5, the call to Arrays.asList can be simplified as shown above.

Update: A generified version of the above:

interface Operation {

abstract void execute(E elem);

}

public void modList(List extends E> list, Operation op) {

for (E elem : list)

op.execute(elem);

}

modList(pList, new Operation() {

public void execute(Person p) { p.setAge(p.getAge() + 1); }

});

Note that with the above definition of modList, you can execute an Operation on e.g. a List too (provided Student is a subclass of Person). A plain List parameter type would not allow this.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值