- 我正在根据预定义的数组创建两个
ArrayList
。 - 我需要获取两个
ArrayList
中的每个元素并乘以多个值,并将答案存储在第三个ArrayList
中。例如:ListA[0] * ListB[0] = ListC[0]
- 我需要将所有三个列表输出到控制台。
我已经创建并填充了第一个列表,但计算方法extend
让我感到困惑。下面列出了我所拥有的代码。谁能对我在这里缺少的内容提供任何见解?
package threeArrayLists;
import java.util.ArrayList;
public class ThreeArrayLists {
public static void main(String[] args) {
double [] price_Array = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
double [] quantity_Array = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
ArrayList<Double> priceList = new ArrayList<Double>();
ArrayList<Double> quantityList = new ArrayList<Double>();
ArrayList<Double> amountList = new ArrayList<Double>();
for (int i = 0; i < price_Array.length; i++) {
priceList.add(price_Array[i]);
}
for (int j = 0; j < quantity_Array.length; j++) {
quantityList.add(quantity_Array[j]);
}
extend(priceList, quantityList, amountList);
}
private static void extend(ArrayList<Double> prices,
ArrayList<Double> quantity,
ArrayList<Double> amount) {
for (int k = 0; k < prices.size() && k < quantity.size(); k++) {
amount.add(prices[k] * quantity[k]);
}
}
}
最佳答案
你真的需要列表吗?从您帖子中的代码来看,这还不清楚, 并且没有明显的理由使用列表。 仅使用数组,实现可以更短、更简单:
public static void main(String[] args) {
double[] priceArray = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
double[] quantityArray = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
double[] amountArray = multiply(priceArray, quantityArray);
}
private static double[] multiply(double[] prices, double[] quantity) {
double[] result = new double[prices.length + quantity.length];
for (int k = 0; k < prices.length && k < quantity.length; k++) {
result[k] = prices[k] * quantity[k];
}
return result;
}
如果您确实想使用列表:
public static void main(String[] args) {
Double[] priceArray = {10.62, 14.89, 13.21, 16.55, 18.62, 9.47, 6.58, 18.32, 12.15, 3.98};
Double[] quantityArray = {4.0, 8.5, 6.0, 7.35, 9.0, 15.3, 3.0, 5.4, 2.9, 4.8};
List<Double> priceList = Arrays.asList(priceArray);
List<Double> quantityList = Arrays.asList(quantityArray);
List<Double> amountList = multiply(priceList, quantityList);
}
private static List<Double> multiply(List<Double> prices, List<Double> quantity) {
List<Double> result = new ArrayList<Double>();
for (int k = 0; k < prices.size() && k < quantity.size(); k++) {
result.add(prices.get(k) * quantity.get(k));
}
return result;
}
注释:
- 只要有可能,最好通过接口(interface)类型而不是实现类型来声明变量,例如
List<Double>
而不是ArrayList<Double>
- 将列表传递给 void 方法进行修改并不是一个好主意。最好让该方法创建列表并返回它
- Java 中的变量名称应为
camelCase
,无下划线(无_
字符) - 一个巧妙的技巧:如果将数组的类型从
double[]
更改为至Double[]
,您可以使用Arrays.asList
轻松将其转换为列表,就像我在上面的例子中所做的那样
关于java - 在 Java 中将三个 ArrayList 中的元素相乘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26328020/