java 8 - Using generics to share a common method with multiple arguments -
i finding have method able accept 2 types of list<> objects. example:
public void foo(long id) {};
the above function called on multiple objects each of whom have either id of type long or integer. what's happening objects have id defined long, method call works fine:
class bar {long id} bar test = new bar(1l); foo(bar.id);
but objects have integer id, have first convert integer long before using foo. can of course have new method takes in integer id rather not that. way generics?
no. can't define type "or" of 2 types.
however, can accept number
, includes both long
, integer
types, , use longvalue()
method:
public void foo(number number) { long id = number.longvalue(); // rest of code stays same }
Comments
Post a Comment