generics - Java: Instantiating array object of type T using a factory -
i instantiate array of type t such:
items = new t[maxque];
here code far, believe non-reflective approach:
interface myfactory<t> { t[] newobject(); } public class queue< t extends comparable<t> > { private int front; private int rear; private t[] items; private int maxque; private static final int max_items = 1000; public queue(myfactory<t> factory) { maxque = max_items + 1; front = maxque - 1; rear = maxque - 1; items = factory.newobject(); items = new t[maxque]; } }
the { items = factory.newobject(); } works , resolves compiler error not know how set size of array maxque using myfactory interface.
- how can declare array size of maxque?
on side note, while know definition of reflection in java, can please put and/or concept of factories in layman terms?
edit: found decent description of reflection here: what reflection , why useful?
i still bit unclear on when reflection should avoided , whether appropriate creating array.
you can create array of type t
extends, may or may not suitable use extended type (comparable
), or object
:
public class queue<t extends comparable<t> > { private int front; private int rear; private comparable[] items; private int maxque; private static final int max_items = 1000; public queue() { maxque = max_items + 1; front = maxque - 1; rear = maxque - 1; items = new comparable[maxque]; } }
when dequeuing or otherwise needing t
, cast t
@suppresswarnings("unchecked") public t dequeue(){ return (t)items[0]; }
both solutions of mine , immibis' covered here: https://stackoverflow.com/a/530289/360211
Comments
Post a Comment