1

I have a task in which I have to implement an add() method for a custom generic list. In my code i have the following structure:

public abstract class MyGenericListAbstract<T> {
    protected transient T head;
    protected transient T tail;
    protected transient int size;

    ...
}

public final class MyEmptyList<T> extends MyGenericListAbstract {

private T[] list;

... 
public final void add(T e)
{
    this.getList()[this.size()] = (T) e;
}

...

private T[] getList()
{
    return this.list;
}

}

The problem I have for now is that when i try to do this:

public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        MyGenericListAbstract <Integer> list0   = new MyEmptyList();
        list0.add(new Integer(3));
    }

}

I get the following error:

enter image description here

and I cannot figure out why ...

Can anyone please help me?

The entire code is available here, also some documentation about the task here. If you spot some flaws, I would be happy to hear them!

Thanks!

5
  • 3
    Well, does MyGenericListAbstract have an add method? Commented Jul 5, 2014 at 20:51
  • 6
    This is unfortunate to start with: public final class MyEmptyList<T> extends MyGenericListAbstract. That's using the raw type MyGenericListAbstract. Try public final class MyEmptyList<T> extends MyGenericListAbstract<T>. Likewise you should probably use MyGenericListAbstract <Integer> list0 = new MyEmptyList<>();. Avoid raw types as far as possible. Commented Jul 5, 2014 at 20:51
  • @SotiriosDelimanolis no, it doesn't Commented Jul 5, 2014 at 20:53
  • Why are you doing (T) e; whereas e is already a type of T? Commented Jul 5, 2014 at 20:54
  • @Braj NetBeans suggested it Commented Jul 5, 2014 at 20:55

1 Answer 1

3

You hold a reference to MyGenericListAbstract <Integer> in list0 whereas it doesn't have an add method, as you previously said in a comment. The compiler doesn't see that method based on the list reference.

You should either change the reference type to MyEmptyList <Integer> or move the add(T e) method to MyGenericListAbstract class.

PS. The problem is not related with generics, it's just the basic Java inheritance principle.

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

Comments

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.