Home > Software engineering >  How to declare the variables which are of date type and to sort based on the date?
How to declare the variables which are of date type and to sort based on the date?

Time:04-10

I have the transaction class where I have variables like Arrival date, departure date, I am not sure how to define the date data types, so that transaction info must be sorted on basis of start date. I want to give the date in an explicit manner to the class. For example, I want to give 5 dates and sort them. Can you please let me know, how to do that.

public class Transaction implements Comparable<Transaction> 
{
    private Dog dogID;
    private Date startDate;
    private Date departureDate;
    private List<Integer> serviceLevel = Arrays.asList(1,2,3);
    private List<Integer> ratePerDay = Arrays.asList(89,129,149);
    private double totalcharge;
    private double deposit; 
}

CodePudding user response:

tl;dr

Use only java.time classes, never legacy Date class.

Implement the one method required by Comparable interface.

@Override
public int compareTo( Transaction other )
{
    return this.startDate().compareTo( other.startDate()
}

Details

Both Date classes included with Java are terrible, badly designed by people who did not understand date-time handling.

If you want a date only, without time of day, and without the context of a time zone or offset-from-UTC, use java.time.LocalDate.

private LocalDate startDate;
private LocalDate departureDate;

If the main purpose of your class is to communicate data transparently and immutably, define the class as a record. The compiler implicitly creates the constructor, getters, equals & hashCode, and toString.

And never use a floating-point type like double where accuracy matters such as moment. Use BigDecimal where accuracy trumps speed.

A list should generally be named in the plural, for clarity.

The Java naming convention is camelCase. So totalCharge.

public record Transaction
(
    Dog dogID , 
    LocalDate startDate , 
    LocalDate departureDate , 
    List<Integer> serviceLevels , 
    List<BigDecimal> ratesPerDay , 
    BigDecimal totalCharge , 
    BigDecimal deposit
) {}

If you want to usually sort by the start date member field, implement the Comparable interface with its one required method, compareTo. We implement that method by calling upon the compareTo method built into the LocalDate class.

public record Transaction implements Comparable < Transaction > 
(
    Dog dogID , 
    LocalDate startDate , 
    LocalDate departureDate , 
    List<Integer> serviceLevels , 
    List<BigDecimal> ratesPerDay , 
    BigDecimal totalCharge , 
    BigDecimal deposit
) 
{
    @Override
    public int compareTo( Transaction other )
    {
        return this.startDate().compareTo( other.startDate()
    }

}
  • Related