Static polymorphism with generics in Java -
i hoping create clean code can recursively dig collection , print first integer finds. coming c++ background approach looked this:
class test { static void print(integer i) { system.out.println(i); } static <t> void print(arraylist<t> arr) { t entry= arr.at(0); test.print (entry); } static void test() { arraylist<arraylist<integer>> arrayofarrayofint= create(); print( arrayofarrayofint ); } }
unfortunately doesn't work.
one alternative give on static polymorphism , create function print(object o) , number of instanceof checks branch right behavior. way can done due java's type erasure or there more elegant approach?
the following method recursively dig object
, return optional
containing first integer
finds, or optional.empty()
if can't find one.
static optional<integer> firstint(object o) { if (o instanceof integer) return optional.of((integer) o); if (o instanceof int[]) { int[] array = (int[]) o; return array.length > 0 ? optional.of(array[0]) : optional.empty(); } if (o instanceof object[]) return firstint(arrays.aslist((object[]) o)); if (o instanceof iterable) { (object o2 : (iterable<?>) o) { optional<integer> result = firstint(o2); if (result.ispresent()) return result; } } return optional.empty(); }
you can using polymorphism, have create interface searchable
this
interface searchable { optional<integer> search(); }
and create wrapper classes concrete types want able search. example:
public final class searchablelist<t extends searchable> extends abstractlist<t> implements searchable { private final list<t> list; searchablelist(list<t> list) { this.list = list; } // rest omitted }
however, such convoluted mess, , avoid it, preferring instanceof
checks instead.
Comments
Post a Comment