[英]How can I use 1 array with 2 different sizes using inheritance and constructors
I need to use a single array to track scores of a game where the indices are the levels of the game. 我需要使用单个数组来跟踪游戏的得分,其中索引是游戏的级别。 In the parent class, the player is allowed 10 levels.
在父类中,允许玩家10个级别。 In the child class, they are given 40 additional levels for a total of 50.
在儿童班中,他们获得了40个额外的等级,总计达到50个等级。
This chapter is on inheritance and they also cover constructors. 本章是关于继承的,它们还涵盖了构造函数。 Can a constructor in both parent class and child class change the size of a single array?
父类和子类中的构造函数都可以更改单个数组的大小吗?
I have tried declaring the array to size 50, and then in each constructor allocating memory for the size that I need. 我尝试过声明数组的大小为50,然后在每个构造函数中为我需要的大小分配内存。 [10] and [50] for parent and child classes respectively.
父类和子类分别为[10]和[50]。
In Java arrays are not extendable, so you can not just "use 1 array with 2 different sizes". 在Java中,数组是不可扩展的,因此不能仅仅“使用1个具有2种不同大小的数组”。 You probably want to use
ArrayList
: 您可能要使用
ArrayList
:
List<Integer> list = new ArrayList<>();
There's also a question to ask: are you sure you need inheritance for this task? 还有一个问题要问:确定要为此任务继承吗? You could simply create an array of size you want:
您可以简单地创建所需大小的数组:
List<Integer> list = new ArrayList<>(40);
But even that is not necessary. 但这不是必需的。 The list will grow as needed if there's no space left, so you should not take care about it.
如果没有足够的空间,该列表将根据需要增加,因此您不必担心。
Yes, in the constructor you should just be able redefine it like array = new int[#]
是的,在构造函数中,您应该只能像
array = new int[#]
那样重新定义它
Also, maybe not an exact answer to your question, but you could use a List instead of an array. 另外,也许不是您问题的确切答案,但是您可以使用列表而不是数组。 Java Lists are made to be resizable.
Java列表可调整大小。
So instead of int[]
, you could define it as List<Integer>
and not even have to worry about the size. 因此,您可以将其定义为
List<Integer>
而不是int[]
,而不必担心大小。
The lowest level in your hierarchy must give subclasses the option to define the array size. 层次结构中的最低级别必须为子类提供定义数组大小的选项。
For example: 例如:
package io.medev.stackoverflow;
public class Game1 {
private final int[] levels;
public Game1() {
this(0);
}
protected Game1(int additionalLevels) {
this.levels = new int[10 + additionalLevels];
}
}
And the subclass: 和子类:
package io.medev.stackoverflow;
public class Game2 extends Game1 {
public Game2() {
this(0);
}
protected Game2(int additionalLevels) {
super(40 + additionalLevels);
}
}
Like the others already mentioned, I would generally recommend to use a List instead of arrays in this case. 像已经提到的其他方法一样,在这种情况下,我通常建议使用列表而不是数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.