You have not provided two lists of integers to sum together. You have dynArrList
as an addend, and you have arrList1
for the result. But you don't have a second addend, which should tell you that you don't really understand your problem yet. Either your real task isn't what you think it is, or you haven't correcltly identified where you are getting your data from.
So, suppose you have two List<Integer>
s. Program to the interface where possible. How would you do an item by item sum? Write a sum method, and recognize what can happen if the two lists are of different sizes.
public List<Integer> sum(List<Integer> left, List<Integer> right) {
if (left.size() != right.size()) {
// A runtime exception you write saying that you can't add two
// arrays of different sizes.
throw new VectorShapeException(left.size(), right.size());
}
List<Integer> vectorSum = new ArrayList<>();
for (int i = 0; i < left.size(); ++i) {
vectorSum.add(left.get(i) + right.get(i));
}
return vectorSum;
}
Identify what you want to add, and use this.
Now, suppose you had the assignment to calculate the dot product of two integer array lists. You'd might want two things--a method to sum the elemnts of one list, and a method to get a vector of products. This might be wasteful, as you probably don't need the intermediate list, and you'd be wasting space. The first task is easy:
public int sum(List<Integer> list) {
int total = 0;
for(Integer element: list) {
total += element;
}
return total;
}
The second is easy; just copy and rename things:
public List<Integer> product(List<Integer> left, List<Integer> right) {
if (left.size() != right.size()) {
// A runtime exception you write saying that you can't multiply two
// arrays of different sizes.
throw new VectorShapeException(left.size(), right.size());
}
List<Integer> vectorProd = new ArrayList<>();
for (int i = 0; i < left.size(); ++i) {
vectorProd.add(left.get(i) * right.get(i));
}
return vectorProd;
}
public int dotProduct(List<Integer> left, List<Integer> right) {
return sum(product(left, right));
}
But there's a tedious problem here. The cut and paste and modify is a sign that I wasn't really thinking there. The only real difference between the 2-argument sum and product methods is the operator and the names. This leads to functional programming, which is probably too much for now.