mardi 30 octobre 2018

Is there a way to only use a recursive type bound field given a condition?

I'm new to Java and coming from Python, so I don't have a great grasp of generics, but I am trying to make a general Parameter class that contains a value field, which can be an int, float, string or an array of one of the previous types:

public class Parameter<T> {
    private final String name;
    ...
    private final Utils.Range<T> range;
    private final RANGE_TYPE range_type;
    private final T value;

    public enum RANGE_TYPE {CONTINUOUS, DISCREET};
    ...

    /* constructor / builder class etc */
    ...
}

It also has to have a range, which I have implemented as follows:

public class Utils {
    /**
     * Collection of helper classes
     */
    public static class Range<T extends Comparable<T>> {
        /**
         * Generic Inclusive Range (designed for int / float / double).
         */
        private final T start;
        private final T end;

        public Range(T start, T end) {
            this.start = start;
            this.end = end;
        }

        public boolean contains(T number) {
            return (number.compareTo(start) > 0 && number.compareTo(end) < 0);
        }

    }
}

However, the generic types between the range field in Parameter class and the Range class itself are incompatible. Am I coming at this from the wrong direction? In python I would implement this as a dict and not worry too much about the types of the values.

Aucun commentaire:

Enregistrer un commentaire