我在理解如何构建类和泛型构造函数时遇到问题。 我对泛型还很陌生,但现在我有了基本的了解。
以下方法有效:
@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/