1

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.

Luke Ndatigh
  • 91
  • 1
  • 3
  • 7
  • 3
    Arrays are immutable, so you will have to do the resizing yourself. True deletion also won't be possible without manual resizing. Have you considered using an `ArrayList`? – Logan May 26 '17 at 16:30
  • 1
    Tried using some search engine? – GhostCat May 26 '17 at 16:32

2 Answers2

3

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<>();

FilipRistic
  • 2,661
  • 4
  • 22
  • 31
  • 1
    Thanks for pointing out, didn't want to say it that way, I meant that there are not such methods that OP asked for. – FilipRistic May 26 '17 at 17:38
1

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)

zenwraight
  • 2,002
  • 1
  • 10
  • 14