0

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[]"

1
  • 1
    It's an array, not an ArrayList. Commented Jul 23, 2014 at 20:17

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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 {}

2 Comments

Yeah, I'm kind of in a rush here, and I'm required to use an array. The example was just an oversimplification of course.
You can't create Arrays of generic types in java docs.oracle.com/javase/tutorial/java/generics/restrictions.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.