0

Here, i need to delete several element to be [ Lala , Daniel , Gina , Gio ] which from my point of view is deleting [2] , [3] , [4] but i got [ Lala , Daniel , Rusli , Gina ].

I try to search it, i just got the name of my problem called "Delete multiple element" but i didn't find the answer of my problem.

public static void main(String[] args) {
    List<String> index = new ArrayList<>();
    index.add(0, "Lala");
    index.add(1, "Shani");
    index.add(2, "Gracia");
    index.add(3, "Kyla");
    index.add(4, "Gio");
    
    System.out.println(index);
    
    index.remove(3);
    
    List<String> index2 = new ArrayList<>();
    index.add(3, "Gina");
    System.out.println(index);
    
    List<String> index3 = new ArrayList<>();
    index.add(1, "Daniel");
    index.add(3, "Rusli");
    System.out.println(index);
    
    index.remove(2);
    index.remove(3);
    index.remove(4);

Output:

[Lala, Shani, Gracia, Kyla, Gio]
[Lala, Shani, Gracia, Gina, Gio]
[Lala, Daniel, Shani, Rusli, Gracia, Gina, Gio]
[Lala, Daniel, Rusli, Gina]

The results I want:

[Lala, Shani, Gracia, Kyla, Gio]
[Lala, Shani, Gracia, Gina, Gio]
[Lala, Daniel, Shani, Rusli, Gracia, Gina, Gio]
[Lala, Daniel, Gina, Gio]
Zakhel
  • 31
  • 4
  • 1
    Use `Iterator` to remove elements. When you remove it using an index, the list resizes and the elements after that position shift to left (or in other words, their index value decreases by `1`). – Arvind Kumar Avinash Nov 01 '20 at 20:06
  • 1
    You can store the indexes in an array {2,3,4}. Sort it and then start removing from the last index. So first you will remove the element at 4, then 3, then 2. This way you won't have to worry about the shrinking of the array. Hope it helped! – Aunny Nov 01 '20 at 20:26
  • What, how that is possible? I got my output! Thanks a lot Aunny. – Zakhel Nov 01 '20 at 20:31
  • Thanks to you Arvind, actually i got my result and a new knowladge. But i think my lecture hasn't taught me bout that. – Zakhel Nov 01 '20 at 20:35

0 Answers0