Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a CitySortDemo class that populates an ArrayList with cities and then sort

ID: 3558127 • Letter: W

Question

Write a CitySortDemo class that populates an ArrayList with cities and then sorts it. (Remember that you can use Collections.sort to sort an array list.) Your answer should be a single-class (executable) project.

Your program should add 10 cities to the arraylist in no particular order, sort the arraylist, then loop through every item in the arraylist and display it to the user as output on the screen. No direct user interaction is required.

You should use a "for" loop to display all cities in the arraylist after it's been sorted.

Explanation / Answer

Here is the solution

import java.util.ArrayList;
import java.util.Collections;

public class ar_list {
   public static void main(String[] args) {
       // TODO Auto-generated method stub
       // creating the array list
       ArrayList<String> list = new ArrayList<String>();

       // adding the city names to the list
       list.add("new york");
       list.add("melbourne");
       list.add("delhi");
       list.add("mumbai");
       list.add("pune");
       list.add("kolkata");
       list.add("jaipur");
       list.add("california");
       list.add("ohio");
       list.add("masachussetts");

       // sorting the arraylist
       Collections.sort(list);

       // displaying the list
       for (int i = 0; i < list.size(); i++) {
           System.out.println(list.get(i));
       }
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote