Question

In: Computer Science

In Java class PassengerComparator implements Comparator for a Passenger Implement a comparator where a FirstClassPassenger precedes...

In Java

class PassengerComparator implements Comparator for a Passenger

Implement a comparator where a FirstClassPassenger precedes a CoachPassenger,. If both Passengers are of the same TicketClass then the Passenger with the lower TicketNumber precedes the Passenger with the higher TicketNumber.

Solutions

Expert Solution

Hello,

I have developed PassengerComparator class based on your requirement. Attached PassengerComparator class. And also I have created Passenger and PassengerComparatorTester class to test PassengerComparator class. Passenger and PassengerComparatorTester classes are purely based on my assumption as there is no specification provided in your requirement. Attaching Passenger and PassengerComparatorTester classes as well. Please let me know if any changes required.

PassengerComparator.java:

import java.util.Comparator;

// PassengerComparator class that implements Comparator interface with type Passenger
public class PassengerComparator implements Comparator<Passenger>{

        // compare method implementation
        @Override
        public int compare(Passenger p1, Passenger p2) {
                // Verify class type of two passengers. 
                // If any person has class type First and other passenger has class type Coach then return -1 that denotes passenger with class type First come before other passenger
                if(p1.getClassType().equals("First") && p2.getClassType().equals("Coach")) {
                        return -1;
                } else if(p1.getClassType().equals("Coach") && p2.getClassType().equals("First")) {
                        // If any person has class type Coach and other passenger has class type First then return 1 that denotes passenger with class type Coach come after other passenger
                        return 1;
                } else if(p1.getClassType().equals(p2.getClassType())) {
                        // If both passengers class type is same
                        // Then return -1 if p1 ticket number is lower than p2 ticket number else return 1
                        return p1.getTicketNumber() < p2.getTicketNumber() ? -1 : 1;
                }
                return 0;
        }

}

Output:

Passenger.java:

public class Passenger {
        // Class fields
        private String fullName;
        private String classType;
        private int ticketNumber;
        
        // Parameterized constructor with all fields
        public Passenger(String fullName, String classType, int ticketNumber) {
                this.fullName = fullName;
                this.classType = classType;
                this.ticketNumber = ticketNumber;
        }
        
        // Getters and Setters for all fields
        public String getFullName() {
                return fullName;
        }
        public void setFullName(String fullName) {
                this.fullName = fullName;
        }
        public String getClassType() {
                return classType;
        }
        public void setClassType(String classType) {
                this.classType = classType;
        }
        public int getTicketNumber() {
                return ticketNumber;
        }
        public void setTicketNumber(int ticketNumber) {
                this.ticketNumber = ticketNumber;
        }
        
        // toString method
        @Override
        public String toString() {
                return "Passenger [fullName=" + fullName + ", classType=" + classType + ", ticketNumber=" + ticketNumber + "]";
        }
        
}

PassengerComparatorTester.java:

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

// PassengerComparatorTester class to test PassengerComparator class
public class PassengerComparatorTester {

        public static void main(String[] args) {
                // Created 6 Passenger objects using parameterized constructor of Passenger class
                Passenger passenger1 = new Passenger("John Doe", "Coach", 12345878);
                Passenger passenger2 = new Passenger("Michael Misha", "First", 12457893);
                Passenger passenger3 = new Passenger("Rich Cohen", "First", 1245);
                Passenger passenger4 = new Passenger("Dennis Lee", "Coach", 1245879);
                Passenger passenger5 = new Passenger("Robert Key", "Coach", 124);
                Passenger passenger6 = new Passenger("Lewis Jerry", "First", 145785);
                
                // Created new ArrayList of type Passenger
                List<Passenger> passengersList = new ArrayList<Passenger>();
                // Add all 6 passenger objects to the list
                passengersList.add(passenger1);
                passengersList.add(passenger2);
                passengersList.add(passenger3);
                passengersList.add(passenger4);
                passengersList.add(passenger5);
                passengersList.add(passenger6);
                
                System.out.println("**************************************************************************");
                System.out.println("Before Sorting");
                System.out.println("**************************************************************************");
                // Before sorting, printing all passengers by using for each loop
                for (Passenger passenger : passengersList) {
                        System.out.println(passenger);
                }
                
                
                // Call sort method in Collections interface with PassengerComparator
                Collections.sort(passengersList, new PassengerComparator());
                
                System.out.println("**************************************************************************");
                System.out.println("After Sorting");
                System.out.println("**************************************************************************");
                // After sorting, printing all passengers by using for each loop
                for (Passenger passenger : passengersList) {
                        System.out.println(passenger);
                }

        }

}

