I'm trying to add the int values of Integer objects within an ArrayList, using a recursion (for the first time). Here's what I have so far:
import java.util.Scanner;
import java.util.ArrayList;
public class SumArrayList {
private static int calculateSumArrayListHelper(ArrayList<Integer> duplicate) {
if (duplicate.size() == 0) {
return 0;
}
int lastNum = duplicate.get(duplicate.size()-1).intValue();
return lastNum + calculateSumArrayListHelper(duplicate.remove(duplicate.size()-1));
}
public static int calculateSumArrayList(ArrayList<Integer> original) {
ArrayList<Integer> duplicate = (ArrayList<Integer>) original.clone();
return calculateSumArrayListHelper(duplicate);
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
System.out.println("How many values should the ArrayList contain?");
int arrayLength = reader.nextInt();
System.out.println("Enter "+arrayLength+" integers:");
for (int i = 0; i < arrayLength; i++) {
Integer j = new Integer(reader.nextInt());
list.add(j);
}
System.out.println("The sum of all the integers in that ArrayList is: "+calculateSumArrayList(list));
}
}
And of course, the compile error:
SumArrayList.java:10: calculateSumArrayListHelper(java.util.ArrayList<java.lang.Integer>) in SumArrayList cannot be applied to (java.lang.Integer)
return lastNum + calculateSumArrayListHelper(duplicate.remove(duplicate.size()-1));
^
SumArrayList.java:10: operator + cannot be applied to int,calculateSumArrayListHelper
return lastNum + calculateSumArrayListHelper(duplicate.remove(duplicate.size()-1));
^
SumArrayList.java:10: incompatible types
found : <nulltype>
required: int
return lastNum + calculateSumArrayListHelper(duplicate.remove(duplicate.size()-1));
^
Note: SumArrayList.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
3 errors
First of all, I don't know why I'm getting the "Notes" because I'm pretty sure I've specified what type of object goes into each ArrayList that I've created. Second, why does the computer think that duplicate.remove(duplicate.size()-1)
is an Integer? All I'm doing is removing the last element of the ArrayList, so it should still be an ArrayList, right? It's getting reaaallly hard to remain calm with these programs...
P.S. I know I've posted in this forum a lot lately, so I just wanted to say thank you to everyone who has helped me, and thank you in advance to those who will help me!