Java – ArrayList as parameter?
I want to know how to create a method that takes an ArrayList of integers (ArrayList) as a parameter and then displays the contents of ArrayList?
I have some code to generate some random numbers and populate the ArrayList with the results, but I always have error marks in eclipse when trying to create this particular method
This is what I have done so far:
public void showArray(ArrayList<Integer> array){ return; }
I know it's very basic, but I'm not sure how to get close to it - could it be as follows?
public void showArray(ArrayList<Integer> array){ Arrays.toString(array); }
Any help would be appreciated
thank you.
Solution
I assume this is a learning exercise I'll give you some tips:
>Your method is called showarray, but ArrayList < T > is of type list < T > and is not an array More specifically, it is a list implemented by using an array internally Change the parameter to an array, or fix the name of the method. > If possible, use interfaces instead of passing concrete classes to make your methods more reusable. > Small point: it may be better to let the method return a string and display the result outside the method
Try something like this:
public void printList(List<Integer> array) { String toPrint = ...; System.out.println(toPrint); }
You can use loops and StringBuilder to construct toprint strings