Related Solutions

JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of       ...
JAVA * create Q3 class to implement comparator for a TreeSet. The purpose of        * the comparator is to compare the alphabetic order of integers. With Q3,        * the order of Integer elements will be sort according to the order of        * digit Unicode.        * For example, the value of {11,3,31,2} will return {11,2,3,31}        * NOTE: You don't need to compare each digit one by one. Just compare them System.out.println("Q3...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement...
In java design and code a class named comparableTriangle that extends Triangle and implements Comparable. Implement the compareTo method to compare the triangles on the basis of similarity. Draw the UML diagram for your classes. Write a Driver class (class which instantiates the comparableTriangle objects) to determine if two instances of ComparableTriangle objects are similar (sample output below). It should prompt the user to enter the 3 sides of each triangle and then display whether or not the are similar...
4) Define an abstract class Name Java class that implements interface Comparable   
4) Define an abstract class Name Java class that implements interface Comparable   
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is...
Language: Java Design and implement a program that implements an Interpolation Search method. Interpolation search is similar to binary search, except it tries to begin the search nearer to the location of the item. Instead of the using the middle value of the sorted array, interpolation search estimates the location of the target with respect to the first & last values in the array. The implementation is the same as binary search except that you should calculate the mid value...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for...
Use Java programming to implement the following: Implement the following methods in the UnorderedList class for managing a singly linked list that cannot contain duplicates. Default constructor Create an empty list i.e., head is null. boolean insert(int data) Insert the given data into the end of the list. If the insertion is successful, the function returns true; otherwise, returns false. boolean delete(int data) Delete the node that contains the given data from the list. If the deletion is successful, the...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with...
In Java: Job class The Job implements the Comparable interface A Job object is instantiated with three int variables, indicating the arrivalTime, the timeForTheJob, and the priority. When the Job is created it is given the next sequential ID starting from 1. (You should use a static variable to keep track of where you are in ID assignment.) There are also int variables for startTime, waitTime (in queue) and endTime for the Job. The following methods are required: getID, set...
Java the goal is to create a list class that uses an array to implement the...
Java the goal is to create a list class that uses an array to implement the interface below. I'm having trouble figuring out the remove(T element) and set(int index, T element). I haven't added any custom methods other than a simple expand method that doubles the size by 2. I would prefer it if you did not use any other custom methods. Please use Java Generics, Thank you. import java.util.*; /** * Interface for an Iterable, Indexed, Unsorted List ADT....
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song...
Write a Java program that implements a song database. The SongsDatabase class keeps tracks of song titles by classifying them according to genre (e.g., Pop, Rock, etc.). The class uses a HashMap to map a genre with a set of songs that belong to such a genre. The set of songs will be represented using a HashSet. Your driver output should sufficiently prove that your code properly implements the code below. public class SongsDatabase { private Map<String, Set<String>> genreMap =...
Write a Java application that implements the following: Create an abstract class called GameTester. The GameTester...
Write a Java application that implements the following: Create an abstract class called GameTester. The GameTester class includes a name for the game tester and a boolean value representing the status (full-time, part-time). Include an abstract method to determine the salary, with full-time game testers getting a base salary of $3000 and part-time game testers getting $20 per hour. Create two subclasses called FullTimeGameTester, PartTimeGameTester. Create a console application that demonstrates how to create objects of both subclasses. Allow the...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT