Java - ArrayList<Integer> as Parameter...?
Solution 1
I'm assuming this is a learning exercise. I'll give you a few hints:
- Your method is named showArray, but an
ArrayList<T>
is of typeList<T>
, and is not an array. More specifically it is a list that is implemented by internally using an array. Either change the parameter to be an array or else fix the name of the method. - Use an interface if possible instead of passing a concrete class to make your method more reusable.
- Minor point: It may be better to have your 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 a loop and a StringBuilder to construct the toPrint string.
Solution 2
Is there any reason why System.out.println( array );
wouldn't work for you?
Output will be like:
[1, 2, 3]
Solution 3
If you are looking to print the array items, try
public void showArray(ArrayList<Integer> array){
for(int arrayItem : array)
{
System.out.println(arrayItem);
}
}
Mus
“Data Scientist (n.): Person who is better at statistics than any software engineer and better at software engineering than any statistician.” ― Josh Wills, Director of Data Engineering at Slack
Updated on March 05, 2020Comments
-
Mus about 4 years
I would like to know how to create a method which takes an ArrayList of Integers (ArrayList) as a parameter and then display the contents of the ArrayList?
I have some code which generates some random numbers and populates the ArrayList with the results, however I keep having errors flag up in eclipse when attempting to create this particular method.
Here is what I have so far:
public void showArray(ArrayList<Integer> array){ return; }
I know that it is very basic, but I am unsure exactly how to approach it - could it be something like the following?
public void showArray(ArrayList<Integer> array){ Arrays.toString(array); }
Any assistance would be greatly appreciated.
Thank you.