java 如何在 BlueJ 中为 ArrayList 输入参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16018998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I enter parameters for an ArrayList in BlueJ?
提问by user1894469
In BlueJ, if I write a method that takes an array as a parameter, then when I want to test that method with a method call I have to enter the elements with curly braces, so:
在 BlueJ 中,如果我编写一个将数组作为参数的方法,那么当我想使用方法调用测试该方法时,我必须用花括号输入元素,因此:
{1,2,3}
{1,2,3}
How do I do a method call for an ArrayList
?
我如何为 做一个方法调用ArrayList
?
Here is my code:
这是我的代码:
import java.util.*;
public class Test2{
public static int[] toArray(ArrayList<Integer>a){
int len = a.size();
int []b = new int[len];
for(int i = 0; i<len; i++){
b[i] = a.get(i);
}
return b;
}
}
Now I want to test it in BlueJ, what should I type in the following dialog box?
现在我想在BlueJ中测试,在下面的对话框中应该输入什么?
回答by Bill the Lizard
You need to create an instance of ArrayList
to pass to your method when you call it. With your project open in the main BlueJ window, click on the Tools menu, then on "Use Library Class...", then select java.util.ArrayList
from the Class menu. Also select the no-argument constructor from the list that appears, then click Ok.
您需要创建一个实例ArrayList
以在调用它时传递给您的方法。在 BlueJ 主窗口中打开您的项目后,单击 Tools 菜单,然后单击“Use Library Class...”,然后java.util.ArrayList
从 Class 菜单中进行选择。同时从出现的列表中选择无参数构造函数,然后单击确定。
BlueJ will then display another dialog asking you for a name for the instance and for a type parameter for the ArrayList
. Enter a name and Integer
for the type parameter.
BlueJ 然后将显示另一个对话框,询问您实例的名称和ArrayList
. 输入名称和Integer
类型参数。
After you click Ok, the new ArrayList
instance will appear in the object bench area at the bottom of the main BlueJ window.
单击“确定”后,新ArrayList
实例将出现在 BlueJ 主窗口底部的对象工作台区域中。
When you right click on the new instance, BlueJ will display a menu of methods that can be called on it. Select the boolean add(Integer)
method a few times to add some values to the instance.
当您右键单击新实例时,BlueJ 将显示可对其调用的方法菜单。boolean add(Integer)
多次选择该方法以向实例添加一些值。
Finally, when you right click on your test class and call the toArray
method, you can enter the name of the ArrayList
instance to pass it as the argument to your method.
最后,当您右键单击您的测试类并调用该toArray
方法时,您可以输入ArrayList
实例的名称以将其作为参数传递给您的方法。
The results of the method call are displayed in a dialog.
方法调用的结果显示在对话框中。
Click the Inspect button to view the contents of the int
array returned from your method, or click the Get button to add it to the object bench.
单击 Inspect 按钮查看int
从您的方法返回的数组的内容,或单击 Get 按钮将其添加到对象工作台。
回答by Simon Arsenault
Arrays.asList("1", "2", "3");
Will return a List
and not a ArrayList
.
将返回 aList
而不是 a ArrayList
。
Your methods' parameters should always be the interface and not the implementation.
您的方法的参数应该始终是接口而不是实现。