Write a java program to accept names of ‘n’ cities, insert same into array list collection and display the contents of same array list, also remove all these elements.
Here's a Java program that accepts names of 'n' cities from the user, inserts them into an ArrayList, displays the contents of the ArrayList, and then removes all the elements from it:
import java.util.ArrayList;
import java.util.Scanner;
public class CityArrayList {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<string> cities = new ArrayList<>();
// Accept names of n cities from the user and insert them into the ArrayList
System.out.print("Enter the number of cities: ");
int n = scanner.nextInt();
System.out.println("Enter the names of the cities:");
for (int i = 0; i < n; i++) {
String city = scanner.next();
cities.add(city);
}
// Display the contents of the ArrayList
System.out.println("The cities in the ArrayList are:");
for (String city : cities) {
System.out.println(city);
}
// Remove all the elements from the ArrayList
cities.clear();
// Display the contents of the ArrayList after removing all elements
System.out.println("The ArrayList after removing all elements:");
System.out.println(cities);
}
}
The program first accepts the number of cities 'n' from the user and then accepts the names of the 'n' cities and inserts them into an ArrayList named cities
. It then displays the contents of the ArrayList using a for-each loop. Finally, it removes all the elements from the ArrayList using the clear
method and displays the contents of the ArrayList after removing all elements.- Java ArrayList
- Inserting elements in ArrayList
- Removing elements from ArrayList
- Java Scanner class
- Java for-each loop
- Java clear method