Search code examples
javagenericsgeneric-method

Java - Generics; Is it usefull to parameterize a method if you want to swap 2 Items of an object?


The following code alows to swap 2 Items of an Object :

public class Box<F, S> {
    F first;
    S second;   

    //Method to swap
    public static <F> void swapItems(Box<F,F> box){

        F temp = box.first;
        box.first = box.second;
        box.second = temp;
    }
}

//The method could also be implemented like this:

    void swapItems() {

        F tmp1 = first;
        S tmp2 = second;
        first = (F) tmp2;
        second = (S) tmp1;
    }

What is the advantage of the generic code? I just don't get it. Could sombody explain this to me? Might the generic one be useful if i call this method on 2 objects?


Solution

  • Your example class is in fact a good example of bad use of generics. A generic Box used to swap items is founded on a misconception.

    Might the generic one be useful if i call this method on 2 objects?

    That's right (with the code in the question). Generics aren't designed for code reuse or for structuring code. We have methods, packages, and modules for that.

    A box of two items that supports swapping order, may be implemented better as follows (although a better-suited name would be Pair, I believe):

    class Box<T> {
        private T first;
        private T second;   
    
        //2-parameter constructor
    
        public void swapItems(){
    
            T temp = first;
            first = second;
            second = temp;
        }
    
        //getters and setters
    }
    

    The above class could be used as follows:

    Box<String> stringBox = new Box<>("first", "second");
    String first = stringBox.getFirst();
    String second = stringBox.getSecond();
    

    Or as follows:

    Box<Integer> intBox = new Box<>(1, 2);
    int first = intBox.getFirst();
    int second = intBox.getSecond();
    

    What is the advantage of the generic code?

    Assuming you had a class as the one above, then generics would allow you to make a box of different types <T>, with type-safety guaranteed by the compiler, just as shown in the two example uses: the Box class is defined once, but used with "box items" of different types, of which the compiler is aware and for which it helps validate types.

    For example, the following incorrect calls would fail (continuing examples above):

    String third = intBox.getFirst();
    

    This last (incorrect) statement will fail at compile time, thus enabling faster feedback (as opposed to class cast exceptions at runtime).

    Other important notes:

    • Your class declares two distinct type parameters, <F, S>, so you cannot "swap" first and second. The compiler would reject the code as the two types aren't guaranteed to be compatible.