Thursday, 24 August 2017

CREATING AN ARRAY LIST TO STORE ONLY STRINGS IN JAVA


/*Program to Create an ArrayList which will be able to store only Strings */

package ListPackage;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Eg2 {
public void printAll() /* Function to print the data */
{
Scanner ip = new Scanner(System.in);
ArrayList<String> al = new ArrayList<String>(); /* Creating an ArrayList */
System.out.println("Enter the number of datas to be entered:\n");
int num = ip.nextInt();
for (int i = 0; i < num; i++) {
String s = ip.next();
al.add(s);
}
System.out.println("\nThe entered strings are:\n");
Iterator<String> i = al.iterator();

 /* Iterator to iterate & display the array list contents */
while (i.hasNext()) {
System.out.println(i.next());
}
}
public static void main(String a[]) {
Eg2 obj = new Eg2();/* Instantiating the class */
obj.printAll();
}

}

No comments:

Post a Comment