想象一下对象的数组。
int MAX_ALLOWED = 5; Object [] object = new Object [MAX_ALLOWED];假设该对象是具有其各自位置的游戏的单元。 当用户按下名为“spawn unit”的按钮时,代码将是:
unit [] = new Object (location);如您所见, [_]中没有标识符,因此会出现问题。 我不知道该把什么放在这里。如果我放0,那么每当我创建一个对象时,它将覆盖对象的内存为0。
访问特定对象或单元时。
for (int i = 0; i <= unit.length; i++) { if (location = unit [i].get_Location) { move (unit [i]); } }但是如果我在0之后访问一个元素,这样做会给我一个空指针异常。
Imagine an array of objects.
int MAX_ALLOWED = 5; Object [] object = new Object [MAX_ALLOWED];Suppose the object was a unit for a game with its respective location. When the user presses a button called "spawn unit" the code will be:
unit [] = new Object (location);As you can see there is no identifier in the [ _ ] so this presents the problem. I don't know what to put in here.If I put 0 it will over-ride the memory of the object at 0 every-time I create an object.
When accessing a particular object or unit.
for (int i = 0; i <= unit.length; i++) { if (location = unit [i].get_Location) { move (unit [i]); } }But doing this will give me a null-pointer exception if I access an element after 0.
最满意答案
对于存储事物列表的一般问题,应避免使用数组。 相反,Collections对程序员更友好,而且速度相当快。
在您的情况下,使用数组意味着必须保留最后使用的元素的索引并管理大小等,使用List更容易:
List<Unit> units = new ArrayList<Unit>();然后使用,简单地说:
units.add(new Unit());如果要限制大小,请在添加之前:
if (units.size() == MAX_ALLOWED) { // do something else }迭代元素:
for (Unit unit : units) { // do something with unit }关于列表的好处是它们会根据需要增大尺寸,但在您的情况下可能不需要这样,因为您似乎想要一个固定的最大值。
Arrays should be avoided for the general problem of storing lists of things. Instead, Collections are far more programmer friendly, and still pretty fast.
In your case, using an array would mean having to keep the index of the last used element and manage the size, etc, etc. Using a List is way easier:
List<Unit> units = new ArrayList<Unit>();then to use, simply:
units.add(new Unit());if you want to restrict the size, before you add:
if (units.size() == MAX_ALLOWED) { // do something else }To iterate over the elements:
for (Unit unit : units) { // do something with unit }A good thing about Lists is they will grow in size as needed, although in your case this may not be needed as you seem to want a fixed maximum.
更多推荐
发布评论