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

Create a class called Person2 that is identical to the Person class in the previ

ID: 3769203 • Letter: C

Question

Create a class called Person2 that is identical to the Person class in the previous problem except have it implement the Comparable interface and implement the required methods from the Comparable interface. Your compareTo method should compare by birth year.

Create a class called Student2 that inherits from Person2. It should otherwise be the same as the Student class from the previous example.

Write a tester class (Person2Tester) that populates an ArrayList of Student2 objects and then sorts them by year of birth using the Collections sort method.

Explanation / Answer

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

class Person2 implements Comparable{  
   String name;
   BirthDate bdate;
  
   public Person2(String name,BirthDate bdate){
       this.name=name;
       this.bdate = bdate;
   }

   @Override
   public int compareTo(Object obj){
       Person2 st=(Person2)obj;
   if(this.bdate.year==st.bdate.year)
       return 0;
   else if(this.bdate.year > st.bdate.year)
       return 1;
   else
       return -1;
   }

}
class BirthDate{
   int day;
   int month;
   int year;
   public BirthDate(int day,int month,int year){
       this.day = day;
       this.month = month;
       this.year = year;
   }
}

class PersonTester2{
   public static void main(String[] args) {
       List list = new ArrayList();
       list.add(new Person2("Pk", new BirthDate(1, 2, 1991)));
       list.add(new Person2("Me", new BirthDate(1, 2, 1999)));
       list.add(new Person2("Cd", new BirthDate(1, 2, 1995)));
       list.add(new Person2("Nm", new BirthDate(1, 2, 1992)));
       list.add(new Person2("Al", new BirthDate(1, 2, 1993)));
       list.add(new Person2("Pe", new BirthDate(1, 2, 1998)));
       list.add(new Person2("Zs", new BirthDate(1, 2, 1994)));
       for(Object o : list){
           Person2 p = (Person2)o;
           System.out.print(p.name+" ");
       }
       System.out.println();
       Collections.sort(list);
       for(Object o : list){
           Person2 p = (Person2)o;
           System.out.print(p.name+" ");
       }
   }
}

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