Java List remove element using ListIterator

Description

Java List remove element using ListIterator

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;

public class Main {
  public static void main(String[] args) {
    List<String> aList = new ArrayList<String>();

    aList.add("CSS");
    aList.add("Java");
    aList.add("HTML");
    aList.add("Javascript");
    aList.add("C++");

    // Get an object of ListIterator using listIterator() method

    ListIterator<String> listIterator = aList.listIterator();
    listIterator.next();//from w w w  .  j a  v a  2s  .c  om
    listIterator.next();

    // remove element returned by last next method

    listIterator.remove();
    for (String str: aList){
      System.out.println(str);
    }
  }
}
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class Main {
  public static void main(String args[]) {
    List<String> langList = new ArrayList<>();
    langList.add("CSS");
    langList.add("Java");
    langList.add("Javascript");
    langList.add("SQL");
    langList.add("C++");
    langList.add("HTML");

    ListIterator<String> lit = langList.listIterator();
    /*from   ww w .  ja  v a2  s. c o m*/
    System.out.println(lit.next());
    System.out.println(lit.next());
    String s = (String) lit.next();
    System.out.println(s);
    lit.remove();
    System.out.println(lit.next());
    System.out.println(lit.next());
    
    lit.add(s);
    System.out.println(lit.next());// Gets back just added
    System.out.println(lit.previous());
    System.out.println(lit.previous());
    
    s = (String) lit.previous();
    lit.remove();
    System.out.println(lit.next());
    System.out.println(lit.next());
    lit.add(s);

  }
}



PreviousNext

Related