Reputation: 446
Couldn't find elsewhere, so here goes: I'm trying to create a generic class that contains an array holding objects of the given type. I have the rest of the code somewhat working, but for some reason I can't call my add
method with the type as a parameter. Here's the example:
public class Generic<E extends Item> {
private E[] items = (E[])(new Object[5]);
public void add(E neu) {
this.items[0] = neu;
}
public void problematic(Class<E> clazz) {
E neu = clazz.newInstance();
this.items.add(neu); // this line is the problem
}
}
The given error is "Cannot invoke Add(E) on the array type E[]"
Upvotes: 0
Views: 770
Reputation: 865
I guess instead of this.items.add(neu); use the method call add() this.add(neu);
But you are always adding to array[0] do you really want to do that ?
Also (E[])(new Object[5]); is an unsafe cast, as Jigar Joshi posted use an ArrayList instead A working example :
import java.util.ArrayList;
public class Generic <E extends Item> {
private ArrayList<E> items = new ArrayList<E>();
public void add(E neu) {
this.items.add(neu);
}
public void problematic(E clazz) {
this.add(clazz); // this line is the problem
}
}
class Item {}
The same with an Array of Object
public class Gen <E extends Item> {
private Object[] items = new Object[5];
private int itemCounter = 0;
public void add(E neu) {
if(itemCounter < items.length){
this.items[itemCounter] = neu;
itemCounter +=1;
}
}
public int length()
{
return itemCounter;
}
// testing the class
public static void main(String[] args)
{
Item t0 = new Item();
Item t1 = new Item();
Item t2 = new Item();
Item t3 = new Item();
Item t4 = new Item();
Item t5 = new Item();
Gen<Item> g = new Gen<Item>();
g.add(t0);
g.add(t1);
g.add(t2);
g.add(t3);
g.add(t4);
g.add(t5); // ignored
System.out.println(g.length());
}
}
class Item {}
Upvotes: 1
Reputation: 240898
array
don't have add()
method and so the compilation failure, change it to ArrayList
since it looks like you don't know the initial size of your array
Upvotes: 2