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

1. Write a class called TelDirectory that implements the Comparable interface. T

ID: 3672044 • Letter: 1

Question

1. Write a class called TelDirectory that implements the Comparable interface. The class should contain two fields name (String) and phone number (String). Write the necessary constructors, accessors, mutators and other methods.

2. Write a client class that creates an ArrayList of 10 TelDirectory objects called list1. Print the list. Call Collections.sort(list1), to sort the elements according to the name. If Print the sorted list. the names are the same then sort the list using the phone number.

Explanation / Answer

package com.he.capillary.chegg1;

public class TelDirectory implements Comparable<TelDirectory> {

   private String name;
   private String phonenumber;

   public String getName() {
       return name;
   }

   public void setName(String name) {
       this.name = name;
   }

   public String getPhonenumber() {
       return phonenumber;
   }

   public void setPhonenumber(String phonenumber) {
       this.phonenumber = phonenumber;
   }

   public TelDirectory(String name, String phonenumber) {
       super();
       this.name = name;
       this.phonenumber = phonenumber;
   }

   public int compareTo(TelDirectory o) {
       int result = this.getName().compareTo(o.getName());
       if (result == 0) {
           return this.getPhonenumber().compareTo(o.getPhonenumber());
       }
       return result;
   }

   @Override
   public String toString() {
       return "TelDirectory [name=" + name + ", phonenumber=" + phonenumber + "]";
   }

}

package com.he.capillary.chegg1;

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

public class ClientClass {

   public static void main(String[] args) {
       List<TelDirectory> list = new ArrayList<TelDirectory>();
       list.add(new TelDirectory("A", "111111"));
       list.add(new TelDirectory("B", "111111"));
       list.add(new TelDirectory("C", "111111"));
       list.add(new TelDirectory("D", "111111"));
       list.add(new TelDirectory("E", "111111"));
       list.add(new TelDirectory("F", "111111"));
       list.add(new TelDirectory("G", "111111"));
       list.add(new TelDirectory("H", "111111"));
       list.add(new TelDirectory("I", "111111"));
       list.add(new TelDirectory("A", "3333"));
      
       System.out.println(list);
       Collections.sort(list);
       System.out.println(list);
   }
}


Let me know the sorting order if you want other one.

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