How to properly cast when using generics in java methods? -



How to properly cast when using generics in java methods? -

i have assignment implement own version of collections.fill() , collections.reverse(). algorithms simple enough, i'm getting little bit lost in generics involved, when need casting.

my original thought like:

public static void reverse(list<?> a_list) { int list_size = a_list.size(); listiterator<?> left_to_right = a_list.listiterator(); listiterator<?> right_to_left = a_list.listiterator(list_size); ? temp_variable; // ..doing stuff right_to_left.set(temp_variable); }

but of course of study can't declare temp type "?". declaring "object temp_variable" makes sense, phone call set(temp_variable) @ end won't work (since listiterator won't take object -- because list not type list<object>).

it makes sense me, declare temp object, , cast listiterators:

listiterator<object> left_to_right = (listiterator<object>) a_list.listiterator(); listiterator<object> right_to_left = (listiterator<object>) a_list.listiterator(list_size);

the compiler gives me unchecked cast warnings when this, can't think of how break, given implementation. there danger in doing this?

then in collections.fill(), wanted like:

public static <e> void fill(list<? super e> a_list, e an_object) { listiterator<e> an_iterator = (listiterator<e>) a_list.listiterator(); // ..doing stuff an_iterator.set(an_object); }

this gives unchecked cast warning, too. , thinking more, though still warning, safer cast like:

listiterator<object> an_iterator = (listiterator<object>)a_list.listiterator();

if generic type of list superclass of e, should safer cast listiterator list of objects, , not listiterator subclass of list's generic type, shouldn't it?

any advice appreciated...i don't think our instructor wanted involved, i'd understand generics better.

don't cast, , don't utilize ?. utilize type-parameterized methods; this.

public static <t> void reverse(list<t> a_list) { int list_size = a_list.size(); listiterator<t> left_to_right = a_list.listiterator(); listiterator<t> right_to_left = a_list.listiterator(list_size); t temp_variable; while(left_to_right.nextindex() < list_size / 2) { temp_variable = left_to_right.next(); left_to_right.set(right_to_left.previous()); right_to_left.set(temp_variable); } }

java generics

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -