简体   繁体   English

如何在Java中从数组添加/删除项目?

[英]How can I add/remove an item from an array in Java?

What method can I use in adding or removing an element from my array. 在数组中添加或删除元素时可以使用哪种方法。 Is there a method for this? 有办法吗? Plus, one that resizes the array automatically in cases when an element is deleted to prevent the default "0" from occupying that space. 另外,在删除元素时可以自动调整数组大小的数组,以防止默认的“ 0”占用该空间。

You don't have those methods for arrays but you can use ArrayList instead. 您没有用于数组的那些方法,但可以改用ArrayList Code example: 代码示例:

List<String> list = new ArrayList<>();
list.add("str 1");
list.add("str 2");
list.add(0,"str 3"); // Add 3 on position 0
list.remove(1); // remove item on position 1
list.remove("str 2"); // remove first occurrence of str 2

But you can't use primitive type directly as in arrays, if you want ArrayList of int then you will use Integer class which acts as wrapper for primitive type - List<Integer> list = new ArrayList<>(); 但是您不能像在数组中那样直接使用基本类型,如果要使用int的ArrayList ,则将使用Integer类,该类充当基本类型的包装器-List List<Integer> list = new ArrayList<>();

So you can't perform all the actions that you mentioned above using arrays. 因此,您不能使用数组执行上面提到的所有操作。

You might look into using ArrayList class in java. 您可能会研究在Java中使用ArrayList类。 It has in built remove libraries as well. 它还具有内置的删除库。

Check this link out - https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int) 检查此链接-https: //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#remove(int)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM