超载列表与LT Java函数;>参数 [英] Overloading Java function with List<> parameter

查看:197
本文介绍了超载列表与LT Java函数;>参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个班

public class Customer{
  ...
  public String getCustomerNumber();
  ...
}

public class Applicant{
   ....
   private Customer c;
   public Customer getCustomer(){ return c; }
   ...
}

在与客户或申请人名单psented $ P $我想它迭代列表,并做一些事为CustomerNumber。功能

When presented with a list of customers or applicants I want a function which iterates the list and does something with the CustomerNumber.

我试过重载函数

public void processCustomerNumbers(List<Customer> custList)
...

public void processCustomerNumbers(List<Applicant> appList)
...

但这些被视为重复的方法......有没有这样做,而不是仅仅有2命名不同功能的一个很好的方式?

but these are seen as duplicate methods... is there a nice way of doing this rather than just having 2 differently named functions?

推荐答案

如果你让这两个类实现共同的接口,

If you make both classes implement a common interface,

interface CustomerNumber {
    String getCustomerNumber();
}

public class Customer implements CustomerNumber {
  ...
  public String getCustomerNumber();
  ...
}

public class Applicant implements CustomerNumber {
   ....
   private Customer c;
   public Customer getCustomer() { return c; }
   public String getCustomerNumber() { return getCustomer().getCustomerNumber(); }
   ...
}

那么你也许可以做你想做的只是一个单一的方法是什么:

then you might be able to do what you want with just a single method:

public void processCustomerNumbers(List<? extends CustomerNumber> appList) {
    for (Customer c: appList) {
        processCustomerNumber(c.getCustomerNumber());
    }
}

这篇关于超载列表与LT Java函数;&GT;参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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