When primitive arrays given,
int[] iArr = new int[]{0,1,2,3,4};
long[] lArr = new int[]{0,1,2,3,4};
double[] dArr = new int[]{0,1,2,3,4};
And Each provided by Supplier,
class IarrSupplier {
int[] supply();
}
class LarrSupplier {
long[] supply();
}
class DarrSupplier {
double[] supplyer();
}
How can I add them all in an abstraction way? Such as
interface PSupplier<T> {
T[] supply();
}
And providers are implements PSupplier<T>
class IarrSupplier implements PSupplier<int> {
int[] supply();
}
class LarrSupplier implements PSupplier<long[]> {
long[] supply();
}
class DarrSupplier implements PSupplier<double[]> {
double[] supplyer();
}
I know primitive type generic is not supported in java. And so above will not work at all.
But If it works, I hope to do,
// same or several type of PSuppliers will be provided.
PSupplier[] suppliers = polymorphsSuppliers();
long[] totalSumArray = [my_fixed_length];
for(PSupplier supplier : suppliers){
for(int i = 0 ; i < totalSumArray.length ; i++){
totalSumArray[i] += supplier.supply()[i];
}
}
What would possible/better design to do this?
In short,
I don't know what you want to do exactly, but I can see several problems about your code. I guess you want to iterate over an unidimensional array, so, in the interface PSupplier it's not neccesary declare the method that returns an array T[] , so the fixed code would be:
interface PSupplier<T> { T supply(); }
Now the next classes which implement from PSupplier interface, their generic type must be an array of the data type you want, for example:
class IarrSupplier implements PSupplier<int[]> {
@Override
public int[] supply() {
return new int[]{1,2,3,4,5,6,7};
}
}
Remember that the generics accept only Objects, and, unless in java, an array is an object, it doesn't matter if its type is primitive,so, for that reason, you can type PSupplier<int[]> and will be correct. Or you can use PSupplier<Integer[]> and will be correct too, because Integer is a wrapper class for int data type. If you don't know about wrapper classes in java, I recommend read about that: Wrapper classes in java
For the method polymorphsSuppliers() must return an array of PSupplier , for example:
** here, the polymorphism is working **
PSupplier[] polymorphsSuppliers(){
return new PSupplier[]
{
new IarrSupplier(),
new LarrSupplier(),
new DarrSupplier(),
......
};
}
About your code in the for loops, I don't understand what you want to do exactly. But I hope the examples I typed work for you.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.