在 Java 中扩展多维数组 (2D)
如何在 Java 中扩展多维数组?
我需要扩展它的第一个维度。它的格式如下:myArray[x][7]
“7”在所有扩展部分上将保持“7”。
How can I extend a multidimensional array in Java?
I need to extend its first dimension. It's in a format like:myArray[x][7]
The "7" will stay "7" on all extended parts.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Java 中的数组具有固定长度,因此您无法真正扩展它。您必须创建一个更大的新数组,然后将旧数组的内容复制到新数组中。像这样:
您当然也可以使用动态增长的
ArrayList
等。 (这实际上是处理动态增长数组时的首选方法。)Arrays in Java have fixed length, so you can't really extend it. You will have to create a new, larger, array, and then copy the content of the old array into the new one. Like this:
You could of course also use for instance an
ArrayList<SomeType[]>
that grows dynamically. (This is actually the preferred way when dealing with dynamically growing arrays.)您还可以使用 Arrays.copyOf 方法,例如:
You could also use Arrays.copyOf method, for example:
如果您想这样做,请创建一个包含数组作为实例变量并处理与其交互的类。
if you want to do this, make a class that contains the array as an instance variable and handles all interaction with it.
你不能。
您可以创建一个具有正确尺寸的新数组,但我建议您阅读有关 ArrayList 类的信息,该类(据您需要了解)允许动态数组。
You can't.
You could create a new array with the correct dimensions, but I would recommend reading up about the ArrayList class which (as far as you need to know) allows for dynamic arrays.