Create an ArrayList of Employees (contain id and name) and add 3 Employees to the ArrayList to start. Next, you want to sort these Employees by their name using Collections.sort. Refer back to ch 4 and lab 2 part 2 to use comparator and Collections.sort. In order to avoid affecting the original list and employees, clone the ArrayList before using the sort method. To make a deep copy of the ArrayList, implement the clone method of Employee and use it to create a new ArrayList of employees.

Respuesta :

Answer:

Kindly note that, you're to replace "at" with shift 2 as the brainly text editor can't accept the symbol

Explanation:

Java code:

import java.util.*; public class Employees { // variables private int id; private String name; // getters public String getName() { return name; } public int getId() { return id; } // constructor public Employees(int id, String name) { this.id = id; this.name = name; } // comparator function based on the name static class compareByName implements Comparator<Employees> { "at"Override public int compare(Employees emp1, Employees emp2) { return emp1.getName().compareTo(emp2.getName()); } } // clone method for arraylist public static ArrayList<Employees> clone(ArrayList<Employees> arr) { ArrayList<Employees> temp = new ArrayList<Employees>(); for(int i=0;i<arr.size();i++) temp.add(arr.get(i)); return temp; } // main method public static void main(String[] args) { Scanner scan = new Scanner(System. in); // reading 3 employees details ArrayList<Employees> arr = new ArrayList<Employees>(); for(int i=0;i<3;i++) { System.out.print("Enter id: "); int id = scan. nextInt(); System.out.print("Enter name: "); scan. nextLine(); String name = scan. nextLine(); arr.add(new Employees(id,name)); } // cloning and sorting ArrayList<Employees> cloneArray = clone(arr); Collections. sort(arr, new compareByName()); // printing System. out. println("Array after cloning: "); for(int i=0;i<cloneArray. size();i++) { System.out.println(cloneArray. get(i). getId() + " " + cloneArray. get(i).getName()); } System. out. println("Array after sorting: "); for(int i=0;i<arr.size();i++) { System. out. println(arr.get(i). getId() + " " + arr.get(i). getName()); } } }  

Kindly check the attached images below for the code screenshot and code output.

Ver imagen temmydbrain
Ver imagen temmydbrain
Ver imagen temmydbrain
Ver imagen temmydbrain