Search code examples
javagenericsjavafxgeneric-programming

Passing a double to a method that accepts T


Question

I am trying to pass a double to a method that accepts T. That method (In this case. I plan to add the cases for String, int, etc.) requires the item passed to be a double or else it will throw an error.

Basically, I want to pass a double to commitEdit(T).

Background

I understand I am being very vague so I'll try to elaborate. I am attempting to create a class that extends TableCell<S,T> such that I can use it generically. I have no experience with <S,T> parameters. The method I am trying to call is commitEdit(T) which up until now I have been creating a new class that extends TableCell<CustomRowObject, Double> and everything has been working fine because commitEdit(Double) is easy enough to call.

The problem is that every time I want to make a new table, I have to make a new cell class and I would rather create a generic cell that handles the casting of the value from an Object to Double, String, Integer, etc, and passes it to commitEdit(T).

In all my years of programming i have always tried to avoid generic arguments but now I believe it is a good time to learn.

Code

Here's an example of the wrapper for commitEdit(T) that I've come up with so far(Doesnt work)

    public static class EditingCell<S, T> extends TableCell<S, T> {

        public EditingCell() {
        }

        public void commit(Object val) {
            if(val instanceof Double) {
                commitEdit((Double) val);
            } else if(val instanceof String) {
                commitEdit((String) val);
            }
        }
    }

The method commitEdit(T) in the type TableCell<S,T> is not applicable for the arguments (double)

Im Dumb

As in this specific case, all I had to do was cast to T as such commitEdit( (T) val).


Solution

  • This works:

    @Test
    public void testDoubleGeneric()
    {
        commitEdit(3.1514D);
    }
    
    private <T> void commitEdit(final T value)
    {
        if (!(value instanceof Double))
        {
            throw new IllegalArgumentException();
        }
    }
    

    However I'd argue, that your approach to use generics is not the right approach for your problem. Whenever you have to use instanceof, generics are not the solution. Consider method overloading instead.

    public void commit(Double d) ...
    
    public void commit(String str) ...