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 resul开发者_如何学Cts, 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.
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.
Is there any reason why System.out.println( array );
wouldn't work for you?
Output will be like:
[1, 2, 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);
}
}
This sounds like someone wants us to do their homework. You don't have to return anything if you are just displaying it, and if the method has a void return type. I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))? then you would need a loop.
精彩评论