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

Write a program to sort an ArrayList of Name(ArrayList) into ascending order. Us

ID: 3676613 • Letter: W

Question

Write a program to sort an ArrayList of Name(ArrayList) into ascending order. Use the sort method in the java.util.Collections class to sort the ArrayList of Names. The program should print the ArrayList before sorting and after sorting. Print one Name per line. Test your program. The Name class has two instance fields named last and first. The fields are both of type string and represent the last name and first name respectively. The Name class implements the java.lang.Comparableinterface. Name objects are ordered by last name followed by name. For example, the following code segment prints the string less: The compare To() method compares the last and first fields separately. That is it does not concatenate the last and first fields fields and make the comparison on the concatenated values. The Name class has one constructor. The Name class implements the toString method. The toString method returns the string consisting of the last name, followed the following code segment prints the string Smith,Al.

Explanation / Answer

Program:

// import the required packages
import java.io.*;
import java.util.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
//class Name
public class Name
{
   // Declare the required variables  
   private String lastName;
   private String firstName;
   // constructor
   public Name(String fstnm, String lstnm)
   {              
       lastName = lstnm;
       firstName = fstnm;      
   }

   // method to get the last name
   public String getlastname()
   {
       return lastName;
   }
   // method to return the name
   public String toString()
   {
        return lastName+", "+firstName;
    }

   // main method
   public static void main(String[] args)
   {
       ArrayList<Name> arraylist = new ArrayList<Name>();
       arraylist.add(new Name("Zenet", "Chanya"));
       arraylist.add(new Name("John", "Ramshu"));
       arraylist.add(new Name("Jack", "Smith"));
       arraylist.add(new Name("Al", "Arabt"));
       System.out.println("Before Sorting");
       // loop iteration
       for(Name str: arraylist)
        {
           System.out.println(str);
        }
       // sorting
        Collections.sort(arraylist);
        System.out.println("After Sorting");
        for(Name str: arraylist)
        {
           System.out.println(str);
        }  
   }  
}

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