简体   繁体   中英

Java - ArrayList<Integer> as Parameter…?

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.

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 type List<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM