【问题标题】:Is there any way to make this typified method generic?有什么方法可以使这个典型的方法通用吗?
【发布时间】:2020-02-25 13:44:15
【问题描述】:

我正在尝试编写一种方法,该方法采用任何类型的任何集合、两个函数和两个表示一定限制的整数值。

为了更好地理解,我将展示一个我想构建通用的示例方法。

private void buildSums() {
    double sum = 0;
    for (YearlyLineValuesEntity y_l_v_E : yearlyList) {
        if (y_l_v_E.getDb() >= 20001 && y_l_v_E.getDb() <= 20155) {
            sum += y_l_v_E.getAmount();
        }
    }
}

示例方法中的返回值在这种情况下并不重要。仅用于对我的目标有一个基本的了解。

这是我的尝试:

上面if语句中的数字由我尝试过的以下方法中的参数“from”和“to”表示。 getDb() 应该来自参数“propertyDb”,getAmount() 应该来自“propertyAmount”-paramater。

    <T> List <Double> sumUpGroup(Collection<? extends T> entityList, Function<? super T, Integer> propertyDb, Function<?
        super T, Double> propertyAmount, int from, int to) {
    Double sum = null;
    List<Double> list = null;
    for (int i = 0; i < entityList.size(); i++) {
        EntityList x = entityList.get(i); //generic type
        if (x.getDB() >= from && x.getDB() <= to) { //propertyDb here
            sum += x.getAmount(); //propertyAmount here
        }
    }
    list.add(sum);
    return list;
}

我不知道如何使用作为方法中的参数的 2 个函数在代码中进一步处理。我需要另一种方法来解决这个问题吗?

你们有什么想法吗?谢谢

【问题讨论】:

  • 所以你想提供访问器?比如sum += propertyAmount.apply(x);?你的sum 显然不能是T,它应该是double,你应该返回List&lt;Double&gt; 而不是List&lt;T&gt;,因为T 是为你的实体类型保留的。
  • 是的..对,改变了返回值..
  • "所以要提供访问器?比如sum += propertyAmount.apply(x);?"是的,我想是的:)
  • EntityList.get(i) 在这种情况下只能返回Object。你不知道类型。 Collection 也不支持 .get(...)。
  • 如果你想使用实体的访问器,那么它们都应该是某个接口。目前尚不清楚您想对这些函数做什么,但我认为该函数应该接受相同的接口并在其上执行某些操作,然后您使用 apply。这里实际上不需要泛型方法。

标签: java function generics typed


【解决方案1】:

类似下面的东西会起作用(为了清楚起见,我删除了列表内容)

<T> double sumUpGroup(Collection<? extends T> entityList, 
    Function<? super T, Integer> dbAccessor, 
    Function<? super T, Double> amountAccessor, 
    int from, int to) {

    double sum = 0;
    for (T entity : entityList) {
        int value = dbAccessor.apply(entity);
        if (value >= from && value <= to) {
            sum += amountAccessor.apply(entity);
        }
    }

    return sum;
}

然后您可以按如下方式调用该方法,当然要给出正确的方法名称

sumUpGroup(myEntities, Entity::getDbValue, Entity::getAmount, 0, 100);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-05-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 1970-01-01
相关资源
最近更新 更多