Java 如何在数组末尾添加元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28549489/
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 to add an element at the end of an array?
提问by Jeffrey Zong
I want to know how to add or append a new element to the end of an array. Is any simple way to add the element at the end? I know how to use a StringBuffer but I don't know how to use it to add an element in an array. I prefer it without an ArrayList or list. I wonder if the StringBuffer will work on integers.
我想知道如何在数组末尾添加或追加新元素。有什么简单的方法可以在最后添加元素?我知道如何使用 StringBuffer 但我不知道如何使用它在数组中添加元素。我更喜欢它没有 ArrayList 或列表。我想知道 StringBuffer 是否适用于整数。
回答by MinecraftShamrock
Arrays in Java have a fixed length that cannot be changed. So Java provides classes that allow you to maintain lists of variable length.
Java 中的数组具有固定长度,无法更改。因此 Java 提供了允许您维护可变长度列表的类。
Generally, there is the List<T>
interface, which represents a list of instances of the class T
. The easiest and most widely used implementation is the ArrayList
. Here is an example:
通常,有List<T>
接口,它表示类的实例列表T
。最简单和最广泛使用的实现是ArrayList
. 下面是一个例子:
List<String> words = new ArrayList<String>();
words.add("Hello");
words.add("World");
words.add("!");
List.add()
simply appends an element to the list and you can get the size of a list using List.size()
.
List.add()
只需将一个元素附加到列表中,您就可以使用List.size()
.
回答by Tunaki
You can not add an element to an array, since arrays, in Java, are fixed-length. However, you could build a new array from the existing one using Arrays.copyOf(array, size)
:
您不能向数组添加元素,因为在 Java 中数组是固定长度的。但是,您可以使用Arrays.copyOf(array, size)
以下命令从现有数组构建一个新数组:
public static void main(String[] args) {
int[] array = new int[] {1, 2, 3};
System.out.println(Arrays.toString(array));
array = Arrays.copyOf(array, array.length + 1); //create new array from old array and allocate one more element
array[array.length - 1] = 4;
System.out.println(Arrays.toString(array));
}
I would still recommend to drop working with an array and use a List
.
我仍然建议放弃使用数组并使用List
.
回答by dcsohl
The OP says, for unknown reasons, "I prefer it without an arraylist or list."
OP 说,出于未知的原因,“我更喜欢它没有数组列表或列表。”
If the type you are referring to is a primitive (you mention integers, but you don't say if you mean int
or Integer
), then you can use one of the NIO Buffer classes like java.nio.IntBuffer
. These act a lot like StringBuffer
does - they act as buffers for a list of the primitive type (buffers exist for all the primitives but not for Objects), and you can wrap a buffer around an array and/or extract an array from a buffer.
如果您所指的类型是原始类型(您提到了整数,但没有说您的意思是int
还是Integer
),那么您可以使用 NIO Buffer 类之一,例如java.nio.IntBuffer
. 它们的作用很像StringBuffer
- 它们充当原始类型列表的缓冲区(缓冲区存在于所有原始类型,但不存在于对象),您可以将缓冲区包裹在数组周围和/或从缓冲区中提取数组。
Note that the javadocs say, "The capacity of a buffer is never negative and never changes." It's still just a wrapper around an array, but one that's nicer to work with. The only way to effectively expand a buffer is to allocate()
a larger one and use put()
to dump the old buffer into the new one.
请注意,javadocs 说,“缓冲区的容量永远不会为负且永远不会改变。” 它仍然只是一个数组的包装器,但它更适合使用。有效扩展缓冲区的唯一方法是扩大缓冲区allocate()
并使用put()
将旧缓冲区转储到新缓冲区中。
If it's not a primitive, you should probably just use List
, or come up with a compelling reason why you can't or won't, and maybe somebody will help you work around it.
如果它不是原始的,您可能应该使用List
,或者想出一个令人信服的理由为什么您不能或不会,也许有人会帮助您解决它。
回答by Durandal
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the endis meaningless (by itself).
为了澄清术语正确:数组是固定长度的结构(并且现有的长度不能改变)末尾的表达式add是没有意义的(本身)。
What you can do is create a new array one element larger and fill in the new element in the last slot:
您可以做的是创建一个大一个元素的新数组,并在最后一个插槽中填充新元素:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
这很快就会变得效率低下,因为每次调用 append 时都会创建一个新数组并复制旧数组内容。
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
显着减少开销的一种方法是创建一个更大的数组并跟踪它实际填充的索引。添加一个元素就像填充下一个索引并增加索引一样简单。如果阵列完全填满,则会创建一个具有更多可用空间的新阵列。
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
猜猜 ArrayList 做了什么:正是如此。所以当需要动态大小的数组时,ArrayList 是一个不错的选择。不要重新发明轮子。
回答by happyHelper
As many others pointed out if you are trying to add a new element at the end of list then something like, array[array.length-1]=x; should do. But this will replace the existing element.
正如许多其他人指出的那样,如果您尝试在列表末尾添加一个新元素,则类似于 array[array.length-1]=x; 应该做。但这将替换现有元素。
For something like continuous addition to the array. You can keep track of the index and go on adding elements till you reach end and have the function that does the addition return you the next index, which in turn will tell you how many more elements can fit in the array.
对于诸如连续添加到数组之类的东西。您可以跟踪索引并继续添加元素,直到到达末尾,并让执行添加的函数返回下一个索引,这反过来会告诉您数组中可以容纳多少元素。
Of course in both the cases the size of array will be predefined. Vector can be your other option since you do not want arraylist, which will allow you all the same features and functions and additionally will take care of incrementing the size.
当然,在这两种情况下,数组的大小都是预先定义的。Vector 可以是您的另一种选择,因为您不需要 arraylist,它允许您使用所有相同的特性和功能,另外还将负责增加大小。
Coming to the part where you want StringBuffer to array. I believe what you are looking for is the getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) method. Look into it that might solve your doubts. Again I would like to point out that after managing to get an array out of it, you can still only replace the last existing element(character in this case).
来到您希望 StringBuffer 排列的部分。我相信您正在寻找的是 getChars(int srcBegin, int srcEnd,char[] dst,int dstBegin) 方法。看看它可能会解决你的疑虑。我想再次指出,在设法从中获取数组后,您仍然只能替换最后一个现有元素(在这种情况下为字符)。
回答by Kaplan
one-liner with streams
单线带溪流
Stream.concat(Arrays.stream( array ), Stream.of( newElement )).toArray();