0

I'm trying to do this Java How To Program Task: "Write an appliaction that calculates the product of a series of integers that are passed to method 'product' using a variable-length argument list.

I get the error message that the method product(Integer...) in the type VarLenArgumentList is not applicable for the arguments (ArrayList). Why so, if Java treats the variable-length argument list as an array? Isn't an ArrayList an array?

What is another way of completing the task?

Scanner keyboard = new Scanner(System.in);
int flag = 0;
ArrayList<Integer> intArray = new ArrayList<>();

do
{
    System.out.print("Enter a positive integer or '-1' to quit:" );
    int input = keyboard.nextInt();
    intArray.add(input);

} while (flag != -1);

product(intArray); 
}

public static int product (Integer... numbers) 
{
    int total = 0;

    for (Integer element : numbers)
        total *= element;

    return total;
}
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
enhancedJack
  • 265
  • 1
  • 6
  • 15
  • Nope, this is not a dupe, at least not for the linked question. THe question here is mainly `Isn't an ArrayList an array?`, which is NOT the question in the linked thread. – amit May 05 '15 at 21:39
  • In the example you posted `} while (flag == -1);` should be `} while (input != -1)` to match your print condition also `System.out.printf` should require a `String format` argument, which I don't see in your example, so I'm guessing you meant `System.out.print` or `System.out.println`. – anonymous May 05 '15 at 21:50
  • You're right, of course. I've edited my post and improved it. – enhancedJack May 06 '15 at 08:45

2 Answers2

4

Integer... parameter accepts arbitrary number of Integer objects, or an array Integer[]. Since ArrayList<Integer> is not an Integer[], it is not accepted.

ArrayList is NOT an array, it is a Collection, while array in java is a different object.

You can however use toArray(T) method to easily turn your ArrayList into an array. but note that it will be a DIFFERENT object, and this is useful mainly when you just want to read from the collection, not write to it.

amit
  • 175,853
  • 27
  • 231
  • 333
0

What is another way of completing the task?

You can pass a List of Integer into the method.

 public static int product (List<Integer> integerList) 
    {
    Integer total = 0;

    for (Integer element : integerList)
        total *= element;

    return total;
    }
underdog
  • 4,447
  • 9
  • 44
  • 89