Reputation: 560
I have problems understanding how to build a class and a constructor generic. I'm pretty new to generics, but now I have a basic understanding.
The following method works:
@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);
}
How is it possible to use this method in a class? The class should have a constructor and generic properties.
This is one of my approaches, this doesn't work. But I also don't know how to solve it.
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);
}
}
When constructing the class, Collection entities and Function property should be passed to the method.
I need help setting up the class and the constructor generic.
Upvotes: 2
Views: 65
Reputation: 9756
A few things I would think of:
You don't need the P
type in your generics because the type of your property
attribute is expressed in terms of T
If you have your entities
and property
as class variables, you don't need to pass them to your groupProceeds
method
You can't use @Override
here because you are not extending any class or implementing any interface
You should not make the method generic as it would hide the class generic. You want the same T as the class T.
Try it this way:
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 */
}
}
Or if you want to pass the parameters to the method, you don't need them as attributes on the class and don't even need the constructor anymore:
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 */
}
}
Upvotes: 2