1

I have delared an Arraylist I want it to be a generic type.

ArrayList<T> locker = new ArrayList<T>();

Then I have a method add which needs also to be generic.

public <T extends Gear> boolean add(Gear item)
{

    locker.add(item);// this is giving me compile error => no suitable method found for add(Gear)
    return true;
}

how can I fix it, I am new to generic types as well.

3
  • How is your class declared? SomeClass<T extends Gear> ? Commented Nov 30, 2012 at 12:19
  • No matter how his class is declared, that bird don't fly. Commented Nov 30, 2012 at 12:20
  • yes the class is public class Locker<T extends Gear> { Commented Nov 30, 2012 at 12:20

2 Answers 2

5

You don't need to redeclare the generic type in your method if it already is in your class declaration:

public class Locker<T extends Gear> {
    private List<T> locker = new ArrayList<T>();

    public boolean add(T item) {
        locker.add(item);
        return true;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

You effectively have two generic parameter types defined. You have fallen into the classic trap of believing them to be the same, because they have the same name. Your first generic parameter (T) is at the class level, and can be used though out it, your second one (T extends Gear), is only applicable within the context of your add method.

You should probably change your class level parameter to T extends Gear, as pointed out by others, and remove the method level declaration.

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.