Let's say I have a class Text
which implement an interface called Drawable
which is defined as follow :
public interface Drawable {
public void draw (DrawConfig drawConfig);
}
I want to have an object which acts like an array with items but which implements Drawable
as well, to be able to write drawables.draw(drawConfig)
and having it forward the call to all its children instead of having to do a for loop. So I first created a wrapper class which looks like this :
public class Drawables implements Drawable {
private final Array<Drawable> items = new Array<Drawable>();
public void add (final Drawable value) {
this.items.add(value);
}
@Override
public void draw (final DrawConfig drawConfig) {
for (final T item : this.items)
item.draw(drawConfig);
}
}
The first problem is that as it's a wrapper it doesn't have any of the Array
class methods and I have to manually add the ones I need (like add()
in the example above).
The second problem is that if I store only Text
objects in it, I can't write :
for (Text t : drawables)
t.setText("blablabla");
Which means I have to make another array and I'll end up with two arrays just for that. I want to avoid that so I thought about using genericity as the Array
class is generic and I turned my Drawables
class into this :
public class Drawables<T extends Drawable> extends Array<T> implements Drawable {
@Override
public void draw (final DrawConfig drawConfig) {
for (final T item : this.items) // Line 17
item.draw(drawConfig);
}
}
And now I can write :
Drawables<Text> drawables = new Drawables<Text>();
drawables.add(new Text());
drawables.add(new Text());
for (Text t : drawables)
t.setText("blablabla");
drawables.draw(drawConfig);
And it compiles !! Except that at runtime I get the following error :
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [La.b.c.ui.Drawable;
at a.b.c.Drawables.draw(Drawables.java:17)
at a.b.c.ui.components.Text_UseTest.render(Text_UseTest.java:80)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:215)
at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:120)
See the comment in my code for line 17.
What is the problem? And is it even possible to achieve what I want to do?
Array<T>
? It's not the built-inArray
class. – markspace Jul 7 '15 at 20:11Array<T>
class works, but there's some information in this StackOverflow question about dealing with arrays and generics: stackoverflow.com/questions/30388464/… – markspace Jul 7 '15 at 20:22