Java:如何将 ArrayList 作为对象的实例变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2516778/
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
Java: How to have an ArrayList as instance variable of an object?
提问by JDelage
All,
全部,
I'm working on a class project to build a little Connect4 game in Java. My current thinking is to have a class of Columns that have as instance variable a few integers (index, max. length, isFull?) and one ArrayList to receive both the integers above and the plays of each players (e.g., 1's and 0's standing for X's and O's). This is probably going to be split between 2 classes but the question remains the same.
我正在做一个班级项目,用 Java 构建一个小 Connect4 游戏。我目前的想法是有一类 Columns 作为实例变量有几个整数(索引、最大长度、isFull?)和一个 ArrayList 来接收上面的整数和每个球员的比赛(例如,1 和 0 的立场X 和 O 的)。这可能会分为 2 个班级,但问题保持不变。
My current attempt looks like this:
我目前的尝试是这样的:
import java.util.ArrayList;
public class Conn4Col {
public int hMax;
public int index;
public final int initialSize = 0;
public final int fullCol = 0;
public ArrayList<Integer>;
(...)}
Unfortunately, this doesn't compile. The compiler says an <identifier
> is missing where my ArrayList declaration stands.
不幸的是,这不能编译。编译器说<identifier
我的 ArrayList 声明所在的位置缺少 > 。
We're just starting objects and we haven't really looked into other instance variables than the basic types.
我们刚刚开始创建对象,除了基本类型之外,我们还没有真正研究过其他实例变量。
Can someone tell me where my error is and how to correct it?
有人能告诉我我的错误在哪里以及如何纠正它吗?
Many thanks,
非常感谢,
JDelage
JDelage
采纳答案by Gregory Pakosz
You forgot to give your member a name.
你忘了给你的成员一个名字。
import java.util.ArrayList;
public class Conn4Col {
public int hMax;
public int index;
public final int initialSize = 0;
public final int fullCol = 0;
public ArrayList<Integer> list;
(...)}
回答by Alexander Pogrebnyak
public ArrayList<Integer> list;
But, do not declare ArrayList public:
但是,不要将 ArrayList 声明为 public:
private ArrayList<Integer> list = new ArrayList<Integer> ();
public List<Integer> getList ()
{
return Collections.unmodifiableList(list);
}
回答by Robby Pond
private List<Integer> list = new ArrayList<Integer>();
回答by pitpod
One more addition: better use java.util.List and only use the specific ArrayList during the creation of the object:
另外一个补充:最好使用 java.util.List 并且只在创建对象期间使用特定的 ArrayList :
public List<Integer> list;
...
list = new ArrayList<Integer>();
That way you can change the actual implementation without having to change the member declaration.
这样您就可以更改实际实现而无需更改成员声明。