简体   繁体   中英

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.

You don't have those methods for arrays but you can use ArrayList instead. 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<>();

So you can't perform all the actions that you mentioned above using arrays.

You might look into using ArrayList class in java. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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