Problem:
ArrayList<String>
means you want an array-backed list that can hold String
objects. This restricts the add
method to only accept strings. The mistake you are making is that you are passing other non-String
objects into the add
method.
Bad Answer 1:
The easy way out is to change it to ArrayList<Object>
, but this defeats the purpose of generics. The good thing is, you can now pass any object to the add
method. The bad thing is, you can now pass any object to the add
method.
Bad Answer 2:
You can create three ArrayList
objects instead:
ArrayList<Education> eduCategories [...]
ArrayList<Games> gameCategories [...]
ArrayList<Medical> medCategories [...]
But this is also bad, because now you have three lists.
Good Answer:
You only need one list. For this, you have to create a proper hierarchy:
-
Create an abstract class called
Category
:abstract class Category
-
Create three classes
Education
,Games
andMedical
, all extendingCategory
:class Education extends Category class Games extends Category class Medical extends Category
Then you can create your list as:
ArrayList<Category> categories = new ArrayList<Category>();
categories.add( new Education() );
categories.add( new Games() ) ;
categories.add( new Medical() ) ;
In this case, you’re restricting the add
method to accept only a Category
object. Since Education
, Games
and Medical
are all (by extension) Category
objects, they will be accepted. But the following will fail:
categories.add( "some string" ); //compilation error: String is not a Category
So now we are able to take full advantage of generics (compile-time type protection) while allowing different sub-classes to be accepted by the same list.
4
solved Why is it giving me the error “method ArrayList.add(String) is not applicable”?