Sobes.tech
Senior

Implement your own enum type as if before the modern enum in Java 1.5. It should implement the contract of a modern Java enum: • easy to get any enum value • safe comparison of values by reference (==) • each value has a string name matching the value name • each value has an integer `ordinal` identifier containing its declaration order • can get a list of all enum values • can get a value by its `ordinal` • can get a value by its name For example, you can take a list of currencies. It is important that the list is potentially extendable, because the quality of the code will determine how smoothly it will be in the future to add values to the enum. class Currency { // TODO } --- Given the user_orders table |ts|user_id|order_value| Return the sum of the first purchase for each user.

sobes.tech AI

Answer from AI

Before the appearance of enum in Java 1.5, a comparable type could be implemented using a class and static constants. Here is an example implementation of the Currency class that meets the specified requirements:

import java.util.*;

public class Currency {
    private static final List<Currency> VALUES = new ArrayList<>();
    private final String name;
    private final int ordinal;

    // Private constructor
    private Currency(String name) {
        this.name = name;
        this.ordinal = VALUES.size();
        VALUES.add(this);
    }

    // Define values
    public static final Currency USD = new Currency("USD");
    public static final Currency EUR = new Currency("EUR");
    public static final Currency GBP = new Currency("GBP");

    // Get name
    public String name() {
        return name;
    }

    // Get ordinal
    public int ordinal() {
        return ordinal;
    }

    // Get all values
    public static Currency[] values() {
        return VALUES.toArray(new Currency[0]);
    }

    // Get by name
    public static Currency valueOf(String name) {
        for (Currency c : VALUES) {
            if (c.name.equals(name)) {
                return c;
            }
        }
        throw new IllegalArgumentException("No enum constant Currency." + name);
    }

    @Override
    public String toString() {
        return name;
    }
}

This class:

  • Stores all values in the list VALUES.
  • Assigns a unique ordinal to each value based on creation order.
  • Allows retrieving all values via the values() method.
  • Allows retrieving a value by name via valueOf(String).
  • Comparison by reference works because all values are static constants.

For an SQL query to get the sum of the first purchase for each user from the user_orders table:

SELECT user_id, SUM(order_value) AS first_order_sum
FROM user_orders uo1
WHERE ts = (
    SELECT MIN(ts) FROM user_orders uo2 WHERE uo2.user_id = uo1.user_id
)
GROUP BY user_id;

This query finds the minimum purchase date for each user and sums the order values made at that time (if multiple orders at the same time).