Thursday, March 5, 2009

ArrayList & Iterator

/* Programmer: Maribelle Lacno
* Program name: myList
* Subject: IT134_Computer Programming 3
* Instructor: Mr. Dony Dongiapon
* Date Started: 03/03/09
* Date Finished: 03/04/09
* Purpose: To create a program that will understand the concept of ArrayList and iterator.
*/

import java.util.*;

public class myList{

public static void main(String[] args){
boolean quit = true;
System.out.print("\na. add new data to the list.");
System.out.print("\nb.remove data from the list.");
System.out.print("\nc. view the content of the list.");

Scanner scan=new Scanner(System.in);
ArrayList list= new ArrayList();
do{
System.out.print("\nWhat do you want to do? ");
String choice=scan.next();
char c=choice.charAt(0);
if(c=='a'){
System.out.print("\nYou choose to add a new data.");
System.out.print("\nEnter the data: ");
String data = scan.nextLine();
list.add(data);
System.out.print("\nSize of list after adding data: " + list.size());
}else if(c=='b'){
System.out.print("\nYou choose to remove a data.");
System.out.print("\nEnter the data: ");
String index = scan.nextLine();
list.remove(index);
System.out.print("\nSize of list after deleting data: " + list.size());
}else if(c=='c'){
System.out.print("\nYou choose to view the list.");
System.out.print("\nMy List of classmates: ");
Iterator classmate= list.iterator();
while (classmate.hasNext()){
String content= classmate.next();
System.out.print("\n"+content);
}
ListIterator listClassmate= list.listIterator();
while (listClassmate.hasNext()){
String content= listClassmate.next();
listClassmate.set("\n"+content);
}
}else if(c=='q'||c=='Q'){
System.exit(0);
}else{
System.out.print("\nInvalid choice.\nPlease try again.");
}
}while(quit);
}
}


Things I learned in this exercise:

  • ArrayList implementation is like the concept of Linkedlist.
  • the iterator is used to access and manipulate the operation of the ArrayList.
  • ArrayList class has many methods like add(), remove(), set(), and size().
  • to use the ArrayList and iterator or ListIterator, we must import the java.util package.

No comments:

Post a Comment