java - 如何构建泛型类和构造函数以使用泛型方法?

标签 java class generics constructor

我在理解如何构建类和泛型构造函数时遇到问题。 我对泛型还很陌生,但现在我有了基本的了解。

以下方法有效:

@Override
public <T> List<T> groupProceeds(Collection<? extends T> e, Function<? super T, Integer> p) {
    int from = 10001;
    int to = 10070;
    int sum = 1010000;

    return buildGroup(e, p, from, to, sum);
}

如何在类中使用此方法?该类应该具有构造函数和通用属性。

这是我的方法之一,但行不通。但我也不知道如何解决。

public class StandardStructure<T, P> {

    private T entities;
    private P property;


    public StandardStructure (Collection<? extends T> entities, Function<? super T, Integer> property) {
        this.entities = entities;
        this.property = property;

    }

    @Override
    public <T> List<T> groupProceeds(Collection<? extends T> e, Function<? super T, Integer> p) {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(e, p, from, to, sum);
    }
}

构造类时,应将集合实体函数属性传递给方法。

我需要帮助设置类和泛型构造函数。

最佳答案

我想到的一些事情:

  • 您的泛型中不需要 P 类型,因为 property 属性的类型以 T 表示>

  • 如果您将实体属性作为类变量,则无需将它们传递给groupProceeds方法

  • 此处不能使用 @Override,因为您没有扩展任何类或实现任何接口(interface)

  • 您不应该使方法通用,因为它会隐藏类通用。您想要与 T 类相同的 T。

尝试这样:

public class StandardStructure<T> {

    private Collection<? extends T> entities;
    private Function<? super T, Integer> property;

    public StandardStructure (Collection<? extends T> entities, Function<? super T, Integer> property) {
        this.entities = entities;
        this.property = property;
   }

    public List<T> groupProceeds() {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(entities, property, from, to, sum);
    }

    private List<T> buildGroup(Collection<? extends T> e,  Function<? super T, Integer> p, int from, int to, int sum) {
        /* Whatever that does */
    }
}

或者,如果您想将参数传递给方法,则不需要它们作为类的属性,甚至不再需要构造函数:

public class StandardStructure<T> {

    public List<T> groupProceeds(Collection<? extends T> entities, Function<? super T, Integer> property) {
        int from = 10001;
        int to = 10070;
        int sum = 1010000;

        return buildGroup(entities, property, from, to, sum);
    }

    private List<T> buildGroup(Collection<? extends T> e,  Function<? super T, Integer> p, int from, int to, int sum) {
         /* Whatever that does */
    }
}

关于java - 如何构建泛型类和构造函数以使用泛型方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58916011/

相关文章:

java - 带有 Web 服务的 SMSlib

java - 如何在 Hibernate 上实现 GenericDAO 类

c# - 具有逆变类型参数和 Unity 容器的泛型

java - 如何在 Eclipse 中查看 JRE 的源代码?

java - 多个组件的 Swing 数据绑定(bind)

java - 静态方法调用另一个静态方法,对象引用作为参数 :Is It Thread Safe?

javascript - 返回值而不是 self 的类

C++ const 函数错误

java - 获取类的所有实例

C# 遍历作为泛型传递的字典