Rushdi Shams
Rushdi Shams

Reputation: 2423

Manipulating Generics through auto/unboxing

public class Generics {

    public static <T> T increaseBalance (T amount){
        //say I want to increase the amount here, put it into finalBalance and return
        return finalBalance;
    }

    public static void main(String[] args){
        System.out.println(increaseBalance (new Integer(10)));
        System.out.println(increaseBalance (new Double(20)));
    }

}

Hi. I am just into Generics and auto/unboxing. In this simple code segment, I am trying to send two different objects to increaseBalance(T amount) method and would like to increase the amount by 10 and return the final balance. How can this be achieved? It would make my understanding of generics and auto/unboxing clearer. Thanks a lot.

Upvotes: 0

Views: 139

Answers (1)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

Unfortunately, there's no easy way to apply the + operator to a Generic type T.

You have two options:

  • Overloading

or

  • Checking the type and casting to a specific boxed type

If you pick to overloading, you can implement two methods, both for each of the possible parameter types.

public static Integer increaseBalance (Integer amount){
    return amount + 10;
}

public static Double increaseBalance (Double amount){
    return amount + 10;
}

If you want to stick to the generic method, you will have to check the parameter type and then do a cast.

public static <T extends Number> Number increaseBalance (T amount){
    Number result = null;
    if (amount instanceof Integer) {
        result = new Integer((Integer) amount + 10);
    } else if (amount instanceof Double) {
        result = new Double((Double) amount + 10);
    } else {
        //do nothing
    }
    return result;
}

Upvotes: 4

Related Questions