對於比Java更熟悉Java的人來說,這很可能是一個簡單的問題。這是我的問題的要點:從增強for循環中的通用對象中解析方法調用
我有一個函數,基本上生成一個ArrayList
中包含的對象的可能組合。因爲我有多個需要使用這個函數的對象,函數在尖叫我是泛型的。但是,我遇到的問題是增強型for循環無法解析泛型迭代器的方法調用。我明白爲什麼會發生這種情況,但我對Java不熟悉,不知道如何解決此問題。在任何情況下,這裏是我的代碼:
private <T> ArrayList<T> determineIdealOrderCombination(ArrayList<T> orders, int position){
// Local Variable Declarations
List<ArrayList<T>> subsets = new ArrayList<>();
int k = orders.size()+1; // Add one due to the do-while loop
int theoreticalQuantity;
int indexOfMaxProfit;
double maxProfit;
int[] s; // Here we'll keep indices pointing to elements in input array
double[] profits; // Here we'll keep track of the profit of each combination
// Begin searching for valid combinations
do {
// Setup
k--;
s = new int[k];
profits = new double[k];
// Generate combinations
if ((k <= orders.size()) && (k > 0)) {
// Set the first index sequence: 0, 1, 2,...
for (int i = 0; (s[i] = i) < k - 1; i++) ;
subsets.add(getSubset(orders, s));
for (; ;) {
int i;
// Find position of item that can be incremented
for (i = k - 1; i >= 0 && s[i] == orders.size() - k + i; i--) ;
if (i < 0) {
break;
} else {
s[i]++; // increment this item
for (++i; i < k; i++) { // fill up remaining items
s[i] = s[i - 1] + 1;
}
subsets.add(getSubset(orders, s));
}
}
// All combinations have been evaluated, now throw away invalid combinations that violate the upper limit
// and calculate the valid combinations profits.
for (int i = 0; i < subsets.size(); i++) {
// Calculate the final position
theoreticalQuantity = position;
profits[i] = 0;
for (T t : subsets.get(i)) {
theoreticalQuantity += t.getQuantity(); // <-- THE PROBLEM
profits[i] += calculateProjectedProfit(t.getSecurity(), t.getQuantity(), t.getPrice()); // <-- THE PROBLEM
}
if(theoreticalQuantity > _MAX_POSITION_PER_ASSET){
// Negate profits if final position violates the position limit on an asset
profits[i] = Double.MIN_VALUE;
}
}
}
else{
break;
}
}
while((subsets.size() == 0) );
// Verify that the subset array is not zero - it should never be zero
if(subsets.size() == 0){
return new ArrayList<>();
}
// Return the most profitable combination, if any.
indexOfMaxProfit = -1;
maxProfit = Double.MIN_VALUE;
for(int i = 0; i < profits.length; i++){
if(profits[i] != Double.MIN_VALUE){
if(profits[i] > maxProfit){
maxProfit = profits[i];
indexOfMaxProfit = i;
}
}
}
if((maxProfit > 0) && (indexOfMaxProfit != -1)){
return subsets.get(indexOfMaxProfit);
}
else{
return new ArrayList<>();
}
}
任何幫助,將不勝感激。
你怎麼知道'T'會有'getQuantity()'方法?或不在'java.lang.Object'中的其他方法? – bcsb1001
@ bcsb1001是的,這就是錯誤在我身上引發的原因。作爲作者,我知道這個函數只會被具有此方法的對象使用,但編譯器並不知道這是事實。 – Mlagma
看起來你需要用這些方法創建一個接口。 –