Home > database >  How to clear only one index from ArrayList in java?
How to clear only one index from ArrayList in java?

Time:08-17

I tried to remove only "Nokia" from ArrayList how to do it? But the rest should be printed!

package arraylisthashmaphashlist;

import java.util.ArrayList;

public class Arraylisthashmaphashlist {
    

    public static void main(String[] args) {

    ArrayList <String> mobiles = new ArrayList<String>();
    
    mobiles.add("Nokia");
    mobiles.add("Apple");
    mobiles.add("Samsung");
    mobiles.add("Oppo");
    System.out.println(mobiles);
    
    mobiles.clear();
    System.out.println(mobiles);

CodePudding user response:

mobiles.remove("Nokia")

or you can do mobiles.remove(mobiles.indexOf("Nokia")), which will find the index of the first element equal to "Nokia" in your list, and then pass that to the remove function which can either remove an Object by index or by the Object itself.

CodePudding user response:

Add:

mobiles.remove("Nokia");

To your code before mobiles.clear();.

  • Related