使用 List<> 重载 Java 函数范围 [英] Overloading Java function with List<> parameter

查看:20
本文介绍了使用 List<> 重载 Java 函数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两节课

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

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

当出现客户或申请人列表时,我想要一个函数来迭代列表并使用 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());
    }
}

这篇关于使用 List&lt;&gt; 重载 Java 函数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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