[英]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? 我想知道如何创建一个方法,它将一个ArrayList of Integers(ArrayList)作为参数,然后显示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. 我有一些代码生成一些随机数并用结果填充ArrayList,但是在尝试创建这个特定方法时,我在eclipse中一直有错误标记。
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:
我会给你一些提示:
ArrayList<T>
is of type List<T>
, and is not an array. ArrayList<T>
的类型为List<T>
,并且不是数组。 More specifically it is a list that is implemented by internally using an array. 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. 您可以使用循环和StringBuilder来构造toPrint字符串。
Is there any reason why System.out.println( array );
System.out.println( array );
是否有任何原因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.
如果您只是显示它,并且该方法具有void返回类型,则不必返回任何内容。 I don't know exactly what you want but is it something along the lines of System.out.println(array.elementAt(index))?
我不知道你想要什么,但它是否与System.out.println(array.elementAt(index))一致? then you would need a loop.
然后你需要一个循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.